summaryrefslogtreecommitdiffstats
path: root/vector
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--vector/makefile18
-rw-r--r--vector/vectors.c107
2 files changed, 125 insertions, 0 deletions
diff --git a/vector/makefile b/vector/makefile
new file mode 100644
index 0000000..6ce8fd9
--- /dev/null
+++ b/vector/makefile
@@ -0,0 +1,18 @@
+CARGS := -Wall -Werror -I.
+CPPARGS := -Wall -Werror -I.
+
+all: cpp-vector.pdf c_build/vectors
+
+%.pdf: %.md
+ pandoc \
+ --latex-engine=xelatex \
+ --filter pandoc-include-code \
+ $< -o $@
+
+c_build/%: %.c
+ mkdir -p c_build
+ gcc $(CARGS) $< -o $@
+
+cpp_build/%: %.cpp
+ mkdir -p cpp_build
+ g++ $(CPPARGS) $< -o $@
diff --git a/vector/vectors.c b/vector/vectors.c
new file mode 100644
index 0000000..c8a5906
--- /dev/null
+++ b/vector/vectors.c
@@ -0,0 +1,107 @@
+#include <stddef.h>
+#include <stdio.h>
+
+struct vec3 {
+ double x;
+ double y;
+ double z;
+};
+
+struct vec3 vec3_add(struct vec3 * const v, struct vec3 * const u)
+{
+ struct vec3 result = {0, 0, 0};
+
+ if (v == NULL || u == NULL)
+ return result;
+
+ result.x = v->x + u->x;
+ result.y = v->y + u->y;
+ result.z = v->z + u->z;
+
+ return result;
+}
+
+struct vec3 vec3_mul(struct vec3 * const v, const double scalar)
+{
+ struct vec3 result = {0, 0, 0};
+
+ if (v == NULL)
+ return result;
+
+ result.x = scalar * v->x;
+ result.y = scalar * v->y;
+ result.z = scalar * v->z;
+
+ return result;
+}
+
+struct vec3 vec3_sub(struct vec3 * const v, struct vec3 * const u)
+{
+ struct vec3 result = {0, 0, 0};
+
+ result = vec3_mul(u, -1.0);
+ result = vec3_add(v, &result);
+
+ return result;
+}
+
+double vec3_dot(struct vec3 * const v, struct vec3 * const u)
+{
+ if (v == NULL || u == NULL)
+ return 0;
+
+ return (v->x * u->x) + (v->y * u->y) + (v->z * u->y);
+}
+
+struct vec3 vec3_cross(struct vec3 * const v, struct vec3 * const u)
+{
+ struct vec3 result = {0, 0, 0};
+
+ result.x = (v->y * u->z) - (v->z * u->y);
+ result.y = (v->z * u->x) - (v->x * u->z);
+ result.z = (v->x * u->y) - (v->y * u->x);
+
+ return result;
+}
+
+void vec3_print(struct vec3 * const v)
+{
+ if (v == NULL)
+ return;
+
+ printf("<%.2f,%.2f,%.2f>\n", v->x, v->y, v->y);
+}
+
+
+int main(int argc, char *argv[])
+{
+ struct vec3 a = {1, 2, 3};
+ struct vec3 b = {4, 5, 6};
+ struct vec3 res;
+
+ printf("a = ");
+ vec3_print(&a);
+ printf("b = ");
+ vec3_print(&b);
+
+ printf("sum a + b : ");
+ res = vec3_add(&a, &b);
+ vec3_print(&res);
+
+ printf("sub a - b : ");
+ res = vec3_sub(&a, &b);
+ vec3_print(&res);
+
+ printf("product 3*a : ");
+ res = vec3_mul(&a, 3);
+ vec3_print(&res);
+
+ printf("dot product : ");
+ printf("%.2f\n", vec3_dot(&a, &b));
+
+ printf("cross product : ");
+ res = vec3_cross(&a, &b);
+ vec3_print(&res);
+
+ return 0;
+}