linalg.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661
  1. #include "pocketpy/linalg.h"
  2. namespace pkpy{
  3. #define BIND_VEC_VEC_OP(D, name, op) \
  4. vm->bind##name(PK_OBJ_GET(Type, type), [](VM* vm, PyObject* _0, PyObject* _1){ \
  5. Vec##D& self = _CAST(Vec##D&, _0); \
  6. Vec##D& other = CAST(Vec##D&, _1); \
  7. return VAR(self op other); \
  8. });
  9. #define BIND_VEC_FLOAT_OP(D, name, op) \
  10. vm->bind##name(PK_OBJ_GET(Type, type), [](VM* vm, PyObject* _0, PyObject* _1){ \
  11. Vec##D& self = _CAST(Vec##D&, _0); \
  12. f64 other = CAST(f64, _1); \
  13. return VAR(self op other); \
  14. });
  15. #define BIND_VEC_FUNCTION_0(D, name) \
  16. vm->bind_method<0>(type, #name, [](VM* vm, ArgsView args){ \
  17. Vec##D& self = _CAST(Vec##D&, args[0]); \
  18. return VAR(self.name()); \
  19. });
  20. #define BIND_VEC_FUNCTION_1(D, name) \
  21. vm->bind_method<1>(type, #name, [](VM* vm, ArgsView args){ \
  22. Vec##D& self = _CAST(Vec##D&, args[0]); \
  23. Vec##D& other = CAST(Vec##D&, args[1]); \
  24. return VAR(self.name(other)); \
  25. });
  26. #define BIND_VEC_MUL_OP(D) \
  27. vm->bind__mul__(PK_OBJ_GET(Type, type), [](VM* vm, PyObject* _0, PyObject* _1){ \
  28. Vec##D& self = _CAST(Vec##D&, _0); \
  29. if(is_non_tagged_type(_1, Vec##D::_type(vm))){ \
  30. Vec##D& other = _CAST(Vec##D&, _1); \
  31. return VAR(self * other); \
  32. } \
  33. f64 other = CAST(f64, _1); \
  34. return VAR(self * other); \
  35. }); \
  36. vm->bind_method<1>(type, "__rmul__", [](VM* vm, ArgsView args){ \
  37. Vec##D& self = _CAST(Vec##D&, args[0]); \
  38. f64 other = CAST(f64, args[1]); \
  39. return VAR(self * other); \
  40. }); \
  41. vm->bind__truediv__(PK_OBJ_GET(Type, type), [](VM* vm, PyObject* _0, PyObject* _1){ \
  42. Vec##D& self = _CAST(Vec##D&, _0); \
  43. f64 other = CAST(f64, _1); \
  44. return VAR(self / other); \
  45. });
  46. // https://github.com/Unity-Technologies/UnityCsReference/blob/master/Runtime/Export/Math/Vector2.cs#L289
  47. static Vec2 SmoothDamp(Vec2 current, Vec2 target, Vec2& currentVelocity, float smoothTime, float maxSpeed, float deltaTime)
  48. {
  49. // Based on Game Programming Gems 4 Chapter 1.10
  50. smoothTime = std::max(0.0001F, smoothTime);
  51. float omega = 2.0F / smoothTime;
  52. float x = omega * deltaTime;
  53. float exp = 1.0F / (1.0F + x + 0.48F * x * x + 0.235F * x * x * x);
  54. float change_x = current.x - target.x;
  55. float change_y = current.y - target.y;
  56. Vec2 originalTo = target;
  57. // Clamp maximum speed
  58. float maxChange = maxSpeed * smoothTime;
  59. float maxChangeSq = maxChange * maxChange;
  60. float sqDist = change_x * change_x + change_y * change_y;
  61. if (sqDist > maxChangeSq)
  62. {
  63. float mag = std::sqrt(sqDist);
  64. change_x = change_x / mag * maxChange;
  65. change_y = change_y / mag * maxChange;
  66. }
  67. target.x = current.x - change_x;
  68. target.y = current.y - change_y;
  69. float temp_x = (currentVelocity.x + omega * change_x) * deltaTime;
  70. float temp_y = (currentVelocity.y + omega * change_y) * deltaTime;
  71. currentVelocity.x = (currentVelocity.x - omega * temp_x) * exp;
  72. currentVelocity.y = (currentVelocity.y - omega * temp_y) * exp;
  73. float output_x = target.x + (change_x + temp_x) * exp;
  74. float output_y = target.y + (change_y + temp_y) * exp;
  75. // Prevent overshooting
  76. float origMinusCurrent_x = originalTo.x - current.x;
  77. float origMinusCurrent_y = originalTo.y - current.y;
  78. float outMinusOrig_x = output_x - originalTo.x;
  79. float outMinusOrig_y = output_y - originalTo.y;
  80. if (origMinusCurrent_x * outMinusOrig_x + origMinusCurrent_y * outMinusOrig_y > 0)
  81. {
  82. output_x = originalTo.x;
  83. output_y = originalTo.y;
  84. currentVelocity.x = (output_x - originalTo.x) / deltaTime;
  85. currentVelocity.y = (output_y - originalTo.y) / deltaTime;
  86. }
  87. return Vec2(output_x, output_y);
  88. }
  89. void Vec2::_register(VM* vm, PyObject* mod, PyObject* type){
  90. PY_STRUCT_LIKE(Vec2)
  91. vm->bind_constructor<3>(type, [](VM* vm, ArgsView args){
  92. float x = CAST_F(args[1]);
  93. float y = CAST_F(args[2]);
  94. return vm->heap.gcnew<Vec2>(PK_OBJ_GET(Type, args[0]), Vec2(x, y));
  95. });
  96. // @staticmethod
  97. vm->bind(type, "smooth_damp(current: vec2, target: vec2, current_velocity_: vec2, smooth_time: float, max_speed: float, delta_time: float) -> vec2", [](VM* vm, ArgsView args){
  98. Vec2 current = CAST(Vec2, args[0]);
  99. Vec2 target = CAST(Vec2, args[1]);
  100. Vec2& current_velocity_ = CAST(Vec2&, args[2]);
  101. float smooth_time = CAST_F(args[3]);
  102. float max_speed = CAST_F(args[4]);
  103. float delta_time = CAST_F(args[5]);
  104. Vec2 ret = SmoothDamp(current, target, current_velocity_, smooth_time, max_speed, delta_time);
  105. return VAR(ret);
  106. }, {}, BindType::STATICMETHOD);
  107. // @staticmethod
  108. vm->bind(type, "angle(__from: vec2, __to: vec2) -> float", [](VM* vm, ArgsView args){
  109. Vec2 __from = CAST(Vec2, args[0]);
  110. Vec2 __to = CAST(Vec2, args[1]);
  111. float val = atan2f(__to.y, __to.x) - atan2f(__from.y, __from.x);
  112. const float PI = 3.1415926535897932384f;
  113. if(val > PI) val -= 2*PI;
  114. if(val < -PI) val += 2*PI;
  115. return VAR(val);
  116. }, {}, BindType::STATICMETHOD);
  117. vm->bind__repr__(PK_OBJ_GET(Type, type), [](VM* vm, PyObject* obj){
  118. Vec2 self = _CAST(Vec2&, obj);
  119. SStream ss;
  120. ss.setprecision(3);
  121. ss << "vec2(" << self.x << ", " << self.y << ")";
  122. return VAR(ss.str());
  123. });
  124. vm->bind_method<1>(type, "rotate", [](VM* vm, ArgsView args){
  125. Vec2 self = _CAST(Vec2&, args[0]);
  126. float radian = CAST(f64, args[1]);
  127. return VAR_T(Vec2, self.rotate(radian));
  128. });
  129. vm->bind_method<1>(type, "rotate_", [](VM* vm, ArgsView args){
  130. Vec2& self = _CAST(Vec2&, args[0]);
  131. float radian = CAST(f64, args[1]);
  132. self = self.rotate(radian);
  133. return vm->None;
  134. });
  135. PY_FIELD(Vec2, "x", _, x)
  136. PY_FIELD(Vec2, "y", _, y)
  137. BIND_VEC_VEC_OP(2, __add__, +)
  138. BIND_VEC_VEC_OP(2, __sub__, -)
  139. BIND_VEC_MUL_OP(2)
  140. BIND_VEC_FLOAT_OP(2, __truediv__, /)
  141. BIND_VEC_FUNCTION_1(2, dot)
  142. BIND_VEC_FUNCTION_1(2, cross)
  143. BIND_VEC_FUNCTION_1(2, copy_)
  144. BIND_VEC_FUNCTION_0(2, length)
  145. BIND_VEC_FUNCTION_0(2, length_squared)
  146. BIND_VEC_FUNCTION_0(2, normalize)
  147. BIND_VEC_FUNCTION_0(2, normalize_)
  148. }
  149. void Vec3::_register(VM* vm, PyObject* mod, PyObject* type){
  150. PY_STRUCT_LIKE(Vec3)
  151. vm->bind_constructor<4>(type, [](VM* vm, ArgsView args){
  152. float x = CAST_F(args[1]);
  153. float y = CAST_F(args[2]);
  154. float z = CAST_F(args[3]);
  155. return vm->heap.gcnew<Vec3>(PK_OBJ_GET(Type, args[0]), Vec3(x, y, z));
  156. });
  157. vm->bind__repr__(PK_OBJ_GET(Type, type), [](VM* vm, PyObject* obj){
  158. Vec3 self = _CAST(Vec3&, obj);
  159. SStream ss;
  160. ss.setprecision(3);
  161. ss << "vec3(" << self.x << ", " << self.y << ", " << self.z << ")";
  162. return VAR(ss.str());
  163. });
  164. PY_FIELD(Vec3, "x", _, x)
  165. PY_FIELD(Vec3, "y", _, y)
  166. PY_FIELD(Vec3, "z", _, z)
  167. BIND_VEC_VEC_OP(3, __add__, +)
  168. BIND_VEC_VEC_OP(3, __sub__, -)
  169. BIND_VEC_MUL_OP(3)
  170. BIND_VEC_FUNCTION_1(3, dot)
  171. BIND_VEC_FUNCTION_1(3, cross)
  172. BIND_VEC_FUNCTION_1(3, copy_)
  173. BIND_VEC_FUNCTION_0(3, length)
  174. BIND_VEC_FUNCTION_0(3, length_squared)
  175. BIND_VEC_FUNCTION_0(3, normalize)
  176. BIND_VEC_FUNCTION_0(3, normalize_)
  177. }
  178. void Vec4::_register(VM* vm, PyObject* mod, PyObject* type){
  179. PY_STRUCT_LIKE(Vec4)
  180. vm->bind_constructor<1+4>(type, [](VM* vm, ArgsView args){
  181. float x = CAST_F(args[1]);
  182. float y = CAST_F(args[2]);
  183. float z = CAST_F(args[3]);
  184. float w = CAST_F(args[4]);
  185. return vm->heap.gcnew<Vec4>(PK_OBJ_GET(Type, args[0]), Vec4(x, y, z, w));
  186. });
  187. vm->bind__repr__(PK_OBJ_GET(Type, type), [](VM* vm, PyObject* obj){
  188. Vec4 self = _CAST(Vec4&, obj);
  189. SStream ss;
  190. ss.setprecision(3);
  191. ss << "vec4(" << self.x << ", " << self.y << ", " << self.z << ", " << self.w << ")";
  192. return VAR(ss.str());
  193. });
  194. PY_FIELD(Vec4, "x", _, x)
  195. PY_FIELD(Vec4, "y", _, y)
  196. PY_FIELD(Vec4, "z", _, z)
  197. PY_FIELD(Vec4, "w", _, w)
  198. BIND_VEC_VEC_OP(4, __add__, +)
  199. BIND_VEC_VEC_OP(4, __sub__, -)
  200. BIND_VEC_MUL_OP(4)
  201. BIND_VEC_FUNCTION_1(4, dot)
  202. BIND_VEC_FUNCTION_1(4, copy_)
  203. BIND_VEC_FUNCTION_0(4, length)
  204. BIND_VEC_FUNCTION_0(4, length_squared)
  205. BIND_VEC_FUNCTION_0(4, normalize)
  206. BIND_VEC_FUNCTION_0(4, normalize_)
  207. }
  208. #undef BIND_VEC_VEC_OP
  209. #undef BIND_VEC_MUL_OP
  210. #undef BIND_VEC_FUNCTION_0
  211. #undef BIND_VEC_FUNCTION_1
  212. void Mat3x3::_register(VM* vm, PyObject* mod, PyObject* type){
  213. PY_STRUCT_LIKE(Mat3x3)
  214. vm->bind_constructor<-1>(type, [](VM* vm, ArgsView args){
  215. if(args.size() == 1+0) return vm->heap.gcnew<Mat3x3>(PK_OBJ_GET(Type, args[0]), Mat3x3::zeros());
  216. if(args.size() == 1+1){
  217. const List& list = CAST(List&, args[1]);
  218. if(list.size() != 9) vm->TypeError("Mat3x3.__new__ takes a list of 9 floats");
  219. Mat3x3 mat;
  220. for(int i=0; i<9; i++) mat.v[i] = CAST_F(list[i]);
  221. return vm->heap.gcnew<Mat3x3>(PK_OBJ_GET(Type, args[0]), mat);
  222. }
  223. if(args.size() == 1+9){
  224. Mat3x3 mat;
  225. for(int i=0; i<9; i++) mat.v[i] = CAST_F(args[1+i]);
  226. return vm->heap.gcnew<Mat3x3>(PK_OBJ_GET(Type, args[0]), mat);
  227. }
  228. vm->TypeError(_S("Mat3x3.__new__ takes 0 or 1 or 9 arguments, got ", args.size()-1));
  229. return vm->None;
  230. });
  231. vm->bind_method<1>(type, "copy_", [](VM* vm, ArgsView args){
  232. Mat3x3& self = _CAST(Mat3x3&, args[0]);
  233. const Mat3x3& other = CAST(Mat3x3&, args[1]);
  234. self = other;
  235. return vm->None;
  236. });
  237. vm->bind__repr__(PK_OBJ_GET(Type, type), [](VM* vm, PyObject* obj){
  238. const Mat3x3& self = _CAST(Mat3x3&, obj);
  239. SStream ss;
  240. ss.setprecision(3);
  241. ss << "mat3x3([" << self._11 << ", " << self._12 << ", " << self._13 << ",\n";
  242. ss << " " << self._21 << ", " << self._22 << ", " << self._23 << ",\n";
  243. ss << " " << self._31 << ", " << self._32 << ", " << self._33 << "])";
  244. return VAR(ss.str());
  245. });
  246. vm->bind__getitem__(PK_OBJ_GET(Type, type), [](VM* vm, PyObject* obj, PyObject* index){
  247. Mat3x3& self = _CAST(Mat3x3&, obj);
  248. Tuple& t = CAST(Tuple&, index);
  249. if(t.size() != 2){
  250. vm->TypeError("Mat3x3.__getitem__ takes a tuple of 2 integers");
  251. }
  252. i64 i = CAST(i64, t[0]);
  253. i64 j = CAST(i64, t[1]);
  254. if(i < 0 || i >= 3 || j < 0 || j >= 3){
  255. vm->IndexError("index out of range");
  256. }
  257. return VAR(self.m[i][j]);
  258. });
  259. vm->bind__setitem__(PK_OBJ_GET(Type, type), [](VM* vm, PyObject* obj, PyObject* index, PyObject* value){
  260. Mat3x3& self = _CAST(Mat3x3&, obj);
  261. const Tuple& t = CAST(Tuple&, index);
  262. if(t.size() != 2){
  263. vm->TypeError("Mat3x3.__setitem__ takes a tuple of 2 integers");
  264. }
  265. i64 i = CAST(i64, t[0]);
  266. i64 j = CAST(i64, t[1]);
  267. if(i < 0 || i >= 3 || j < 0 || j >= 3){
  268. vm->IndexError("index out of range");
  269. }
  270. self.m[i][j] = CAST_F(value);
  271. });
  272. PY_FIELD(Mat3x3, "_11", _, _11)
  273. PY_FIELD(Mat3x3, "_12", _, _12)
  274. PY_FIELD(Mat3x3, "_13", _, _13)
  275. PY_FIELD(Mat3x3, "_21", _, _21)
  276. PY_FIELD(Mat3x3, "_22", _, _22)
  277. PY_FIELD(Mat3x3, "_23", _, _23)
  278. PY_FIELD(Mat3x3, "_31", _, _31)
  279. PY_FIELD(Mat3x3, "_32", _, _32)
  280. PY_FIELD(Mat3x3, "_33", _, _33)
  281. vm->bind__add__(PK_OBJ_GET(Type, type), [](VM* vm, PyObject* _0, PyObject* _1){
  282. Mat3x3& self = _CAST(Mat3x3&, _0);
  283. Mat3x3& other = CAST(Mat3x3&, _1);
  284. return VAR_T(Mat3x3, self + other);
  285. });
  286. vm->bind__sub__(PK_OBJ_GET(Type, type), [](VM* vm, PyObject* _0, PyObject* _1){
  287. Mat3x3& self = _CAST(Mat3x3&, _0);
  288. Mat3x3& other = CAST(Mat3x3&, _1);
  289. return VAR_T(Mat3x3, self - other);
  290. });
  291. vm->bind__mul__(PK_OBJ_GET(Type, type), [](VM* vm, PyObject* _0, PyObject* _1){
  292. Mat3x3& self = _CAST(Mat3x3&, _0);
  293. f64 other = CAST_F(_1);
  294. return VAR_T(Mat3x3, self * other);
  295. });
  296. vm->bind_method<1>(type, "__rmul__", [](VM* vm, ArgsView args){
  297. Mat3x3& self = _CAST(Mat3x3&, args[0]);
  298. f64 other = CAST_F(args[1]);
  299. return VAR_T(Mat3x3, self * other);
  300. });
  301. vm->bind__truediv__(PK_OBJ_GET(Type, type), [](VM* vm, PyObject* _0, PyObject* _1){
  302. Mat3x3& self = _CAST(Mat3x3&, _0);
  303. f64 other = CAST_F(_1);
  304. return VAR_T(Mat3x3, self / other);
  305. });
  306. vm->bind__matmul__(PK_OBJ_GET(Type, type), [](VM* vm, PyObject* _0, PyObject* _1){
  307. Mat3x3& self = _CAST(Mat3x3&, _0);
  308. if(is_non_tagged_type(_1, Mat3x3::_type(vm))){
  309. const Mat3x3& other = _CAST(Mat3x3&, _1);
  310. return VAR_T(Mat3x3, self.matmul(other));
  311. }
  312. if(is_non_tagged_type(_1, Vec3::_type(vm))){
  313. const Vec3& other = _CAST(Vec3&, _1);
  314. return VAR_T(Vec3, self.matmul(other));
  315. }
  316. return vm->NotImplemented;
  317. });
  318. vm->bind(type, "matmul(self, other: mat3x3, out: mat3x3 = None)", [](VM* vm, ArgsView args){
  319. const Mat3x3& self = _CAST(Mat3x3&, args[0]);
  320. const Mat3x3& other = CAST(Mat3x3&, args[1]);
  321. if(args[2] == vm->None){
  322. return VAR_T(Mat3x3, self.matmul(other));
  323. }else{
  324. Mat3x3& out = CAST(Mat3x3&, args[2]);
  325. out = self.matmul(other);
  326. return vm->None;
  327. }
  328. });
  329. vm->bind_method<0>(type, "determinant", [](VM* vm, ArgsView args){
  330. Mat3x3& self = _CAST(Mat3x3&, args[0]);
  331. return VAR(self.determinant());
  332. });
  333. vm->bind_method<0>(type, "transpose", [](VM* vm, ArgsView args){
  334. Mat3x3& self = _CAST(Mat3x3&, args[0]);
  335. return VAR_T(Mat3x3, self.transpose());
  336. });
  337. vm->bind__invert__(PK_OBJ_GET(Type, type), [](VM* vm, PyObject* obj){
  338. Mat3x3& self = _CAST(Mat3x3&, obj);
  339. Mat3x3 ret;
  340. bool ok = self.inverse(ret);
  341. if(!ok) vm->ValueError("matrix is not invertible");
  342. return VAR_T(Mat3x3, ret);
  343. });
  344. vm->bind_method<0>(type, "invert", [](VM* vm, ArgsView args){
  345. Mat3x3& self = _CAST(Mat3x3&, args[0]);
  346. Mat3x3 ret;
  347. bool ok = self.inverse(ret);
  348. if(!ok) vm->ValueError("matrix is not invertible");
  349. return VAR_T(Mat3x3, ret);
  350. });
  351. vm->bind_method<0>(type, "invert_", [](VM* vm, ArgsView args){
  352. Mat3x3& self = _CAST(Mat3x3&, args[0]);
  353. Mat3x3 ret;
  354. bool ok = self.inverse(ret);
  355. if(!ok) vm->ValueError("matrix is not invertible");
  356. self = ret;
  357. return vm->None;
  358. });
  359. vm->bind_method<0>(type, "transpose_", [](VM* vm, ArgsView args){
  360. Mat3x3& self = _CAST(Mat3x3&, args[0]);
  361. self = self.transpose();
  362. return vm->None;
  363. });
  364. // @staticmethod
  365. vm->bind(type, "zeros()", [](VM* vm, ArgsView args){
  366. return VAR_T(Mat3x3, Mat3x3::zeros());
  367. }, {}, BindType::STATICMETHOD);
  368. // @staticmethod
  369. vm->bind(type, "ones()", [](VM* vm, ArgsView args){
  370. return VAR_T(Mat3x3, Mat3x3::ones());
  371. }, {}, BindType::STATICMETHOD);
  372. // @staticmethod
  373. vm->bind(type, "identity()", [](VM* vm, ArgsView args){
  374. return VAR_T(Mat3x3, Mat3x3::identity());
  375. }, {}, BindType::STATICMETHOD);
  376. /*************** affine transformations ***************/
  377. // @staticmethod
  378. vm->bind(type, "trs(t: vec2, r: float, s: vec2)", [](VM* vm, ArgsView args){
  379. Vec2 t = CAST(Vec2, args[0]);
  380. f64 r = CAST_F(args[1]);
  381. Vec2 s = CAST(Vec2, args[2]);
  382. return VAR_T(Mat3x3, Mat3x3::trs(t, r, s));
  383. }, {}, BindType::STATICMETHOD);
  384. vm->bind(type, "copy_trs_(self, t: vec2, r: float, s: vec2)", [](VM* vm, ArgsView args){
  385. Mat3x3& self = _CAST(Mat3x3&, args[0]);
  386. Vec2 t = CAST(Vec2, args[1]);
  387. f64 r = CAST_F(args[2]);
  388. Vec2 s = CAST(Vec2, args[3]);
  389. self = Mat3x3::trs(t, r, s);
  390. return vm->None;
  391. });
  392. vm->bind(type, "copy_t_(self, t: vec2)", [](VM* vm, ArgsView args){
  393. Mat3x3& self = _CAST(Mat3x3&, args[0]);
  394. Vec2 t = CAST(Vec2, args[1]);
  395. self = Mat3x3::trs(t, self._r(), self._s());
  396. return vm->None;
  397. });
  398. vm->bind(type, "copy_r_(self, r: float)", [](VM* vm, ArgsView args){
  399. Mat3x3& self = _CAST(Mat3x3&, args[0]);
  400. f64 r = CAST_F(args[1]);
  401. self = Mat3x3::trs(self._t(), r, self._s());
  402. return vm->None;
  403. });
  404. vm->bind(type, "copy_s_(self, s: vec2)", [](VM* vm, ArgsView args){
  405. Mat3x3& self = _CAST(Mat3x3&, args[0]);
  406. Vec2 s = CAST(Vec2, args[1]);
  407. self = Mat3x3::trs(self._t(), self._r(), s);
  408. return vm->None;
  409. });
  410. vm->bind_method<0>(type, "is_affine", [](VM* vm, ArgsView args){
  411. Mat3x3& self = _CAST(Mat3x3&, args[0]);
  412. return VAR(self.is_affine());
  413. });
  414. vm->bind_method<0>(type, "_t", [](VM* vm, ArgsView args){
  415. Mat3x3& self = _CAST(Mat3x3&, args[0]);
  416. return VAR_T(Vec2, self._t());
  417. });
  418. vm->bind_method<0>(type, "_r", [](VM* vm, ArgsView args){
  419. Mat3x3& self = _CAST(Mat3x3&, args[0]);
  420. return VAR(self._r());
  421. });
  422. vm->bind_method<0>(type, "_s", [](VM* vm, ArgsView args){
  423. Mat3x3& self = _CAST(Mat3x3&, args[0]);
  424. return VAR_T(Vec2, self._s());
  425. });
  426. vm->bind_method<1>(type, "transform_point", [](VM* vm, ArgsView args){
  427. const Mat3x3& self = _CAST(Mat3x3&, args[0]);
  428. Vec2 v = CAST(Vec2, args[1]);
  429. Vec2 res = Vec2(self._11 * v.x + self._12 * v.y + self._13, self._21 * v.x + self._22 * v.y + self._23);
  430. return VAR_T(Vec2, res);
  431. });
  432. vm->bind_method<1>(type, "transform_vector", [](VM* vm, ArgsView args){
  433. const Mat3x3& self = _CAST(Mat3x3&, args[0]);
  434. Vec2 v = CAST(Vec2, args[1]);
  435. Vec2 res = Vec2(self._11 * v.x + self._12 * v.y, self._21 * v.x + self._22 * v.y);
  436. return VAR_T(Vec2, res);
  437. });
  438. }
  439. void add_module_linalg(VM* vm){
  440. PyObject* linalg = vm->new_module("linalg");
  441. Vec2::register_class(vm, linalg);
  442. Vec3::register_class(vm, linalg);
  443. Vec4::register_class(vm, linalg);
  444. Mat3x3::register_class(vm, linalg);
  445. PyObject* float_p = vm->_modules["c"]->attr("float_p");
  446. linalg->attr().set("vec2_p", float_p);
  447. linalg->attr().set("vec3_p", float_p);
  448. linalg->attr().set("vec4_p", float_p);
  449. linalg->attr().set("mat3x3_p", float_p);
  450. }
  451. /////////////// mat3x3 ///////////////
  452. Mat3x3::Mat3x3() {}
  453. Mat3x3::Mat3x3(float _11, float _12, float _13,
  454. float _21, float _22, float _23,
  455. float _31, float _32, float _33)
  456. : _11(_11), _12(_12), _13(_13)
  457. , _21(_21), _22(_22), _23(_23)
  458. , _31(_31), _32(_32), _33(_33) {}
  459. Mat3x3 Mat3x3::zeros(){
  460. return Mat3x3(0, 0, 0, 0, 0, 0, 0, 0, 0);
  461. }
  462. Mat3x3 Mat3x3::ones(){
  463. return Mat3x3(1, 1, 1, 1, 1, 1, 1, 1, 1);
  464. }
  465. Mat3x3 Mat3x3::identity(){
  466. return Mat3x3(1, 0, 0, 0, 1, 0, 0, 0, 1);
  467. }
  468. Mat3x3 Mat3x3::operator+(const Mat3x3& other) const{
  469. Mat3x3 ret;
  470. for (int i=0; i<9; ++i) ret.v[i] = v[i] + other.v[i];
  471. return ret;
  472. }
  473. Mat3x3 Mat3x3::operator-(const Mat3x3& other) const{
  474. Mat3x3 ret;
  475. for (int i=0; i<9; ++i) ret.v[i] = v[i] - other.v[i];
  476. return ret;
  477. }
  478. Mat3x3 Mat3x3::operator*(float scalar) const{
  479. Mat3x3 ret;
  480. for (int i=0; i<9; ++i) ret.v[i] = v[i] * scalar;
  481. return ret;
  482. }
  483. Mat3x3 Mat3x3::operator/(float scalar) const{
  484. Mat3x3 ret;
  485. for (int i=0; i<9; ++i) ret.v[i] = v[i] / scalar;
  486. return ret;
  487. }
  488. bool Mat3x3::operator==(const Mat3x3& other) const{
  489. for (int i=0; i<9; ++i){
  490. if (!isclose(v[i], other.v[i])) return false;
  491. }
  492. return true;
  493. }
  494. bool Mat3x3::operator!=(const Mat3x3& other) const{
  495. for (int i=0; i<9; ++i){
  496. if (!isclose(v[i], other.v[i])) return true;
  497. }
  498. return false;
  499. }
  500. Mat3x3 Mat3x3::matmul(const Mat3x3& other) const{
  501. Mat3x3 out;
  502. out._11 = _11 * other._11 + _12 * other._21 + _13 * other._31;
  503. out._12 = _11 * other._12 + _12 * other._22 + _13 * other._32;
  504. out._13 = _11 * other._13 + _12 * other._23 + _13 * other._33;
  505. out._21 = _21 * other._11 + _22 * other._21 + _23 * other._31;
  506. out._22 = _21 * other._12 + _22 * other._22 + _23 * other._32;
  507. out._23 = _21 * other._13 + _22 * other._23 + _23 * other._33;
  508. out._31 = _31 * other._11 + _32 * other._21 + _33 * other._31;
  509. out._32 = _31 * other._12 + _32 * other._22 + _33 * other._32;
  510. out._33 = _31 * other._13 + _32 * other._23 + _33 * other._33;
  511. return out;
  512. }
  513. Vec3 Mat3x3::matmul(const Vec3& other) const{
  514. Vec3 out;
  515. out.x = _11 * other.x + _12 * other.y + _13 * other.z;
  516. out.y = _21 * other.x + _22 * other.y + _23 * other.z;
  517. out.z = _31 * other.x + _32 * other.y + _33 * other.z;
  518. return out;
  519. }
  520. float Mat3x3::determinant() const{
  521. return _11 * _22 * _33 + _12 * _23 * _31 + _13 * _21 * _32
  522. - _11 * _23 * _32 - _12 * _21 * _33 - _13 * _22 * _31;
  523. }
  524. Mat3x3 Mat3x3::transpose() const{
  525. Mat3x3 ret;
  526. ret._11 = _11; ret._12 = _21; ret._13 = _31;
  527. ret._21 = _12; ret._22 = _22; ret._23 = _32;
  528. ret._31 = _13; ret._32 = _23; ret._33 = _33;
  529. return ret;
  530. }
  531. bool Mat3x3::inverse(Mat3x3& out) const{
  532. float det = determinant();
  533. if (isclose(det, 0)) return false;
  534. float inv_det = 1.0f / det;
  535. out._11 = (_22 * _33 - _23 * _32) * inv_det;
  536. out._12 = (_13 * _32 - _12 * _33) * inv_det;
  537. out._13 = (_12 * _23 - _13 * _22) * inv_det;
  538. out._21 = (_23 * _31 - _21 * _33) * inv_det;
  539. out._22 = (_11 * _33 - _13 * _31) * inv_det;
  540. out._23 = (_13 * _21 - _11 * _23) * inv_det;
  541. out._31 = (_21 * _32 - _22 * _31) * inv_det;
  542. out._32 = (_12 * _31 - _11 * _32) * inv_det;
  543. out._33 = (_11 * _22 - _12 * _21) * inv_det;
  544. return true;
  545. }
  546. Mat3x3 Mat3x3::trs(Vec2 t, float radian, Vec2 s){
  547. float cr = cosf(radian);
  548. float sr = sinf(radian);
  549. return Mat3x3(s.x * cr, -s.y * sr, t.x,
  550. s.x * sr, s.y * cr, t.y,
  551. 0.0f, 0.0f, 1.0f);
  552. }
  553. bool Mat3x3::is_affine() const{
  554. float det = _11 * _22 - _12 * _21;
  555. if(isclose(det, 0)) return false;
  556. return _31 == 0.0f && _32 == 0.0f && _33 == 1.0f;
  557. }
  558. Vec2 Mat3x3::_t() const { return Vec2(_13, _23); }
  559. float Mat3x3::_r() const { return atan2f(_21, _11); }
  560. Vec2 Mat3x3::_s() const {
  561. return Vec2(
  562. sqrtf(_11 * _11 + _21 * _21),
  563. sqrtf(_12 * _12 + _22 * _22)
  564. );
  565. }
  566. } // namespace pkpy