Skip to content

Commit

Permalink
feat(⨯): New vector functions
Browse files Browse the repository at this point in the history
  • Loading branch information
wcandillon authored Apr 29, 2020
1 parent b84ae5b commit 97a7529
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 5 deletions.
23 changes: 20 additions & 3 deletions packages/core/src/Vectors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,11 @@ const apply = (fn: Fn, ...vectors: Adaptable[]) => ({

const add = (...vectors: BinArgOp) => apply(Animated.add, ...vectors);
const sub = (...vectors: BinArgOp) => apply(Animated.sub, ...vectors);
const dot = (...vectors: BinArgOp) => apply(Animated.multiply, ...vectors);
const div = (...vectors: BinArgOp) => apply(Animated.divide, ...vectors);
const mul = (...vectors: BinArgOp) => apply(Animated.multiply, ...vectors);
const pow = (...vectors: [Adaptable, number]) =>
apply(Animated.pow, ...vectors);
const sqrt = (...vectors: SingleArgOp) => apply(Animated.sqrt, ...vectors);
const cos = (...vectors: SingleArgOp) => apply(Animated.cos, ...vectors);
const sin = (...vectors: SingleArgOp) => apply(Animated.sin, ...vectors);
const min = (vector: Adaptable, value: Animated.Adaptable<number>) =>
Expand All @@ -58,14 +61,22 @@ const max = (vector: Adaptable, value: Animated.Adaptable<number>) =>
const clamp = (value: Adaptable, minVec: Adaptable, maxVec: Adaptable) =>
apply(clamp1, value, minVec, maxVec);

const invert = (a: Adaptable) => dot(-1, a);
const invert = (a: Adaptable) => mul(-1, a);

const set = (a: Vector<Animated.Value<number>>, b: Adaptable) =>
block([
Animated.set(a.x, isAdaptable(b) ? b : b.x),
Animated.set(a.y, isAdaptable(b) ? b : b.y),
]);

const length = (v: Vector) =>
Animated.sqrt(Animated.add(Animated.pow(v.x, 2), Animated.pow(v.y, 2)));
const normalize = (v: Vector) => div(v, length(v));
const dot = (v1: Vector, v2: Vector) =>
add(Animated.multiply(v1.x, v2.x), Animated.multiply(v1.y, v2.y));
const cross = (v1: Vector, v2: Vector) =>
sub(Animated.multiply(v1.x, v2.y), Animated.multiply(v1.y, v2.x));

export const vec = {
create,
createValue,
Expand All @@ -74,13 +85,19 @@ export const vec = {
sub,
dot,
div,
multiply: dot,
mul,
multiply: mul,
divide: div,
pow,
sqrt,
set,
clamp,
apply,
min,
max,
cos,
sin,
length,
normalize,
cross,
};
4 changes: 2 additions & 2 deletions packages/core/src/__tests__/Vectors.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,8 @@ test("multiply", () => {
const c = vec.create(1, 1);
const d = vec.create(2, 2);
const result = vec.createValue(2, 2);
expect(vec.dot(a, b, c, d)).toEqual(result);
expect(vec.dot(2, 1, 1, 1)).toEqual(result);
expect(vec.mul(a, b, c, d)).toEqual(result);
expect(vec.mul(2, 1, 1, 1)).toEqual(result);
});

test("divide", () => {
Expand Down

0 comments on commit 97a7529

Please sign in to comment.