-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmat.c
More file actions
105 lines (94 loc) · 2.71 KB
/
Copy pathmat.c
File metadata and controls
105 lines (94 loc) · 2.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#include "mat.h"
#include <malloc.h>
#include <memory.h>
#include <stdlib.h>
mat _mat_init_matrix(int linear_size_x, int linear_size_y) {
mat m;
m.size_x = linear_size_x;
m.size_y = linear_size_y;
m.data = (float*)malloc(sizeof(float)*linear_size_x*linear_size_y);
return m;
}
void _mat_free_matrix(mat *mat) {
free(mat->data);
}
float* _mat_index_data(mat *mat, int x, int y) {
return mat->data+(y*mat->size_x)+x;
}
float* _mat4_index_data(mat4x4 *mat, int x, int y) {
return (*mat)+(y*4)+x;
}
float* _mat2_index_data(mat2x2 *mat, int x, int y) {
return (*mat)+(y*2)+x;
}
void _mat4_mult(mat4x4* _restrict m1, mat4x4* _restrict m2, mat4x4 *buf) {
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 4; ++j) {
float sum = 0.0f;
for (int k = 0; k < 4; ++k) {
sum += (*_mat4_index_data(m1, i, k)) * (*_mat4_index_data(m2, k, j));
}
*_mat4_index_data(buf, i, j) = sum;
}
}
}
void _mat2_mult(mat2x2* _restrict m1, mat2x2* _restrict m2, mat2x2 *buf) {
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 2; ++j) {
float sum = 0.0f;
for (int k = 0; k < 2; ++k) {
sum += (*_mat2_index_data(m1, i, k)) * (*_mat2_index_data(m2, k, j));
}
*_mat2_index_data(buf, i, j) = sum;
}
}
}
mat _mat_mult(mat* _restrict m1, mat* _restrict m2) {
if (m1->size_y != m2->size_x) {
exit(1);
}
const int rows = m1->size_x;
const int cols = m2->size_y;
const int inner = m1->size_y;
mat prod = _mat_init_matrix(rows, cols);
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
float sum = 0.0f;
for (int k = 0; k < inner; ++k) {
sum += (*_mat_index_data(m1, i, k)) * (*_mat_index_data(m2, k, j));
}
*_mat_index_data(&prod, i, j) = sum;
}
}
return prod;
}
void _mat4_mult_vec(mat4x4* m,
float x, float y, float z, float w,
float *destX, float *destY, float *destZ, float *destW
) {
const float vec[4] = { x, y, z, w };
float sum[4] = { 0, 0, 0, 0 };
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 4; ++j) {
sum[i] += (*_mat4_index_data(m, i, j)) * vec[j];
}
}
*destX = sum[0];
*destY = sum[1];
*destZ = sum[2];
*destW = sum[3];
}
void _mat2_mult_vec(mat2x2* m,
float x, float y,
float *destX, float *destY
) {
const float vec[2] = { x, y };
float sum[2] = { 0, 0 };
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 2; ++j) {
sum[i] += (*_mat2_index_data(m, i, j)) * vec[j];
}
}
*destX = sum[0];
*destY = sum[1];
}