comparison semiconginev2/core/matrix.nim @ 1218:56781cc0fc7c compiletime-tests

did: renamge main package
author sam <sam@basx.dev>
date Wed, 17 Jul 2024 21:01:37 +0700
parents semicongine/core/matrix.nim@a3eb305bcac2
children c4f98eb4bb05
comparison
equal deleted inserted replaced
1217:f819a874058f 1218:56781cc0fc7c
1 export math
2
3 type
4 # layout is row-first
5 # having an object instead of directly aliasing the array seems a bit ugly at
6 # first, but is necessary to be able to work correctly with distinguished
7 # types (i.e. TMat23 and TMat32 would be an alias for the same type array[6, T]
8 # which prevents the type system from identifying the correct type at times)
9 #
10 # Though, great news is that objects have zero overhead!
11 TMat2*[T: SomeNumber] = object
12 data*: array[4, T]
13 TMat23*[T: SomeNumber] = object
14 data*: array[6, T]
15 TMat32*[T: SomeNumber] = object
16 data*: array[6, T]
17 TMat3*[T: SomeNumber] = object
18 data*: array[9, T]
19 TMat34*[T: SomeNumber] = object
20 data*: array[12, T]
21 TMat43*[T: SomeNumber] = object
22 data*: array[12, T]
23 TMat4*[T: SomeNumber] = object
24 data*: array[16, T]
25 TMat* = TMat2|TMat3|TMat4|TMat23|TMat32|TMat34|TMat43
26 Mat2* = TMat2[float32]
27 Mat23* = TMat23[float32]
28 Mat32* = TMat32[float32]
29 Mat3* = TMat3[float32]
30 Mat34* = TMat34[float32]
31 Mat43* = TMat43[float32]
32 Mat4* = TMat4[float32]
33
34 func MakeUnit2*[T: SomeNumber](): auto {.compiletime.} = TMat2[T](data: [
35 T(1), T(0),
36 T(0), T(1),
37 ])
38 func MakeUnit3*[T: SomeNumber](): auto {.compiletime.} = TMat3[T](data: [
39 T(1), T(0), T(0),
40 T(0), T(1), T(0),
41 T(0), T(0), T(1),
42 ])
43 func MakeUnit4*[T: SomeNumber](): auto {.compiletime.} = TMat4[T](data: [
44 T(1), T(0), T(0), T(0),
45 T(0), T(1), T(0), T(0),
46 T(0), T(0), T(1), T(0),
47 T(0), T(0), T(0), T(1),
48 ])
49
50 # generates constants: Unit
51 # Also for Y, Z, R, G, B
52 # not sure if this is necessary or even a good idea...
53 macro generateAllMatrixConsts() =
54 result = newStmtList()
55 for theType in ["int", "int8", "int16", "int32", "int64", "float", "float32", "float64"]:
56 var typename = theType[0 .. 0]
57 if theType[^2].isDigit:
58 typename = typename & theType[^2]
59 if theType[^1].isDigit:
60 typename = typename & theType[^1]
61 result.add(newConstStmt(
62 postfix(ident("Unit2" & typename), "*"),
63 newCall(nnkBracketExpr.newTree(ident("MakeUnit2"), ident(theType)))
64 ))
65 result.add(newConstStmt(
66 postfix(ident("Unit3" & typename), "*"),
67 newCall(nnkBracketExpr.newTree(ident("MakeUnit3"), ident(theType)))
68 ))
69 result.add(newConstStmt(
70 postfix(ident("Unit4" & typename), "*"),
71 newCall(nnkBracketExpr.newTree(ident("MakeUnit4"), ident(theType)))
72 ))
73
74 generateAllMatrixConsts()
75
76 const Unit2* = MakeUnit2[float32]()
77 const Unit3* = MakeUnit3[float32]()
78 const Unit4* = MakeUnit4[float32]()
79
80 template RowCount*(m: typedesc): int =
81 when m is TMat2: 2
82 elif m is TMat23: 2
83 elif m is TMat32: 3
84 elif m is TMat3: 3
85 elif m is TMat34: 3
86 elif m is TMat43: 4
87 elif m is TMat4: 4
88 template ColumnCount*(m: typedesc): int =
89 when m is TMat2: 2
90 elif m is TMat23: 3
91 elif m is TMat32: 2
92 elif m is TMat3: 3
93 elif m is TMat34: 4
94 elif m is TMat43: 3
95 elif m is TMat4: 4
96 template matlen(m: typedesc): int =
97 when m is TMat2: 4
98 elif m is TMat23: 6
99 elif m is TMat32: 6
100 elif m is TMat3: 9
101 elif m is TMat34: 12
102 elif m is TMat43: 12
103 elif m is TMat4: 16
104
105
106 func toString[T: TMat](value: T): string =
107 var
108 strvalues: seq[string]
109 maxwidth = 0
110
111 for n in value.data:
112 let strval = &"{float(n):.4f}"
113 strvalues.add(strval)
114 if strval.len > maxwidth:
115 maxwidth = strval.len
116
117 for i in 0 ..< strvalues.len:
118 let filler = " ".repeat(maxwidth - strvalues[i].len)
119 if i mod T.ColumnCount == T.ColumnCount - 1:
120 result &= filler & strvalues[i] & "\n"
121 else:
122 if i mod T.ColumnCount == 0:
123 result &= " "
124 result &= filler & strvalues[i] & " "
125
126 func `$`*(v: TMat2[SomeNumber]): string = toString[TMat2[SomeNumber]](v)
127 func `$`*(v: TMat23[SomeNumber]): string = toString[TMat23[SomeNumber]](v)
128 func `$`*(v: TMat32[SomeNumber]): string = toString[TMat32[SomeNumber]](v)
129 func `$`*(v: TMat3[SomeNumber]): string = toString[TMat3[SomeNumber]](v)
130 func `$`*(v: TMat34[SomeNumber]): string = toString[TMat34[SomeNumber]](v)
131 func `$`*(v: TMat43[SomeNumber]): string = toString[TMat43[SomeNumber]](v)
132 func `$`*(v: TMat4[SomeNumber]): string = toString[TMat4[SomeNumber]](v)
133
134 func `[]`*[T: TMat](m: T, row, col: int): auto = m.data[col + row * T.ColumnCount]
135 func `[]=`*[T: TMat, U](m: var T, row, col: int, value: U) = m.data[col + row * T.ColumnCount] = value
136 func `[]`*[T: TMat](m: T, i: int): auto = m.data[i]
137 func `[]=`*[T: TMat, U](m: var T, i: int, value: U) = m.data[i] = value
138
139 func Row*[T: TMat2](m: T, i: 0..1): auto = TVec2([m[i, 0], m[i, 1]])
140 func Row*[T: TMat32](m: T, i: 0..2): auto = TVec2([m[i, 0], m[i, 1]])
141 func Row*[T: TMat23](m: T, i: 0..1): auto = TVec3([m[i, 0], m[i, 1], m[i, 2]])
142 func Row*[T: TMat3](m: T, i: 0..2): auto = TVec3([m[i, 0], m[i, 1], m[i, 2]])
143 func Row*[T: TMat43](m: T, i: 0..3): auto = TVec3([m[i, 0], m[i, 1], m[i, 2]])
144 func Row*[T: TMat34](m: T, i: 0..2): auto = TVec4([m[i, 0], m[i, 1], m[i, 2], m[i, 3]])
145 func Row*[T: TMat4](m: T, i: 0..3): auto = TVec4([m[i, 0], m[i, 1], m[i, 2], m[i, 3]])
146
147 func Col*[T: TMat2](m: T, i: 0..1): auto = TVec2([m[0, i], m[1, i]])
148 func Col*[T: TMat23](m: T, i: 0..2): auto = TVec2([m[0, i], m[1, i]])
149 func Col*[T: TMat32](m: T, i: 0..1): auto = TVec3([m[0, i], m[1, i], m[2, i]])
150 func Col*[T: TMat3](m: T, i: 0..2): auto = TVec3([m[0, i], m[1, i], m[2, i]])
151 func Col*[T: TMat34](m: T, i: 0..3): auto = TVec3([m[0, i], m[1, i], m[2, i]])
152 func Col*[T: TMat43](m: T, i: 0..2): auto = TVec4([m[0, i], m[1, i], m[2, i], m[3, i]])
153 func Col*[T: TMat4](m: T, i: 0..3): auto = TVec4([m[0, i], m[1, i], m[2, i], m[3, i]])
154
155 proc createMatMatMultiplicationOperator(leftType: typedesc, rightType: typedesc, outType: typedesc): NimNode =
156 var data = nnkBracket.newTree()
157 for i in 0 ..< RowCount(leftType):
158 for j in 0 ..< rightType.ColumnCount:
159 data.add(newCall(
160 ident("sum"),
161 infix(
162 newCall(newDotExpr(ident("a"), ident("Row")), newLit(i)),
163 "*",
164 newCall(newDotExpr(ident("b"), ident("Col")), newLit(j))
165 )
166 ))
167
168 return newProc(
169 postfix(nnkAccQuoted.newTree(ident("*")), "*"),
170 params = [
171 ident("auto"),
172 newIdentDefs(ident("a"), ident(leftType.name)),
173 newIdentDefs(ident("b"), ident(rightType.name))
174 ],
175 body = nnkObjConstr.newTree(ident(outType.name), nnkExprColonExpr.newTree(ident("data"), data)),
176 procType = nnkFuncDef,
177 )
178
179 proc createMatMatAdditionOperator(theType: typedesc): NimNode =
180 var data = nnkBracket.newTree()
181 for i in 0 ..< matlen(theType):
182 data.add(
183 infix(
184 nnkBracketExpr.newTree(ident("a"), newLit(i)),
185 "+",
186 nnkBracketExpr.newTree(ident("b"), newLit(i)),
187 ))
188
189 return newProc(
190 postfix(nnkAccQuoted.newTree(ident("+")), "*"),
191 params = [
192 ident("auto"),
193 newIdentDefs(ident("a"), ident(theType.name)),
194 newIdentDefs(ident("b"), ident(theType.name))
195 ],
196 body = nnkObjConstr.newTree(ident(theType.name), nnkExprColonExpr.newTree(ident("data"), data)),
197 procType = nnkFuncDef,
198 )
199
200 proc createVecMatMultiplicationOperator(matType: typedesc, vecType: typedesc): NimNode =
201 var data = nnkBracket.newTree()
202 for i in 0 ..< matType.RowCount:
203 data.add(newCall(
204 ident("sum"),
205 infix(
206 ident("v"),
207 "*",
208 newCall(newDotExpr(ident("m"), ident("Row")), newLit(i))
209 )
210 ))
211
212 let resultVec = newCall(
213 nnkBracketExpr.newTree(ident(vecType.name), ident("T")),
214 data,
215 )
216 let name = postfix(nnkAccQuoted.newTree(ident("*")), "*")
217 let genericParams = nnkGenericParams.newTree(nnkIdentDefs.newTree(ident("T"), ident("SomeNumber"), newEmptyNode()))
218 let formalParams = nnkFormalParams.newTree(
219 ident("auto"),
220 newIdentDefs(ident("m"), nnkBracketExpr.newTree(ident(matType.name), ident("T"))),
221 newIdentDefs(ident("v"), nnkBracketExpr.newTree(ident(vecType.name), ident("T"))),
222 )
223
224 return nnkFuncDef.newTree(
225 name,
226 newEmptyNode(),
227 genericParams,
228 formalParams,
229 newEmptyNode(),
230 newEmptyNode(),
231 resultVec
232 )
233
234
235 proc createMatScalarOperator(matType: typedesc, op: string): NimNode =
236 result = newStmtList()
237
238 var data = nnkBracket.newTree()
239 for i in 0 ..< matType.RowCount * matType.ColumnCount:
240 data.add(infix(nnkBracketExpr.newTree(newDotExpr(ident("a"), ident("data")), newLit(i)), op, ident("b")))
241 result.add(newProc(
242 postfix(nnkAccQuoted.newTree(ident(op)), "*"),
243 params = [
244 ident("auto"),
245 newIdentDefs(ident("a"), ident(matType.name)),
246 newIdentDefs(ident("b"), ident("SomeNumber")),
247 ],
248 body = nnkObjConstr.newTree(ident(matType.name), nnkExprColonExpr.newTree(ident("data"), data)),
249 procType = nnkFuncDef,
250 ))
251 result.add(newProc(
252 postfix(nnkAccQuoted.newTree(ident(op)), "*"),
253 params = [
254 ident("auto"),
255 newIdentDefs(ident("b"), ident("SomeNumber")),
256 newIdentDefs(ident("a"), ident(matType.name)),
257 ],
258 body = nnkObjConstr.newTree(ident(matType.name), nnkExprColonExpr.newTree(ident("data"), data)),
259 procType = nnkFuncDef,
260 ))
261 if op == "-":
262 var data2 = nnkBracket.newTree()
263 for i in 0 ..< matType.RowCount * matType.ColumnCount:
264 data2.add(prefix(nnkBracketExpr.newTree(newDotExpr(ident("a"), ident("data")), newLit(i)), op))
265 result.add(newProc(
266 postfix(nnkAccQuoted.newTree(ident(op)), "*"),
267 params = [
268 ident("auto"),
269 newIdentDefs(ident("a"), ident(matType.name)),
270 ],
271 body = nnkObjConstr.newTree(ident(matType.name), nnkExprColonExpr.newTree(ident("data"), data2)),
272 procType = nnkFuncDef,
273 ))
274
275 macro createAllMultiplicationOperators() =
276 result = newStmtList()
277
278 for op in ["+", "-", "*", "/"]:
279 result.add(createMatScalarOperator(TMat2, op))
280 result.add(createMatScalarOperator(TMat23, op))
281 result.add(createMatScalarOperator(TMat32, op))
282 result.add(createMatScalarOperator(TMat3, op))
283 result.add(createMatScalarOperator(TMat34, op))
284 result.add(createMatScalarOperator(TMat43, op))
285 result.add(createMatScalarOperator(TMat4, op))
286
287 result.add(createMatMatMultiplicationOperator(TMat2, TMat2, TMat2))
288 result.add(createMatMatMultiplicationOperator(TMat2, TMat23, TMat23))
289 result.add(createMatMatMultiplicationOperator(TMat23, TMat32, TMat2))
290 result.add(createMatMatMultiplicationOperator(TMat23, TMat3, TMat23))
291 result.add(createMatMatMultiplicationOperator(TMat32, TMat2, TMat32))
292 result.add(createMatMatMultiplicationOperator(TMat32, TMat23, TMat3))
293 result.add(createMatMatMultiplicationOperator(TMat3, TMat32, TMat32))
294 result.add(createMatMatMultiplicationOperator(TMat3, TMat3, TMat3))
295 result.add(createMatMatMultiplicationOperator(TMat3, TMat34, TMat34))
296 result.add(createMatMatMultiplicationOperator(TMat43, TMat3, TMat43))
297 result.add(createMatMatMultiplicationOperator(TMat43, TMat34, TMat4))
298 result.add(createMatMatMultiplicationOperator(TMat4, TMat43, TMat43))
299 result.add(createMatMatMultiplicationOperator(TMat4, TMat4, TMat4))
300
301 result.add(createMatMatAdditionOperator(TMat2))
302 result.add(createMatMatAdditionOperator(TMat23))
303 result.add(createMatMatAdditionOperator(TMat32))
304 result.add(createMatMatAdditionOperator(TMat3))
305 result.add(createMatMatAdditionOperator(TMat34))
306 result.add(createMatMatAdditionOperator(TMat43))
307 result.add(createMatMatAdditionOperator(TMat4))
308
309 result.add(createVecMatMultiplicationOperator(TMat2, TVec2))
310 result.add(createVecMatMultiplicationOperator(TMat3, TVec3))
311 result.add(createVecMatMultiplicationOperator(TMat4, TVec4))
312
313 createAllMultiplicationOperators()
314
315 func `*`*(mat: Mat4, vec: Vec3f): Vec3f =
316 (mat * vec.ToVec4(1)).ToVec3
317
318 func Transposed*[T](m: TMat2[T]): TMat2[T] = TMat2[T](data: [
319 m[0, 0], m[1, 0],
320 m[0, 1], m[1, 1],
321 ])
322 func Transposed*[T](m: TMat23[T]): TMat32[T] = TMat32[T](data: [
323 m[0, 0], m[1, 0],
324 m[0, 1], m[1, 1],
325 m[0, 2], m[1, 2],
326 ])
327 func Transposed*[T](m: TMat32[T]): TMat23[T] = TMat23[T](data: [
328 m[0, 0], m[1, 0], m[2, 0],
329 m[0, 1], m[1, 1], m[2, 1],
330 ])
331 func Transposed*[T](m: TMat3[T]): TMat3[T] = TMat3[T](data: [
332 m[0, 0], m[1, 0], m[2, 0],
333 m[0, 1], m[1, 1], m[2, 1],
334 m[0, 2], m[1, 2], m[2, 2],
335 ])
336 func Transposed*[T](m: TMat43[T]): TMat34[T] = TMat34[T](data: [
337 m[0, 0], m[1, 0], m[2, 0], m[3, 0],
338 m[0, 1], m[1, 1], m[2, 1], m[3, 1],
339 m[0, 2], m[1, 2], m[2, 2], m[3, 2],
340 ])
341 func Transposed*[T](m: TMat34[T]): TMat43[T] = TMat43[T](data: [
342 m[0, 0], m[1, 0], m[2, 0],
343 m[0, 1], m[1, 1], m[2, 1],
344 m[0, 2], m[1, 2], m[2, 2],
345 m[0, 3], m[1, 3], m[2, 3],
346 ])
347 func Transposed*[T](m: TMat4[T]): TMat4[T] = TMat4[T](data: [
348 m[0, 0], m[1, 0], m[2, 0], m[3, 0],
349 m[0, 1], m[1, 1], m[2, 1], m[3, 1],
350 m[0, 2], m[1, 2], m[2, 2], m[3, 2],
351 m[0, 3], m[1, 3], m[2, 3], m[3, 3],
352 ])
353
354 func Translate2d*[T](x, y: T): TMat3[T] = TMat3[T](data: [
355 T(1), T(0), x,
356 T(0), T(1), y,
357 T(0), T(0), T(1),
358 ])
359 func Scale2d*[T](sx, sy: T): TMat3[T] = TMat3[T](data: [
360 sx, T(0), T(0),
361 T(0), sy, T(0),
362 T(0), T(0), T(1),
363 ])
364 func Rotate2d*[T](angle: T): TMat3[T] = TMat3[T](data: [
365 cos(angle), -sin(angle), T(0),
366 sin(angle), cos(angle), T(0),
367 T(0), T(0), T(1),
368 ])
369 func Translate*(x = 0'f32, y = 0'f32, z = 0'f32): TMat4[float32] = Mat4(data: [
370 1'f32, 0'f32, 0'f32, x,
371 0'f32, 1'f32, 0'f32, y,
372 0'f32, 0'f32, 1'f32, z,
373 0'f32, 0'f32, 0'f32, 1'f32,
374 ])
375 func Translate*[T: TVec3](v: T): TMat4[float32] = Translate(v[0], v[1], v[2])
376 func Scale*(x = 1'f32, y = 1'f32, z = 1'f32): Mat4 = Mat4(data: [
377 x, 0'f32, 0'f32, 0'f32,
378 0'f32, y, 0'f32, 0'f32,
379 0'f32, 0'f32, z, 0'f32,
380 0'f32, 0'f32, 0'f32, 1'f32,
381 ])
382 func Scale*[T: TVec3](v: T): TMat4[float32] = Scale(v[0], v[1], v[2])
383 func Rotate*(angle: float32, a: Vec3f): Mat4 =
384 let
385 cosa = cos(angle)
386 sina = sin(angle)
387 x = a[0]
388 y = a[1]
389 z = a[2]
390 Mat4(data: [
391 x * x * (1 - cosa) + cosa, y * x * (1 - cosa) - z * sina, z * x * (1 - cosa) + y * sina, 0'f32,
392 x * y * (1 - cosa) + z * sina, y * y * (1 - cosa) + cosa, z * y * (1 - cosa) - x * sina, 0'f32,
393 x * z * (1 - cosa) - y * sina, y * z * (1 - cosa) + x * sina, z * z * (1 - cosa) + cosa, 0'f32,
394 0'f32, 0'f32, 0'f32, 1'f32,
395 ])
396
397 func asMat3(m: Mat4): auto =
398 Mat3(data: [
399 m[0, 0], m[0, 1], m[0, 2],
400 m[1, 0], m[1, 1], m[1, 2],
401 m[2, 0], m[2, 1], m[2, 2],
402 ])
403
404
405 func Inversed*(m: Mat4): Mat4 =
406 var m3 = m.asMat3.Transposed
407 m3[0, 0] = 1'f32 / m3[0, 0]
408 m3[1, 1] = 1'f32 / m3[1, 1]
409 m3[2, 2] = 1'f32 / m3[2, 2]
410 let col3 = -(m3 * m.Col(3).xyz)
411 return Mat4(data: [
412 m3[0, 0], m3[0, 1], m3[0, 2], col3.x,
413 m3[1, 0], m3[1, 1], m3[1, 2], col3.y,
414 m3[2, 0], m3[2, 1], m3[2, 2], col3.z,
415 0, 0, 0, 1,
416 ])
417
418
419 # call e.g. TMat32[int]().randomized() to get a random matrix
420 template makeRandomMatrixInit(mattype: typedesc) =
421 proc Randomized*[T: SomeInteger](m: mattype[T]): mattype[T] =
422 for i in 0 ..< result.data.len:
423 result.data[i] = rand(low(typeof(m.data[0])) .. high(typeof(m.data[0])))
424 proc Randomized*[T: SomeFloat](m: mattype[T]): mattype[T] =
425 for i in 0 ..< result.data.len:
426 result.data[i] = rand(T(1.0))
427
428 makeRandomMatrixInit(TMat2)
429 makeRandomMatrixInit(TMat23)
430 makeRandomMatrixInit(TMat32)
431 makeRandomMatrixInit(TMat3)
432 makeRandomMatrixInit(TMat34)
433 makeRandomMatrixInit(TMat43)
434 makeRandomMatrixInit(TMat4)
435
436 func Perspective*(fovy, aspect, zNear, zFar: float32): Mat4 =
437 let tanHalfFovy = tan(fovy / 2)
438 return Mat4(data: [
439 1 / (aspect * tanHalfFovy), 0, 0, 0,
440 0, 1 / tanHalfFovy, 0, 0,
441 0, 0, zFar / (zFar - zNear), -(zFar * zNear) / (zFar - zNear),
442 0, 0, 1, 1,
443 ])
444
445 func Ortho*(left, right, top, bottom, zNear, zFar: float32): Mat4 =
446 Mat4(data: [
447 2 / (right - left), 0, 0, -(right + left) / (right - left),
448 0, 2 / (bottom - top), 0, -(bottom + top) / (bottom - top),
449 0, 0, 1 / (zFar - zNear), zNear / (zFar - zNear),
450 0, 0, 0, 1,
451 ])
452
453 # create an orthographic perspective that will map from -1 .. 1 on all axis and keep a 1:1 aspect ratio
454 # the smaller dimension (width or height) will always be 1 and the larger dimension will be larger, to keep the ratio
455 func OrthoWindowAspect*(windowAspect: float32): Mat4 =
456 if windowAspect < 1:
457 let space = 2 * (1 / windowAspect - 1) / 2
458 Ortho(-1, 1, -1 - space, 1 + space, 0, 1)
459 else:
460 let space = 2 * (windowAspect - 1) / 2
461 Ortho(-1 - space, 1 + space, -1, 1, 0, 1)
462
463 func Position*(mat: Mat4): Vec3f {.deprecated.} =
464 mat.Col(3).ToVec3
465
466 func Scaling*(mat: Mat4): Vec3f {.deprecated.} =
467 NewVec4f(mat[0, 0], mat[1, 1], mat[2, 2])