array2d.c 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448
  1. #include "pocketpy/interpreter/array2d.h"
  2. #include "pocketpy/interpreter/vm.h"
  3. #include "pocketpy/interpreter/bindings.h"
  4. #include "pocketpy/pocketpy.h"
  5. #include <limits.h>
  6. static bool c11_array2d_like_is_valid(c11_array2d_like* self, int col, int row) {
  7. return col >= 0 && col < self->n_cols && row >= 0 && row < self->n_rows;
  8. }
  9. static py_Ref c11_array2d__get(c11_array2d* self, int col, int row) {
  10. return self->data + row * self->header.n_cols + col;
  11. }
  12. static bool c11_array2d__set(c11_array2d* self, int col, int row, py_Ref value) {
  13. self->data[row * self->header.n_cols + col] = *value;
  14. return true;
  15. }
  16. c11_array2d* c11_newarray2d(py_OutRef out, int n_cols, int n_rows) {
  17. int numel = n_cols * n_rows;
  18. c11_array2d* ud = py_newobject(out, tp_array2d, numel, sizeof(c11_array2d));
  19. ud->header.n_cols = n_cols;
  20. ud->header.n_rows = n_rows;
  21. ud->header.numel = numel;
  22. ud->header.f_get = (py_Ref (*)(c11_array2d_like*, int, int))c11_array2d__get;
  23. ud->header.f_set = (bool (*)(c11_array2d_like*, int, int, py_Ref))c11_array2d__set;
  24. ud->data = py_getslot(out, 0);
  25. return ud;
  26. }
  27. /* array2d_like bindings */
  28. static bool array2d_like_n_cols(int argc, py_Ref argv) {
  29. PY_CHECK_ARGC(1);
  30. c11_array2d_like* self = py_touserdata(argv);
  31. py_newint(py_retval(), self->n_cols);
  32. return true;
  33. }
  34. static bool array2d_like_n_rows(int argc, py_Ref argv) {
  35. PY_CHECK_ARGC(1);
  36. c11_array2d_like* self = py_touserdata(argv);
  37. py_newint(py_retval(), self->n_rows);
  38. return true;
  39. }
  40. static bool array2d_like_shape(int argc, py_Ref argv) {
  41. PY_CHECK_ARGC(1);
  42. c11_array2d_like* self = py_touserdata(argv);
  43. c11_vec2i shape;
  44. shape.x = self->n_cols;
  45. shape.y = self->n_rows;
  46. py_newvec2i(py_retval(), shape);
  47. return true;
  48. }
  49. static bool array2d_like_numel(int argc, py_Ref argv) {
  50. PY_CHECK_ARGC(1);
  51. c11_array2d_like* self = py_touserdata(argv);
  52. py_newint(py_retval(), self->numel);
  53. return true;
  54. }
  55. static bool array2d_like_is_valid(int argc, py_Ref argv) {
  56. c11_array2d_like* self = py_touserdata(argv);
  57. int col, row;
  58. if(argc == 2) {
  59. PY_CHECK_ARG_TYPE(1, tp_vec2i);
  60. c11_vec2i pos = py_tovec2i(py_arg(1));
  61. col = pos.x;
  62. row = pos.y;
  63. } else if(argc == 3) {
  64. PY_CHECK_ARG_TYPE(1, tp_int);
  65. PY_CHECK_ARG_TYPE(2, tp_int);
  66. col = py_toint(py_arg(1));
  67. row = py_toint(py_arg(2));
  68. } else {
  69. return TypeError("is_valid() expected 2 or 3 arguments");
  70. }
  71. py_newbool(py_retval(), c11_array2d_like_is_valid(self, col, row));
  72. return true;
  73. }
  74. static bool array2d_like_get(int argc, py_Ref argv) {
  75. PY_CHECK_ARG_TYPE(1, tp_int);
  76. PY_CHECK_ARG_TYPE(2, tp_int);
  77. py_Ref default_;
  78. c11_array2d_like* self = py_touserdata(argv);
  79. if(argc == 3) {
  80. default_ = py_None();
  81. } else if(argc == 4) {
  82. default_ = py_arg(3);
  83. } else {
  84. return TypeError("get() expected 2 or 3 arguments");
  85. }
  86. int col = py_toint(py_arg(1));
  87. int row = py_toint(py_arg(2));
  88. if(c11_array2d_like_is_valid(self, col, row)) {
  89. py_assign(py_retval(), self->f_get(self, col, row));
  90. } else {
  91. py_assign(py_retval(), default_);
  92. }
  93. return true;
  94. }
  95. static bool array2d_like_index(int argc, py_Ref argv) {
  96. PY_CHECK_ARGC(2);
  97. c11_array2d_like* self = py_touserdata(argv);
  98. py_Ref value = py_arg(1);
  99. for(int j = 0; j < self->n_rows; j++) {
  100. for(int i = 0; i < self->n_cols; i++) {
  101. py_Ref item = self->f_get(self, i, j);
  102. int code = py_equal(item, value);
  103. if(code == -1) return false;
  104. if(code == 1) {
  105. py_newvec2i(py_retval(),
  106. (c11_vec2i){
  107. {i, j}
  108. });
  109. return true;
  110. }
  111. }
  112. }
  113. return ValueError("value not found");
  114. }
  115. static bool array2d_like_render(int argc, py_Ref argv) {
  116. PY_CHECK_ARGC(1);
  117. c11_sbuf buf;
  118. c11_sbuf__ctor(&buf);
  119. c11_array2d_like* self = py_touserdata(argv);
  120. for(int j = 0; j < self->n_rows; j++) {
  121. for(int i = 0; i < self->n_cols; i++) {
  122. py_Ref item = self->f_get(self, i, j);
  123. if(!py_str(item)) {
  124. c11_sbuf__dtor(&buf);
  125. return false;
  126. }
  127. c11_sbuf__write_sv(&buf, py_tosv(py_retval()));
  128. }
  129. if(j < self->n_rows - 1) c11_sbuf__write_char(&buf, '\n');
  130. }
  131. c11_sbuf__py_submit(&buf, py_retval());
  132. return true;
  133. }
  134. void c11_color32_premult(c11_color32* color);
  135. static bool array2d_like_render_with_color(int argc, py_Ref argv) {
  136. PY_CHECK_ARGC(3);
  137. c11_sbuf buf;
  138. c11_sbuf__ctor(&buf);
  139. c11_array2d_like* self = py_touserdata(argv);
  140. if(!py_checkinstance(py_arg(1), tp_array2d_like)) return false;
  141. if(!py_checkinstance(py_arg(2), tp_array2d_like)) return false;
  142. c11_array2d_like* fg_colors = py_touserdata(py_arg(1));
  143. c11_array2d_like* bg_colors = py_touserdata(py_arg(2));
  144. c11_color32 curr_fg, curr_bg;
  145. curr_fg.u32 = 0;
  146. curr_bg.u32 = 0;
  147. for(int j = 0; j < self->n_rows; j++) {
  148. for(int i = 0; i < self->n_cols; i++) {
  149. py_Ref item = self->f_get(self, i, j);
  150. if(!py_str(item)) {
  151. c11_sbuf__dtor(&buf);
  152. return false;
  153. }
  154. py_Ref fg_item = fg_colors->f_get(fg_colors, i, j);
  155. py_Ref bg_item = bg_colors->f_get(bg_colors, i, j);
  156. c11_color32 new_fg, new_bg;
  157. if(py_isnone(fg_item)) {
  158. new_fg.u32 = 0;
  159. } else {
  160. if(!py_checktype(fg_item, tp_color32)) {
  161. c11_sbuf__dtor(&buf);
  162. return false;
  163. }
  164. new_fg = py_tocolor32(fg_item);
  165. }
  166. if(py_isnone(bg_item)) {
  167. new_bg.u32 = 0;
  168. } else {
  169. if(!py_checktype(bg_item, tp_color32)) {
  170. c11_sbuf__dtor(&buf);
  171. return false;
  172. }
  173. new_bg = py_tocolor32(bg_item);
  174. }
  175. if(curr_fg.u32 != new_fg.u32 || curr_bg.u32 != new_bg.u32) {
  176. if(curr_fg.u32 != 0 || curr_bg.u32 != 0) c11_sbuf__write_cstr(&buf, "\x1b[0m");
  177. curr_fg = new_fg;
  178. curr_bg = new_bg;
  179. if(curr_fg.u32 != 0) {
  180. c11_color32_premult(&curr_fg);
  181. pk_sprintf(&buf, "\x1b[38;2;%d;%d;%dm", curr_fg.r, curr_fg.g, curr_fg.b);
  182. }
  183. if(curr_bg.u32 != 0) {
  184. c11_color32_premult(&curr_bg);
  185. pk_sprintf(&buf, "\x1b[48;2;%d;%d;%dm", curr_bg.r, curr_bg.g, curr_bg.b);
  186. }
  187. }
  188. c11_sbuf__write_sv(&buf, py_tosv(py_retval()));
  189. }
  190. // newline
  191. if(j < self->n_rows - 1) {
  192. curr_fg.u32 = 0;
  193. curr_bg.u32 = 0;
  194. c11_sbuf__write_cstr(&buf, "\x1b[0m\n");
  195. } else {
  196. c11_sbuf__write_cstr(&buf, "\x1b[0m");
  197. }
  198. }
  199. c11_sbuf__py_submit(&buf, py_retval());
  200. return true;
  201. }
  202. static bool array2d_like_all(int argc, py_Ref argv) {
  203. PY_CHECK_ARGC(1);
  204. c11_array2d_like* self = py_touserdata(argv);
  205. for(int j = 0; j < self->n_rows; j++) {
  206. for(int i = 0; i < self->n_cols; i++) {
  207. py_Ref item = self->f_get(self, i, j);
  208. if(!py_checkbool(item)) return false;
  209. if(!py_tobool(item)) {
  210. py_newbool(py_retval(), false);
  211. return true;
  212. }
  213. }
  214. }
  215. py_newbool(py_retval(), true);
  216. return true;
  217. }
  218. static bool array2d_like_any(int argc, py_Ref argv) {
  219. PY_CHECK_ARGC(1);
  220. c11_array2d_like* self = py_touserdata(argv);
  221. for(int j = 0; j < self->n_rows; j++) {
  222. for(int i = 0; i < self->n_cols; i++) {
  223. py_Ref item = self->f_get(self, i, j);
  224. if(!py_checkbool(item)) return false;
  225. if(py_tobool(item)) {
  226. py_newbool(py_retval(), true);
  227. return true;
  228. }
  229. }
  230. }
  231. py_newbool(py_retval(), false);
  232. return true;
  233. }
  234. static bool array2d_like_map(int argc, py_Ref argv) {
  235. // def map(self, f: Callable[[T], Any]) -> 'array2d': ...
  236. PY_CHECK_ARGC(2);
  237. c11_array2d_like* self = py_touserdata(argv);
  238. py_Ref f = py_arg(1);
  239. c11_array2d* res = c11_newarray2d(py_pushtmp(), self->n_cols, self->n_rows);
  240. for(int j = 0; j < self->n_rows; j++) {
  241. for(int i = 0; i < self->n_cols; i++) {
  242. py_Ref item = self->f_get(self, i, j);
  243. if(!py_call(f, 1, item)) return false;
  244. res->data[j * self->n_cols + i] = *py_retval();
  245. }
  246. }
  247. py_assign(py_retval(), py_peek(-1));
  248. py_pop();
  249. return true;
  250. }
  251. static bool array2d_like_apply(int argc, py_Ref argv) {
  252. // def apply_(self, f: Callable[[T], T]) -> None: ...
  253. PY_CHECK_ARGC(2);
  254. c11_array2d_like* self = py_touserdata(argv);
  255. py_Ref f = py_arg(1);
  256. for(int j = 0; j < self->n_rows; j++) {
  257. for(int i = 0; i < self->n_cols; i++) {
  258. py_Ref item = self->f_get(self, i, j);
  259. if(!py_call(f, 1, item)) return false;
  260. bool ok = self->f_set(self, i, j, py_retval());
  261. if(!ok) return false;
  262. }
  263. }
  264. py_newnone(py_retval());
  265. return true;
  266. }
  267. static bool _check_same_shape(int colA, int rowA, int colB, int rowB) {
  268. if(colA != colB || rowA != rowB) {
  269. const char* fmt = "expected the same shape: (%d, %d) != (%d, %d)";
  270. return ValueError(fmt, colA, rowA, colB, rowB);
  271. }
  272. return true;
  273. }
  274. static bool _array2d_like_check_same_shape(c11_array2d_like* self, c11_array2d_like* other) {
  275. return _check_same_shape(self->n_cols, self->n_rows, other->n_cols, other->n_rows);
  276. }
  277. static bool _array2d_like_broadcasted_zip_with(int argc, py_Ref argv, py_Name op, py_Name rop) {
  278. PY_CHECK_ARGC(2);
  279. c11_array2d_like* self = py_touserdata(argv);
  280. c11_array2d_like* other;
  281. if(py_isinstance(py_arg(1), tp_array2d_like)) {
  282. other = py_touserdata(py_arg(1));
  283. if(!_array2d_like_check_same_shape(self, other)) return false;
  284. } else {
  285. other = NULL;
  286. }
  287. c11_array2d* res = c11_newarray2d(py_pushtmp(), self->n_cols, self->n_rows);
  288. for(int j = 0; j < self->n_rows; j++) {
  289. for(int i = 0; i < self->n_cols; i++) {
  290. py_Ref lhs = self->f_get(self, i, j);
  291. py_Ref rhs;
  292. if(other != NULL) {
  293. rhs = other->f_get(other, i, j);
  294. } else {
  295. rhs = py_arg(1); // broadcast
  296. }
  297. if(!py_binaryop(lhs, rhs, op, rop)) return false;
  298. c11_array2d__set(res, i, j, py_retval());
  299. }
  300. }
  301. py_assign(py_retval(), py_peek(-1));
  302. py_pop();
  303. return true;
  304. }
  305. static bool array2d_like_zip_with(int argc, py_Ref argv) {
  306. PY_CHECK_ARGC(3);
  307. c11_array2d_like* self = py_touserdata(argv);
  308. if(!py_checkinstance(py_arg(1), tp_array2d_like)) return false;
  309. c11_array2d_like* other = py_touserdata(py_arg(1));
  310. py_Ref f = py_arg(2);
  311. if(!_array2d_like_check_same_shape(self, other)) return false;
  312. c11_array2d* res = c11_newarray2d(py_pushtmp(), self->n_cols, self->n_rows);
  313. for(int j = 0; j < self->n_rows; j++) {
  314. for(int i = 0; i < self->n_cols; i++) {
  315. py_push(f);
  316. py_pushnil();
  317. py_push(self->f_get(self, i, j));
  318. py_push(other->f_get(other, i, j));
  319. if(!py_vectorcall(2, 0)) return false;
  320. c11_array2d__set(res, i, j, py_retval());
  321. }
  322. }
  323. py_assign(py_retval(), py_peek(-1));
  324. py_pop();
  325. return true;
  326. }
  327. #define DEF_ARRAY2D_LIKE__MAGIC_ZIP_WITH(name, op, rop) \
  328. static bool array2d_like##name(int argc, py_Ref argv) { \
  329. return _array2d_like_broadcasted_zip_with(argc, argv, op, rop); \
  330. }
  331. DEF_ARRAY2D_LIKE__MAGIC_ZIP_WITH(__le__, __le__, __ge__)
  332. DEF_ARRAY2D_LIKE__MAGIC_ZIP_WITH(__lt__, __lt__, __gt__)
  333. DEF_ARRAY2D_LIKE__MAGIC_ZIP_WITH(__ge__, __ge__, __le__)
  334. DEF_ARRAY2D_LIKE__MAGIC_ZIP_WITH(__gt__, __gt__, __lt__)
  335. DEF_ARRAY2D_LIKE__MAGIC_ZIP_WITH(__eq__, __eq__, __eq__)
  336. DEF_ARRAY2D_LIKE__MAGIC_ZIP_WITH(__ne__, __ne__, __ne__)
  337. DEF_ARRAY2D_LIKE__MAGIC_ZIP_WITH(__add__, __add__, __radd__)
  338. DEF_ARRAY2D_LIKE__MAGIC_ZIP_WITH(__sub__, __sub__, __rsub__)
  339. DEF_ARRAY2D_LIKE__MAGIC_ZIP_WITH(__mul__, __mul__, __rmul__)
  340. DEF_ARRAY2D_LIKE__MAGIC_ZIP_WITH(__truediv__, __truediv__, __rtruediv__)
  341. DEF_ARRAY2D_LIKE__MAGIC_ZIP_WITH(__floordiv__, __floordiv__, __rfloordiv__)
  342. DEF_ARRAY2D_LIKE__MAGIC_ZIP_WITH(__mod__, __mod__, __rmod__)
  343. DEF_ARRAY2D_LIKE__MAGIC_ZIP_WITH(__pow__, __pow__, __rpow__)
  344. DEF_ARRAY2D_LIKE__MAGIC_ZIP_WITH(__and__, __and__, 0)
  345. DEF_ARRAY2D_LIKE__MAGIC_ZIP_WITH(__or__, __or__, 0)
  346. DEF_ARRAY2D_LIKE__MAGIC_ZIP_WITH(__xor__, __xor__, 0)
  347. #undef DEF_ARRAY2D_LIKE__MAGIC_ZIP_WITH
  348. static bool array2d_like__invert__(int argc, py_Ref argv) {
  349. PY_CHECK_ARGC(1);
  350. c11_array2d_like* self = py_touserdata(argv);
  351. c11_array2d* res = c11_newarray2d(py_pushtmp(), self->n_cols, self->n_rows);
  352. for(int j = 0; j < self->n_rows; j++) {
  353. for(int i = 0; i < self->n_cols; i++) {
  354. py_Ref item = self->f_get(self, i, j);
  355. if(item->type == tp_bool) {
  356. py_Ref p_out = c11_array2d__get(res, i, j);
  357. py_newbool(p_out, !py_tobool(item));
  358. } else {
  359. if(!pk_callmagic(__invert__, 1, item)) return false;
  360. c11_array2d__set(res, i, j, py_retval());
  361. }
  362. }
  363. }
  364. py_assign(py_retval(), py_peek(-1));
  365. py_pop();
  366. return true;
  367. }
  368. static bool array2d_like_copy(int argc, py_Ref argv) {
  369. // def copy(self) -> 'array2d': ...
  370. PY_CHECK_ARGC(1);
  371. c11_array2d_like* self = py_touserdata(argv);
  372. c11_array2d* res = c11_newarray2d(py_retval(), self->n_cols, self->n_rows);
  373. for(int j = 0; j < self->n_rows; j++) {
  374. for(int i = 0; i < self->n_cols; i++) {
  375. py_Ref item = self->f_get(self, i, j);
  376. res->data[j * self->n_cols + i] = *item;
  377. }
  378. }
  379. return true;
  380. }
  381. static bool array2d_like_tolist(int argc, py_Ref argv) {
  382. PY_CHECK_ARGC(1);
  383. c11_array2d_like* self = py_touserdata(argv);
  384. py_newlistn(py_retval(), self->n_rows);
  385. for(int j = 0; j < self->n_rows; j++) {
  386. py_Ref row_j = py_list_getitem(py_retval(), j);
  387. py_newlistn(row_j, self->n_cols);
  388. for(int i = 0; i < self->n_cols; i++) {
  389. py_Ref item = self->f_get(self, i, j);
  390. py_list_setitem(row_j, i, item);
  391. }
  392. }
  393. return true;
  394. }
  395. static bool array2d_like__iter__(int argc, py_Ref argv) {
  396. PY_CHECK_ARGC(1);
  397. c11_array2d_like* self = py_touserdata(argv);
  398. c11_array2d_like_iterator* ud =
  399. py_newobject(py_retval(), tp_array2d_like_iterator, 1, sizeof(c11_array2d_like_iterator));
  400. py_setslot(py_retval(), 0, argv); // keep the array alive
  401. ud->array = self;
  402. ud->j = 0;
  403. ud->i = 0;
  404. return true;
  405. }
  406. static bool array2d_like__repr__(int argc, py_Ref argv) {
  407. PY_CHECK_ARGC(1);
  408. c11_array2d_like* self = py_touserdata(argv);
  409. char buf[256];
  410. snprintf(buf,
  411. sizeof(buf),
  412. "%s(%d, %d)",
  413. py_tpname(py_typeof(argv)),
  414. self->n_cols,
  415. self->n_rows);
  416. py_newstr(py_retval(), buf);
  417. return true;
  418. }
  419. #define HANDLE_SLICE() \
  420. int start_col, stop_col, step_col; \
  421. int start_row, stop_row, step_row; \
  422. if(!pk__parse_int_slice(x, self->n_cols, &start_col, &stop_col, &step_col)) return false; \
  423. if(!pk__parse_int_slice(y, self->n_rows, &start_row, &stop_row, &step_row)) return false; \
  424. if(step_col != 1 || step_row != 1) return ValueError("slice step must be 1"); \
  425. int slice_width = stop_col - start_col; \
  426. int slice_height = stop_row - start_row;
  427. static bool _array2d_like_IndexError(c11_array2d_like* self, int col, int row) {
  428. return IndexError("(%d, %d) is not a valid index of array2d_like(%d, %d)",
  429. col,
  430. row,
  431. self->n_cols,
  432. self->n_rows);
  433. }
  434. static py_Ref c11_array2d_view__get(c11_array2d_view* self, int col, int row) {
  435. return self->f_get(self->ctx, col + self->origin.x, row + self->origin.y);
  436. }
  437. static bool c11_array2d_view__set(c11_array2d_view* self, int col, int row, py_Ref value) {
  438. return self->f_set(self->ctx, col + self->origin.x, row + self->origin.y, value);
  439. }
  440. static c11_array2d_view* _array2d_view__new(py_OutRef out,
  441. py_Ref keepalive,
  442. int start_col,
  443. int start_row,
  444. int width,
  445. int height) {
  446. c11_array2d_view* res = py_newobject(out, tp_array2d_view, 1, sizeof(c11_array2d_view));
  447. if(width <= 0 || height <= 0) {
  448. ValueError("width and height must be positive");
  449. return NULL;
  450. }
  451. res->header.n_cols = width;
  452. res->header.n_rows = height;
  453. res->header.numel = width * height;
  454. res->header.f_get = (py_Ref (*)(c11_array2d_like*, int, int))c11_array2d_view__get;
  455. res->header.f_set = (bool (*)(c11_array2d_like*, int, int, py_Ref))c11_array2d_view__set;
  456. res->origin.x = start_col;
  457. res->origin.y = start_row;
  458. py_setslot(out, 0, keepalive);
  459. return res;
  460. }
  461. static bool _array2d_view(py_OutRef out,
  462. py_Ref keepalive,
  463. c11_array2d_like* array,
  464. int start_col,
  465. int start_row,
  466. int width,
  467. int height) {
  468. c11_array2d_view* res = _array2d_view__new(out, keepalive, start_col, start_row, width, height);
  469. if(res == NULL) return false;
  470. res->ctx = array;
  471. res->f_get = (py_Ref (*)(void*, int, int))array->f_get;
  472. res->f_set = (bool (*)(void*, int, int, py_Ref))array->f_set;
  473. return true;
  474. }
  475. static bool _chunked_array2d_view(py_OutRef out,
  476. py_Ref keepalive,
  477. c11_chunked_array2d* array,
  478. int start_col,
  479. int start_row,
  480. int width,
  481. int height) {
  482. c11_array2d_view* res = _array2d_view__new(out, keepalive, start_col, start_row, width, height);
  483. if(res == NULL) return false;
  484. res->ctx = array;
  485. res->f_get = (py_Ref (*)(void*, int, int))c11_chunked_array2d__get;
  486. res->f_set = (bool (*)(void*, int, int, py_Ref))c11_chunked_array2d__set;
  487. return true;
  488. }
  489. static bool array2d_like__getitem__(int argc, py_Ref argv) {
  490. PY_CHECK_ARGC(2);
  491. c11_array2d_like* self = py_touserdata(argv);
  492. if(argv[1].type == tp_vec2i) {
  493. c11_vec2i pos = py_tovec2i(&argv[1]);
  494. if(c11_array2d_like_is_valid(self, pos.x, pos.y)) {
  495. py_assign(py_retval(), self->f_get(self, pos.x, pos.y));
  496. return true;
  497. }
  498. return _array2d_like_IndexError(self, pos.x, pos.y);
  499. }
  500. if(py_isinstance(&argv[1], tp_array2d_like)) {
  501. c11_array2d_like* mask = py_touserdata(&argv[1]);
  502. if(!_array2d_like_check_same_shape(self, mask)) return false;
  503. py_newlist(py_retval());
  504. for(int j = 0; j < self->n_rows; j++) {
  505. for(int i = 0; i < self->n_cols; i++) {
  506. py_Ref item = self->f_get(self, i, j);
  507. py_Ref cond = mask->f_get(mask, i, j);
  508. if(!py_checkbool(cond)) return false;
  509. if(py_tobool(cond)) py_list_append(py_retval(), item);
  510. }
  511. }
  512. return true;
  513. }
  514. PY_CHECK_ARG_TYPE(1, tp_tuple);
  515. if(py_tuple_len(&argv[1]) != 2) return TypeError("expected a tuple of 2 elements");
  516. py_Ref x = py_tuple_getitem(&argv[1], 0);
  517. py_Ref y = py_tuple_getitem(&argv[1], 1);
  518. if(py_isint(x) && py_isint(y)) {
  519. int col = py_toint(x);
  520. int row = py_toint(y);
  521. if(c11_array2d_like_is_valid(self, col, row)) {
  522. py_assign(py_retval(), self->f_get(self, col, row));
  523. return true;
  524. }
  525. return _array2d_like_IndexError(self, col, row);
  526. }
  527. bool _1 = py_istype(x, tp_slice) && py_istype(y, tp_slice);
  528. bool _2 = py_istype(x, tp_int) && py_istype(y, tp_slice);
  529. bool _3 = py_istype(x, tp_slice) && py_istype(y, tp_int);
  530. if(_1 || _2 || _3) {
  531. HANDLE_SLICE();
  532. return _array2d_view(py_retval(),
  533. argv,
  534. self,
  535. start_col,
  536. start_row,
  537. slice_width,
  538. slice_height);
  539. }
  540. return TypeError("expected tuple[int, int] or tuple[slice, slice]");
  541. }
  542. static bool array2d_like__setitem__(int argc, py_Ref argv) {
  543. PY_CHECK_ARGC(3);
  544. c11_array2d_like* self = py_touserdata(argv);
  545. py_Ref value = &argv[2];
  546. if(argv[1].type == tp_vec2i) {
  547. c11_vec2i pos = py_tovec2i(&argv[1]);
  548. if(c11_array2d_like_is_valid(self, pos.x, pos.y)) {
  549. bool ok = self->f_set(self, pos.x, pos.y, value);
  550. if(!ok) return false;
  551. py_newnone(py_retval());
  552. return true;
  553. }
  554. return _array2d_like_IndexError(self, pos.x, pos.y);
  555. }
  556. if(py_isinstance(&argv[1], tp_array2d_like)) {
  557. c11_array2d_like* mask = py_touserdata(&argv[1]);
  558. if(!_array2d_like_check_same_shape(self, mask)) return false;
  559. for(int j = 0; j < self->n_rows; j++) {
  560. for(int i = 0; i < self->n_cols; i++) {
  561. py_Ref cond = mask->f_get(mask, i, j);
  562. if(!py_checkbool(cond)) return false;
  563. if(py_tobool(cond)) {
  564. bool ok = self->f_set(self, i, j, value);
  565. if(!ok) return false;
  566. }
  567. }
  568. }
  569. py_newnone(py_retval());
  570. return true;
  571. }
  572. PY_CHECK_ARG_TYPE(1, tp_tuple);
  573. if(py_tuple_len(py_arg(1)) != 2) return TypeError("expected a tuple of 2 elements");
  574. py_Ref x = py_tuple_getitem(py_arg(1), 0);
  575. py_Ref y = py_tuple_getitem(py_arg(1), 1);
  576. if(py_isint(x) && py_isint(y)) {
  577. int col = py_toint(x);
  578. int row = py_toint(y);
  579. if(c11_array2d_like_is_valid(self, col, row)) {
  580. bool ok = self->f_set(self, col, row, value);
  581. if(!ok) return false;
  582. py_newnone(py_retval());
  583. return true;
  584. }
  585. return _array2d_like_IndexError(self, col, row);
  586. }
  587. bool _1 = py_istype(x, tp_slice) && py_istype(y, tp_slice);
  588. bool _2 = py_istype(x, tp_int) && py_istype(y, tp_slice);
  589. bool _3 = py_istype(x, tp_slice) && py_istype(y, tp_int);
  590. if(_1 || _2 || _3) {
  591. HANDLE_SLICE();
  592. if(py_isinstance(value, tp_array2d_like)) {
  593. c11_array2d_like* values = py_touserdata(value);
  594. if(!_check_same_shape(slice_width, slice_height, values->n_cols, values->n_rows))
  595. return false;
  596. for(int j = 0; j < slice_height; j++) {
  597. for(int i = 0; i < slice_width; i++) {
  598. py_Ref item = values->f_get(values, i, j);
  599. bool ok = self->f_set(self, start_col + i, start_row + j, item);
  600. if(!ok) return false;
  601. }
  602. }
  603. } else {
  604. for(int j = 0; j < slice_height; j++) {
  605. for(int i = 0; i < slice_width; i++) {
  606. bool ok = self->f_set(self, start_col + i, start_row + j, value);
  607. if(!ok) return false;
  608. }
  609. }
  610. }
  611. py_newnone(py_retval());
  612. return true;
  613. }
  614. return TypeError("expected tuple[int, int] or tuple[slice, slice]");
  615. }
  616. // count(self, value: T) -> int
  617. static bool array2d_like_count(int argc, py_Ref argv) {
  618. PY_CHECK_ARGC(2);
  619. c11_array2d_like* self = py_touserdata(argv);
  620. int count = 0;
  621. for(int j = 0; j < self->n_rows; j++) {
  622. for(int i = 0; i < self->n_cols; i++) {
  623. int code = py_equal(self->f_get(self, i, j), py_arg(1));
  624. if(code == -1) return false;
  625. count += code;
  626. }
  627. }
  628. py_newint(py_retval(), count);
  629. return true;
  630. }
  631. // get_bounding_rect(self, value: T) -> tuple[int, int, int, int]
  632. static bool array2d_like_get_bounding_rect(int argc, py_Ref argv) {
  633. PY_CHECK_ARGC(2);
  634. c11_array2d_like* self = py_touserdata(argv);
  635. py_Ref value = py_arg(1);
  636. int left = self->n_cols;
  637. int top = self->n_rows;
  638. int right = 0;
  639. int bottom = 0;
  640. for(int j = 0; j < self->n_rows; j++) {
  641. for(int i = 0; i < self->n_cols; i++) {
  642. py_Ref item = self->f_get(self, i, j);
  643. int res = py_equal(item, value);
  644. if(res == -1) return false;
  645. if(res == 1) {
  646. left = c11__min(left, i);
  647. top = c11__min(top, j);
  648. right = c11__max(right, i);
  649. bottom = c11__max(bottom, j);
  650. }
  651. }
  652. }
  653. int width = right - left + 1;
  654. int height = bottom - top + 1;
  655. if(width <= 0 || height <= 0) {
  656. return ValueError("value not found");
  657. } else {
  658. py_TValue* data = py_newtuple(py_retval(), 4);
  659. py_newint(&data[0], left);
  660. py_newint(&data[1], top);
  661. py_newint(&data[2], width);
  662. py_newint(&data[3], height);
  663. }
  664. return true;
  665. }
  666. // count_neighbors(self, value: T, neighborhood: Neighborhood) -> array2d[int]
  667. static bool array2d_like_count_neighbors(int argc, py_Ref argv) {
  668. PY_CHECK_ARGC(3);
  669. c11_array2d_like* self = py_touserdata(argv);
  670. c11_array2d* res = c11_newarray2d(py_pushtmp(), self->n_cols, self->n_rows);
  671. py_Ref value = py_arg(1);
  672. const char* neighborhood = py_tostr(py_arg(2));
  673. const static c11_vec2i Moore[] = {
  674. {{-1, -1}},
  675. {{0, -1}},
  676. {{1, -1}},
  677. {{-1, 0}},
  678. {{1, 0}},
  679. {{-1, 1}},
  680. {{0, 1}},
  681. {{1, 1}},
  682. };
  683. const static c11_vec2i von_Neumann[] = {
  684. {{0, -1}},
  685. {{-1, 0}},
  686. {{1, 0}},
  687. {{0, 1}},
  688. };
  689. const c11_vec2i* offsets;
  690. int n_offsets;
  691. if(strcmp(neighborhood, "Moore") == 0) {
  692. offsets = Moore;
  693. n_offsets = c11__count_array(Moore);
  694. } else if(strcmp(neighborhood, "von Neumann") == 0) {
  695. offsets = von_Neumann;
  696. n_offsets = c11__count_array(von_Neumann);
  697. } else {
  698. return ValueError("neighborhood must be 'Moore' or 'von Neumann'");
  699. }
  700. for(int j = 0; j < self->n_rows; j++) {
  701. for(int i = 0; i < self->n_cols; i++) {
  702. py_i64 count = 0;
  703. for(int k = 0; k < n_offsets; k++) {
  704. int x = i + offsets[k].x;
  705. int y = j + offsets[k].y;
  706. if(x >= 0 && x < self->n_cols && y >= 0 && y < self->n_rows) {
  707. py_Ref item = self->f_get(self, x, y);
  708. int code = py_equal(item, value);
  709. if(code == -1) return false;
  710. count += code;
  711. }
  712. }
  713. py_newint(c11_array2d__get(res, i, j), count);
  714. }
  715. }
  716. py_assign(py_retval(), py_peek(-1));
  717. py_pop();
  718. return true;
  719. }
  720. // convolve(self: array2d_like[int], kernel: array2d_like[int], padding: int) -> array2d[int]
  721. static bool array2d_like_convolve(int argc, py_Ref argv) {
  722. PY_CHECK_ARGC(3);
  723. if(!py_checkinstance(&argv[1], tp_array2d_like)) return false;
  724. PY_CHECK_ARG_TYPE(2, tp_int);
  725. c11_array2d_like* self = py_touserdata(&argv[0]);
  726. c11_array2d_like* kernel = py_touserdata(&argv[1]);
  727. int padding = py_toint(py_arg(2));
  728. if(kernel->n_cols != kernel->n_rows) return ValueError("kernel must be square");
  729. int ksize = kernel->n_cols;
  730. if(ksize % 2 == 0) return ValueError("kernel size must be odd");
  731. int ksize_half = ksize / 2;
  732. c11_array2d* res = c11_newarray2d(py_pushtmp(), self->n_cols, self->n_rows);
  733. for(int j = 0; j < self->n_rows; j++) {
  734. for(int i = 0; i < self->n_cols; i++) {
  735. py_i64 sum = 0;
  736. for(int jj = 0; jj < ksize; jj++) {
  737. for(int ii = 0; ii < ksize; ii++) {
  738. int x = i + ii - ksize_half;
  739. int y = j + jj - ksize_half;
  740. py_i64 _0, _1;
  741. if(x < 0 || x >= self->n_cols || y < 0 || y >= self->n_rows) {
  742. _0 = padding;
  743. } else {
  744. py_Ref item = self->f_get(self, x, y);
  745. if(!py_checkint(item)) return false;
  746. _0 = py_toint(item);
  747. }
  748. py_Ref kitem = kernel->f_get(kernel, ii, jj);
  749. if(!py_checkint(kitem)) return false;
  750. _1 = py_toint(kitem);
  751. sum += _0 * _1;
  752. }
  753. }
  754. py_newint(c11_array2d__get(res, i, j), sum);
  755. }
  756. }
  757. py_assign(py_retval(), py_peek(-1));
  758. py_pop();
  759. return true;
  760. }
  761. #undef HANDLE_SLICE
  762. static void register_array2d_like(py_Ref mod) {
  763. py_Type type = py_newtype("array2d_like", tp_object, mod, NULL);
  764. assert(type == tp_array2d_like);
  765. py_bindproperty(type, "n_cols", array2d_like_n_cols, NULL);
  766. py_bindproperty(type, "n_rows", array2d_like_n_rows, NULL);
  767. py_bindproperty(type, "width", array2d_like_n_cols, NULL);
  768. py_bindproperty(type, "height", array2d_like_n_rows, NULL);
  769. py_bindproperty(type, "shape", array2d_like_shape, NULL);
  770. py_bindproperty(type, "numel", array2d_like_numel, NULL);
  771. py_bindmethod(type, "is_valid", array2d_like_is_valid);
  772. py_bindmethod(type, "get", array2d_like_get);
  773. py_bindmethod(type, "index", array2d_like_index);
  774. py_bindmethod(type, "render", array2d_like_render);
  775. py_bindmethod(type, "render_with_color", array2d_like_render_with_color);
  776. py_bindmethod(type, "all", array2d_like_all);
  777. py_bindmethod(type, "any", array2d_like_any);
  778. py_bindmethod(type, "map", array2d_like_map);
  779. py_bindmethod(type, "apply", array2d_like_apply);
  780. py_bindmethod(type, "zip_with", array2d_like_zip_with);
  781. py_bindmethod(type, "copy", array2d_like_copy);
  782. py_bindmethod(type, "tolist", array2d_like_tolist);
  783. py_bindmagic(type, __le__, array2d_like__le__);
  784. py_bindmagic(type, __lt__, array2d_like__lt__);
  785. py_bindmagic(type, __ge__, array2d_like__ge__);
  786. py_bindmagic(type, __gt__, array2d_like__gt__);
  787. py_bindmagic(type, __eq__, array2d_like__eq__);
  788. py_bindmagic(type, __ne__, array2d_like__ne__);
  789. py_bindmagic(type, __add__, array2d_like__add__);
  790. py_bindmagic(type, __sub__, array2d_like__sub__);
  791. py_bindmagic(type, __mul__, array2d_like__mul__);
  792. py_bindmagic(type, __truediv__, array2d_like__truediv__);
  793. py_bindmagic(type, __floordiv__, array2d_like__floordiv__);
  794. py_bindmagic(type, __mod__, array2d_like__mod__);
  795. py_bindmagic(type, __pow__, array2d_like__pow__);
  796. py_bindmagic(type, __and__, array2d_like__and__);
  797. py_bindmagic(type, __or__, array2d_like__or__);
  798. py_bindmagic(type, __xor__, array2d_like__xor__);
  799. py_bindmagic(type, __invert__, array2d_like__invert__);
  800. py_bindmagic(type, __iter__, array2d_like__iter__);
  801. py_bindmagic(type, __repr__, array2d_like__repr__);
  802. py_bindmagic(type, __getitem__, array2d_like__getitem__);
  803. py_bindmagic(type, __setitem__, array2d_like__setitem__);
  804. py_bindmethod(type, "count", array2d_like_count);
  805. py_bindmethod(type, "get_bounding_rect", array2d_like_get_bounding_rect);
  806. py_bindmethod(type, "count_neighbors", array2d_like_count_neighbors);
  807. py_bindmethod(type, "convolve", array2d_like_convolve);
  808. const char* scc =
  809. "\ndef get_connected_components(self, value: T, neighborhood: Neighborhood) -> tuple[array2d[int], int]:\n from collections import deque\n from vmath import vec2i\n\n DIRS = [vec2i.LEFT, vec2i.RIGHT, vec2i.UP, vec2i.DOWN]\n assert neighborhood in ['Moore', 'von Neumann']\n\n if neighborhood == 'Moore':\n DIRS.extend([\n vec2i.LEFT+vec2i.UP,\n vec2i.RIGHT+vec2i.UP,\n vec2i.LEFT+vec2i.DOWN,\n vec2i.RIGHT+vec2i.DOWN\n ])\n\n visited = array2d[int](self.width, self.height, default=0)\n queue = deque()\n count = 0\n for y in range(self.height):\n for x in range(self.width):\n if visited[x, y] or self[x, y] != value:\n continue\n count += 1\n queue.append((x, y))\n visited[x, y] = count\n while queue:\n cx, cy = queue.popleft()\n for dx, dy in DIRS:\n nx, ny = cx+dx, cy+dy\n if self.is_valid(nx, ny) and not visited[nx, ny] and self[nx, ny] == value:\n queue.append((nx, ny))\n visited[nx, ny] = count\n return visited, count\n\narray2d_like.get_connected_components = get_connected_components\ndel get_connected_components\n";
  810. if(!py_exec(scc, "array2d.py", EXEC_MODE, mod)) {
  811. py_printexc();
  812. c11__abort("failed to execute array2d.py");
  813. }
  814. }
  815. PK_DEFINE_NEXT_WRAPPER(array2d_like_iterator)
  816. int array2d_like_iterator__iternext(py_Ref self_) {
  817. c11_array2d_like_iterator* self = py_touserdata(self_);
  818. if(self->j >= self->array->n_rows) {
  819. py_newnil(py_retval());
  820. return 0;
  821. }
  822. py_TValue* data = py_newtuple(py_retval(), 2);
  823. py_newvec2i(&data[0],
  824. (c11_vec2i){
  825. {self->i, self->j}
  826. });
  827. py_assign(&data[1], self->array->f_get(self->array, self->i, self->j));
  828. self->i++;
  829. if(self->i >= self->array->n_cols) {
  830. self->i = 0;
  831. self->j++;
  832. }
  833. return 1;
  834. }
  835. static void register_array2d_like_iterator(py_Ref mod) {
  836. py_Type type = py_newtype("array2d_like_iterator", tp_object, mod, NULL);
  837. assert(type == tp_array2d_like_iterator);
  838. py_bindmagic(type, __iter__, pk_wrapper__self);
  839. py_bindmagic(type, __next__, array2d_like_iterator__next__);
  840. }
  841. static bool array2d__new__(int argc, py_Ref argv) {
  842. // __new__(cls, n_cols: int, n_rows: int, default: Callable[[vec2i], T] = None)
  843. py_Ref default_ = py_arg(3);
  844. PY_CHECK_ARG_TYPE(0, tp_type);
  845. PY_CHECK_ARG_TYPE(1, tp_int);
  846. PY_CHECK_ARG_TYPE(2, tp_int);
  847. int n_cols = argv[1]._i64;
  848. int n_rows = argv[2]._i64;
  849. if(n_cols <= 0 || n_rows <= 0) return ValueError("array2d() expected positive dimensions");
  850. c11_array2d* ud = c11_newarray2d(py_pushtmp(), n_cols, n_rows);
  851. // setup initial values
  852. if(py_callable(default_)) {
  853. for(int j = 0; j < n_rows; j++) {
  854. for(int i = 0; i < n_cols; i++) {
  855. py_TValue tmp;
  856. py_newvec2i(&tmp,
  857. (c11_vec2i){
  858. {i, j}
  859. });
  860. if(!py_call(default_, 1, &tmp)) return false;
  861. ud->data[j * n_cols + i] = *py_retval();
  862. }
  863. }
  864. } else {
  865. for(int i = 0; i < ud->header.numel; i++) {
  866. ud->data[i] = *default_;
  867. }
  868. }
  869. py_assign(py_retval(), py_peek(-1));
  870. py_pop();
  871. return true;
  872. }
  873. // fromlist(data: list[list[T]]) -> array2d[T]
  874. static bool array2d_fromlist_STATIC(int argc, py_Ref argv) {
  875. PY_CHECK_ARGC(1);
  876. if(!py_checktype(argv, tp_list)) return false;
  877. int n_rows = py_list_len(argv);
  878. if(n_rows == 0) return ValueError("fromlist() expected a non-empty list");
  879. int n_cols = -1;
  880. for(int j = 0; j < n_rows; j++) {
  881. py_Ref row_j = py_list_getitem(argv, j);
  882. if(!py_checktype(row_j, tp_list)) return false;
  883. int n_cols_j = py_list_len(row_j);
  884. if(n_cols == -1) {
  885. if(n_cols_j == 0) return ValueError("fromlist() expected a non-empty list");
  886. n_cols = n_cols_j;
  887. } else if(n_cols != n_cols_j) {
  888. return ValueError("fromlist() expected a list of lists with the same length");
  889. }
  890. }
  891. c11_array2d* res = c11_newarray2d(py_retval(), n_cols, n_rows);
  892. for(int j = 0; j < n_rows; j++) {
  893. py_Ref row_j = py_list_getitem(argv, j);
  894. for(int i = 0; i < n_cols; i++) {
  895. c11_array2d__set(res, i, j, py_list_getitem(row_j, i));
  896. }
  897. }
  898. return true;
  899. }
  900. static void register_array2d(py_Ref mod) {
  901. py_Type type = py_newtype("array2d", tp_array2d_like, mod, NULL);
  902. assert(type == tp_array2d);
  903. py_bind(py_tpobject(type),
  904. "__new__(cls, n_cols: int, n_rows: int, default=None)",
  905. array2d__new__);
  906. py_bindstaticmethod(type, "fromlist", array2d_fromlist_STATIC);
  907. }
  908. static bool array2d_view_origin(int argc, py_Ref argv) {
  909. PY_CHECK_ARGC(1);
  910. c11_array2d_view* self = py_touserdata(argv);
  911. py_newvec2i(py_retval(), self->origin);
  912. return true;
  913. }
  914. static void register_array2d_view(py_Ref mod) {
  915. py_Type type = py_newtype("array2d_view", tp_array2d_like, mod, NULL);
  916. assert(type == tp_array2d_view);
  917. py_bindproperty(type, "origin", array2d_view_origin, NULL);
  918. }
  919. /* chunked_array2d */
  920. #define SMALLMAP_T__SOURCE
  921. #define K c11_vec2i
  922. #define V py_TValue*
  923. #define NAME c11_chunked_array2d_chunks
  924. #define less(a, b) (a._i64 < b._i64)
  925. #define equal(a, b) (a._i64 == b._i64)
  926. #include "pocketpy/xmacros/smallmap.h"
  927. #undef SMALLMAP_T__SOURCE
  928. static py_TValue*
  929. c11_chunked_array2d__new_chunk(c11_chunked_array2d* self, c11_vec2i pos, py_Ref context) {
  930. bool exists = c11_chunked_array2d_chunks__contains(&self->chunks, pos);
  931. if(exists) {
  932. ValueError("chunk already exists at pos (%d, %d)", pos.x, pos.y);
  933. return NULL;
  934. }
  935. int chunk_numel = self->chunk_size * self->chunk_size + 1;
  936. py_TValue* data = PK_MALLOC(sizeof(py_TValue) * chunk_numel);
  937. data[0] = *context;
  938. memset(&data[1], 0, sizeof(py_TValue) * (chunk_numel - 1));
  939. c11_chunked_array2d_chunks__set(&self->chunks, pos, data);
  940. self->last_visited.key = pos;
  941. self->last_visited.value = data;
  942. // init data with default value
  943. for(int i = 1; i < chunk_numel; i++) {
  944. data[i] = self->default_T;
  945. }
  946. return data;
  947. }
  948. static void
  949. cpy312__divmod_int_uint(int a, int b_log2, int b_mask, int* restrict q, int* restrict r) {
  950. if(a >= 0) {
  951. *q = a >> b_log2;
  952. *r = a & b_mask;
  953. } else {
  954. *q = -1 - ((-a - 1) >> b_log2);
  955. *r = b_mask - ((-a - 1) & b_mask);
  956. }
  957. }
  958. static void c11_chunked_array2d__world_to_chunk(c11_chunked_array2d* self,
  959. int col,
  960. int row,
  961. c11_vec2i* restrict chunk_pos,
  962. c11_vec2i* restrict local_pos) {
  963. cpy312__divmod_int_uint(col,
  964. self->chunk_size_log2,
  965. self->chunk_size_mask,
  966. &chunk_pos->x,
  967. &local_pos->x);
  968. cpy312__divmod_int_uint(row,
  969. self->chunk_size_log2,
  970. self->chunk_size_mask,
  971. &chunk_pos->y,
  972. &local_pos->y);
  973. }
  974. static py_TValue* c11_chunked_array2d__parse_col_row(c11_chunked_array2d* self,
  975. int col,
  976. int row,
  977. c11_vec2i* restrict chunk_pos,
  978. c11_vec2i* restrict local_pos) {
  979. c11_chunked_array2d__world_to_chunk(self, col, row, chunk_pos, local_pos);
  980. py_TValue* data;
  981. if(self->last_visited.value != NULL && chunk_pos->_i64 == self->last_visited.key._i64) {
  982. data = self->last_visited.value;
  983. } else {
  984. data = c11_chunked_array2d_chunks__get(&self->chunks, *chunk_pos, NULL);
  985. }
  986. if(data != NULL) {
  987. self->last_visited.key = *chunk_pos;
  988. self->last_visited.value = data;
  989. }
  990. return data;
  991. }
  992. py_Ref c11_chunked_array2d__get(c11_chunked_array2d* self, int col, int row) {
  993. c11_vec2i chunk_pos, local_pos;
  994. py_TValue* data = c11_chunked_array2d__parse_col_row(self, col, row, &chunk_pos, &local_pos);
  995. if(data == NULL) return NULL;
  996. return &data[1 + local_pos.y * self->chunk_size + local_pos.x];
  997. }
  998. bool c11_chunked_array2d__set(c11_chunked_array2d* self, int col, int row, py_Ref value) {
  999. c11_vec2i chunk_pos, local_pos;
  1000. py_TValue* data = c11_chunked_array2d__parse_col_row(self, col, row, &chunk_pos, &local_pos);
  1001. if(data == NULL) {
  1002. if(self->auto_add_chunk) {
  1003. data = c11_chunked_array2d__new_chunk(self, chunk_pos, py_None());
  1004. if(data == NULL) return false;
  1005. } else {
  1006. return IndexError("(%d, %d) is out of bounds and !auto_add_chunk", col, row);
  1007. }
  1008. }
  1009. data[1 + local_pos.y * self->chunk_size + local_pos.x] = *value;
  1010. return true;
  1011. }
  1012. static bool chunked_array2d__new__(int argc, py_Ref argv) {
  1013. PY_CHECK_ARGC(4);
  1014. PY_CHECK_ARG_TYPE(1, tp_int);
  1015. PY_CHECK_ARG_TYPE(3, tp_bool);
  1016. py_Type cls = py_totype(argv);
  1017. c11_chunked_array2d* self = py_newobject(py_retval(), cls, 0, sizeof(c11_chunked_array2d));
  1018. int chunk_size = py_toint(&argv[1]);
  1019. self->default_T = argv[2];
  1020. self->auto_add_chunk = py_tobool(&argv[3]);
  1021. c11_chunked_array2d_chunks__ctor(&self->chunks);
  1022. self->chunk_size = chunk_size;
  1023. switch(chunk_size) {
  1024. case 2: self->chunk_size_log2 = 1; break;
  1025. case 4: self->chunk_size_log2 = 2; break;
  1026. case 8: self->chunk_size_log2 = 3; break;
  1027. case 16: self->chunk_size_log2 = 4; break;
  1028. case 32: self->chunk_size_log2 = 5; break;
  1029. case 64: self->chunk_size_log2 = 6; break;
  1030. case 128: self->chunk_size_log2 = 7; break;
  1031. case 256: self->chunk_size_log2 = 8; break;
  1032. case 512: self->chunk_size_log2 = 9; break;
  1033. case 1024: self->chunk_size_log2 = 10; break;
  1034. case 2048: self->chunk_size_log2 = 11; break;
  1035. case 4096: self->chunk_size_log2 = 12; break;
  1036. default: return ValueError("invalid chunk_size: %d, not power of 2", chunk_size);
  1037. }
  1038. self->chunk_size_mask = chunk_size - 1;
  1039. memset(&self->last_visited, 0, sizeof(c11_chunked_array2d_chunks_KV));
  1040. return true;
  1041. }
  1042. static bool chunked_array2d_chunk_size(int argc, py_Ref argv) {
  1043. PY_CHECK_ARGC(1);
  1044. c11_chunked_array2d* self = py_touserdata(argv);
  1045. py_newint(py_retval(), self->chunk_size);
  1046. return true;
  1047. }
  1048. static bool chunked_array2d__getitem__(int argc, py_Ref argv) {
  1049. PY_CHECK_ARGC(2);
  1050. PY_CHECK_ARG_TYPE(1, tp_vec2i);
  1051. c11_chunked_array2d* self = py_touserdata(argv);
  1052. c11_vec2i pos = py_tovec2i(&argv[1]);
  1053. py_Ref res = c11_chunked_array2d__get(self, pos.x, pos.y);
  1054. if(res == NULL) return IndexError("(%d, %d) is out of bounds", pos.x, pos.y);
  1055. py_assign(py_retval(), res);
  1056. return true;
  1057. }
  1058. static bool chunked_array2d__setitem__(int argc, py_Ref argv) {
  1059. PY_CHECK_ARGC(3);
  1060. PY_CHECK_ARG_TYPE(1, tp_vec2i);
  1061. c11_chunked_array2d* self = py_touserdata(argv);
  1062. c11_vec2i pos = py_tovec2i(&argv[1]);
  1063. bool ok = c11_chunked_array2d__set(self, pos.x, pos.y, &argv[2]);
  1064. if(!ok) return false;
  1065. py_newnone(py_retval());
  1066. return true;
  1067. }
  1068. static bool chunked_array2d__iter__(int argc, py_Ref argv) {
  1069. PY_CHECK_ARGC(1);
  1070. c11_chunked_array2d* self = py_touserdata(argv);
  1071. py_Ref data = py_newtuple(py_pushtmp(), self->chunks.length);
  1072. for(int i = 0; i < self->chunks.length; i++) {
  1073. c11_chunked_array2d_chunks_KV* kv =
  1074. c11__at(c11_chunked_array2d_chunks_KV, &self->chunks, i);
  1075. py_Ref p = py_newtuple(&data[i], 2);
  1076. py_newvec2i(&p[0], kv->key); // pos
  1077. p[1] = kv->value[0]; // context
  1078. }
  1079. bool ok = py_iter(py_peek(-1));
  1080. if(!ok) return false;
  1081. py_pop();
  1082. return true;
  1083. }
  1084. static bool chunked_array2d__len__(int argc, py_Ref argv) {
  1085. PY_CHECK_ARGC(1);
  1086. c11_chunked_array2d* self = py_touserdata(argv);
  1087. py_newint(py_retval(), self->chunks.length);
  1088. return true;
  1089. }
  1090. static bool chunked_array2d_clear(int argc, py_Ref argv) {
  1091. PY_CHECK_ARGC(1);
  1092. c11_chunked_array2d* self = py_touserdata(argv);
  1093. c11__foreach(c11_chunked_array2d_chunks_KV, &self->chunks, p_kv) PK_FREE(p_kv->value);
  1094. c11_chunked_array2d_chunks__clear(&self->chunks);
  1095. self->last_visited.value = NULL;
  1096. py_newnone(py_retval());
  1097. return true;
  1098. }
  1099. static bool chunked_array2d_copy(int argc, py_Ref argv) {
  1100. PY_CHECK_ARGC(1);
  1101. c11_chunked_array2d* self = py_touserdata(argv);
  1102. c11_chunked_array2d* res =
  1103. py_newobject(py_retval(), tp_chunked_array2d, 0, sizeof(c11_chunked_array2d));
  1104. // copy basic data
  1105. memcpy(res, self, sizeof(c11_chunked_array2d));
  1106. // invalidate last_visited cache
  1107. self->last_visited.value = NULL;
  1108. // copy chunks
  1109. memset(&res->chunks, 0, sizeof(c11_chunked_array2d_chunks));
  1110. c11_chunked_array2d_chunks__ctor(&res->chunks);
  1111. c11_vector__reserve(&res->chunks, self->chunks.capacity);
  1112. for(int i = 0; i < self->chunks.length; i++) {
  1113. c11_chunked_array2d_chunks_KV* kv =
  1114. c11__at(c11_chunked_array2d_chunks_KV, &self->chunks, i);
  1115. int chunk_numel = self->chunk_size * self->chunk_size + 1;
  1116. py_TValue* data = PK_MALLOC(sizeof(py_TValue) * chunk_numel);
  1117. memcpy(data, kv->value, sizeof(py_TValue) * chunk_numel);
  1118. // construct new KV
  1119. c11_chunked_array2d_chunks_KV new_kv;
  1120. new_kv.key = kv->key;
  1121. new_kv.value = data;
  1122. c11_vector__push(c11_chunked_array2d_chunks_KV, &res->chunks, new_kv);
  1123. }
  1124. return true;
  1125. }
  1126. static bool chunked_array2d_world_to_chunk(int argc, py_Ref argv) {
  1127. PY_CHECK_ARGC(2);
  1128. PY_CHECK_ARG_TYPE(1, tp_vec2i);
  1129. c11_chunked_array2d* self = py_touserdata(argv);
  1130. c11_vec2i pos = py_tovec2i(&argv[1]);
  1131. c11_vec2i chunk_pos, local_pos;
  1132. c11_chunked_array2d__world_to_chunk(self, pos.x, pos.y, &chunk_pos, &local_pos);
  1133. py_TValue* p = py_newtuple(py_retval(), 2);
  1134. py_newvec2i(&p[0], chunk_pos);
  1135. py_newvec2i(&p[1], local_pos);
  1136. return true;
  1137. }
  1138. static bool chunked_array2d_add_chunk(int argc, py_Ref argv) {
  1139. PY_CHECK_ARGC(3);
  1140. PY_CHECK_ARG_TYPE(1, tp_vec2i);
  1141. c11_chunked_array2d* self = py_touserdata(argv);
  1142. c11_vec2i pos = py_tovec2i(&argv[1]);
  1143. py_TValue* data = c11_chunked_array2d__new_chunk(self, pos, &argv[2]);
  1144. if(data == NULL) return false;
  1145. py_newnone(py_retval());
  1146. return true;
  1147. }
  1148. static bool chunked_array2d_remove_chunk(int argc, py_Ref argv) {
  1149. PY_CHECK_ARGC(2);
  1150. PY_CHECK_ARG_TYPE(1, tp_vec2i);
  1151. c11_chunked_array2d* self = py_touserdata(argv);
  1152. c11_vec2i pos = py_tovec2i(&argv[1]);
  1153. py_TValue* data = c11_chunked_array2d_chunks__get(&self->chunks, pos, NULL);
  1154. if(data != NULL) {
  1155. PK_FREE(data);
  1156. bool ok = c11_chunked_array2d_chunks__del(&self->chunks, pos);
  1157. assert(ok);
  1158. self->last_visited.value = NULL;
  1159. py_newbool(py_retval(), ok);
  1160. } else {
  1161. py_newbool(py_retval(), false);
  1162. }
  1163. return true;
  1164. }
  1165. static bool chunked_array2d_move_chunk(int argc, py_Ref argv) {
  1166. PY_CHECK_ARGC(3);
  1167. PY_CHECK_ARG_TYPE(1, tp_vec2i);
  1168. PY_CHECK_ARG_TYPE(2, tp_vec2i);
  1169. c11_chunked_array2d* self = py_touserdata(argv);
  1170. c11_vec2i src = py_tovec2i(&argv[1]);
  1171. c11_vec2i dst = py_tovec2i(&argv[2]);
  1172. py_TValue* src_data = c11_chunked_array2d_chunks__get(&self->chunks, src, NULL);
  1173. py_TValue* dst_data = c11_chunked_array2d_chunks__get(&self->chunks, dst, NULL);
  1174. if(src_data == NULL || dst_data != NULL) {
  1175. py_newbool(py_retval(), false);
  1176. return true;
  1177. }
  1178. c11_chunked_array2d_chunks__del(&self->chunks, src);
  1179. c11_chunked_array2d_chunks__set(&self->chunks, dst, src_data);
  1180. self->last_visited.value = NULL;
  1181. py_newbool(py_retval(), true);
  1182. return true;
  1183. }
  1184. static bool chunked_array2d_get_context(int argc, py_Ref argv) {
  1185. PY_CHECK_ARGC(2);
  1186. PY_CHECK_ARG_TYPE(1, tp_vec2i);
  1187. c11_chunked_array2d* self = py_touserdata(argv);
  1188. c11_vec2i pos = py_tovec2i(&argv[1]);
  1189. py_TValue* data = c11_chunked_array2d_chunks__get(&self->chunks, pos, NULL);
  1190. if(data == NULL) {
  1191. return IndexError("no chunk found at (%d, %d)", pos.x, pos.y);
  1192. } else {
  1193. py_assign(py_retval(), &data[0]);
  1194. }
  1195. return true;
  1196. }
  1197. void c11_chunked_array2d__dtor(c11_chunked_array2d* self) {
  1198. c11__foreach(c11_chunked_array2d_chunks_KV, &self->chunks, p_kv) PK_FREE(p_kv->value);
  1199. c11_chunked_array2d_chunks__dtor(&self->chunks);
  1200. }
  1201. void c11_chunked_array2d__mark(void* ud, c11_vector* p_stack) {
  1202. c11_chunked_array2d* self = ud;
  1203. pk__mark_value(&self->default_T);
  1204. int chunk_numel = self->chunk_size * self->chunk_size + 1;
  1205. for(int i = 0; i < self->chunks.length; i++) {
  1206. py_TValue* data = c11__getitem(c11_chunked_array2d_chunks_KV, &self->chunks, i).value;
  1207. for(int j = 0; j < chunk_numel; j++) {
  1208. pk__mark_value(data + j);
  1209. }
  1210. }
  1211. }
  1212. static bool chunked_array2d_view(int argc, py_Ref argv) {
  1213. PY_CHECK_ARGC(1);
  1214. c11_chunked_array2d* self = py_touserdata(&argv[0]);
  1215. if(self->chunks.length == 0) { return ValueError("chunked_array2d is empty"); }
  1216. int min_chunk_x = INT_MAX;
  1217. int min_chunk_y = INT_MAX;
  1218. int max_chunk_x = INT_MIN;
  1219. int max_chunk_y = INT_MIN;
  1220. for(int i = 0; i < self->chunks.length; i++) {
  1221. c11_vec2i chunk_pos = c11__getitem(c11_chunked_array2d_chunks_KV, &self->chunks, i).key;
  1222. min_chunk_x = c11__min(min_chunk_x, chunk_pos.x);
  1223. min_chunk_y = c11__min(min_chunk_y, chunk_pos.y);
  1224. max_chunk_x = c11__max(max_chunk_x, chunk_pos.x);
  1225. max_chunk_y = c11__max(max_chunk_y, chunk_pos.y);
  1226. }
  1227. int start_col = min_chunk_x * self->chunk_size;
  1228. int start_row = min_chunk_y * self->chunk_size;
  1229. int width = (max_chunk_x - min_chunk_x + 1) * self->chunk_size;
  1230. int height = (max_chunk_y - min_chunk_y + 1) * self->chunk_size;
  1231. return _chunked_array2d_view(py_retval(), argv, self, start_col, start_row, width, height);
  1232. }
  1233. static bool chunked_array2d_view_rect(int argc, py_Ref argv) {
  1234. PY_CHECK_ARGC(4);
  1235. PY_CHECK_ARG_TYPE(1, tp_vec2i);
  1236. PY_CHECK_ARG_TYPE(2, tp_int);
  1237. PY_CHECK_ARG_TYPE(3, tp_int);
  1238. c11_chunked_array2d* self = py_touserdata(&argv[0]);
  1239. c11_vec2i pos = py_tovec2i(&argv[1]);
  1240. int width = py_toint(&argv[2]);
  1241. int height = py_toint(&argv[3]);
  1242. return _chunked_array2d_view(py_retval(), argv, self, pos.x, pos.y, width, height);
  1243. }
  1244. static bool chunked_array2d_view_chunk(int argc, py_Ref argv) {
  1245. PY_CHECK_ARGC(2);
  1246. PY_CHECK_ARG_TYPE(1, tp_vec2i);
  1247. c11_chunked_array2d* self = py_touserdata(&argv[0]);
  1248. c11_vec2i chunk_pos = py_tovec2i(&argv[1]);
  1249. int start_col = chunk_pos.x * self->chunk_size;
  1250. int start_row = chunk_pos.y * self->chunk_size;
  1251. return _chunked_array2d_view(py_retval(),
  1252. argv,
  1253. self,
  1254. start_col,
  1255. start_row,
  1256. self->chunk_size,
  1257. self->chunk_size);
  1258. }
  1259. static bool chunked_array2d_view_chunks(int argc, py_Ref argv) {
  1260. PY_CHECK_ARGC(4);
  1261. PY_CHECK_ARG_TYPE(1, tp_vec2i);
  1262. PY_CHECK_ARG_TYPE(2, tp_int);
  1263. PY_CHECK_ARG_TYPE(3, tp_int);
  1264. c11_chunked_array2d* self = py_touserdata(&argv[0]);
  1265. c11_vec2i chunk_pos = py_tovec2i(&argv[1]);
  1266. int width = py_toint(&argv[2]) * self->chunk_size;
  1267. int height = py_toint(&argv[3]) * self->chunk_size;
  1268. int start_col = chunk_pos.x * self->chunk_size;
  1269. int start_row = chunk_pos.y * self->chunk_size;
  1270. return _chunked_array2d_view(py_retval(), argv, self, start_col, start_row, width, height);
  1271. }
  1272. static void register_chunked_array2d(py_Ref mod) {
  1273. py_Type type =
  1274. py_newtype("chunked_array2d", tp_object, mod, (py_Dtor)c11_chunked_array2d__dtor);
  1275. assert(type == tp_chunked_array2d);
  1276. py_bind(py_tpobject(type),
  1277. "__new__(cls, chunk_size, default=None, auto_add_chunk=True)",
  1278. chunked_array2d__new__);
  1279. py_bindproperty(type, "chunk_size", chunked_array2d_chunk_size, NULL);
  1280. py_bindmagic(type, __getitem__, chunked_array2d__getitem__);
  1281. py_bindmagic(type, __setitem__, chunked_array2d__setitem__);
  1282. py_bindmagic(type, __iter__, chunked_array2d__iter__);
  1283. py_bindmagic(type, __len__, chunked_array2d__len__);
  1284. py_bindmethod(type, "clear", chunked_array2d_clear);
  1285. py_bindmethod(type, "copy", chunked_array2d_copy);
  1286. py_bindmethod(type, "world_to_chunk", chunked_array2d_world_to_chunk);
  1287. py_bindmethod(type, "add_chunk", chunked_array2d_add_chunk);
  1288. py_bindmethod(type, "remove_chunk", chunked_array2d_remove_chunk);
  1289. py_bindmethod(type, "move_chunk", chunked_array2d_move_chunk);
  1290. py_bindmethod(type, "get_context", chunked_array2d_get_context);
  1291. py_bindmethod(type, "view", chunked_array2d_view);
  1292. py_bindmethod(type, "view_rect", chunked_array2d_view_rect);
  1293. py_bindmethod(type, "view_chunk", chunked_array2d_view_chunk);
  1294. py_bindmethod(type, "view_chunks", chunked_array2d_view_chunks);
  1295. }
  1296. void pk__add_module_array2d() {
  1297. py_GlobalRef mod = py_newmodule("array2d");
  1298. register_array2d_like(mod);
  1299. register_array2d_like_iterator(mod);
  1300. register_array2d(mod);
  1301. register_array2d_view(mod);
  1302. register_chunked_array2d(mod);
  1303. }
  1304. void py_newarray2d(py_OutRef out, int width, int height) { c11_newarray2d(out, width, height); }
  1305. int py_array2d_getwidth(py_Ref self) {
  1306. assert(self->type == tp_array2d);
  1307. c11_array2d* ud = py_touserdata(self);
  1308. return ud->header.n_cols;
  1309. }
  1310. int py_array2d_getheight(py_Ref self) {
  1311. assert(self->type == tp_array2d);
  1312. c11_array2d* ud = py_touserdata(self);
  1313. return ud->header.n_rows;
  1314. }
  1315. py_ObjectRef py_array2d_getitem(py_Ref self, int x, int y) {
  1316. assert(self->type == tp_array2d);
  1317. c11_array2d* ud = py_touserdata(self);
  1318. return c11_array2d__get(ud, x, y);
  1319. }
  1320. void py_array2d_setitem(py_Ref self, int x, int y, py_Ref value) {
  1321. assert(self->type == tp_array2d);
  1322. c11_array2d* ud = py_touserdata(self);
  1323. c11_array2d__set(ud, x, y, value);
  1324. }