Skip to content
Snippets Groups Projects
Commit 136b7f7e authored by Jin Zijun's avatar Jin Zijun
Browse files

the vector functions

parent 95ae00c1
No related branches found
No related tags found
No related merge requests found
resources/images/TEST.bmp

469 KiB

#include "vector.h"
#include <math.h>
#include <stdbool.h>
Vec2i Vec2iNew(int x, int y)
{
Vec2i v;
v.x = x;
v.y = y;
return v;
}
Vec2i Vec2iZero(void)
{
return Vec2iNew(0, 0);
}
Vec2i Vec2iUnit(void)
{
return Vec2iNew(1, 1);
}
Vec2i Vec2iAdd(Vec2i a, Vec2i b)
{
a.x += b.x;
a.y += b.y;
return a;
}
Vec2i Vec2iMinus(Vec2i a, Vec2i b)
{
a.x -= b.x;
a.y -= b.y;
return a;
}
Vec2i Vec2iMult(const Vec2i a, const Vec2i b)
{
return Vec2iNew(a.x * b.x, a.y * b.y);
}
Vec2i Vec2iScale(Vec2i v, int scalar)
{
v.x *= scalar;
v.y *= scalar;
return v;
}
Vec2i Vec2iScaleDiv(Vec2i v, int scaleDiv)
{
v.x /= scaleDiv;
v.y /= scaleDiv;
return v;
}
bool Vec2iEqual(const Vec2i a, const Vec2i b)
{
return a.x == b.x && a.y == b.y;
}
bool Vec2iIsZero(const Vec2i v)
{
return Vec2iEqual(v, Vec2iZero());
}
Vec2i Vec2iNorm(Vec2i v) //模长
{
double magnitude;
if (Vec2iIsZero(v))
{
return v;
}
magnitude = sqrt(v.x*v.x + v.y*v.y);
v.x = (int)floor(v.x / magnitude + 0.5); //(int)floor-> 求不大于某个数的最大整数
v.y = (int)floor(v.y / magnitude + 0.5);
return v;
}
Vec2i Vec2iClamp(Vec2i v, Vec2i lo, Vec2i hi)
{
v.x = CLAMP(v.x, lo.x, hi.x);
v.y = CLAMP(v.y, lo.y, hi.y);
return v;
}
int DistanceSquared(Vec2i a, Vec2i b)
{
int dx = a.x - b.x;
int dy = a.y - b.y;
return dx*dx + dy*dy;
}
#pragma once
#include <stdbool.h>
#define MAX(x, y) ((x) > (y) ? (x) : (y))
#define MIN(x, y) ((x) < (y) ? (x) : (y))
#define CLAMP(v, _min, _max) MAX((_min), MIN((_max), (v))) //若v在[min,max]范围内,则等于v;如果v小于min,则返回min;如果v大于max,则返回max。
typedef struct
{
int x;
int y;
} Vec2i;
Vec2i Vec2iNew(int x, int y);
Vec2i Vec2iZero(void); //(0, 0)
Vec2i Vec2iUnit(void); // (1, 1)
Vec2i Vec2iAdd(Vec2i a, Vec2i b);
Vec2i Vec2iMinus(Vec2i a, Vec2i b);
Vec2i Vec2iMult(const Vec2i a, const Vec2i b);
Vec2i Vec2iScale(Vec2i v, int scalar);
Vec2i Vec2iScaleDiv(Vec2i v, int scaleDiv);
bool Vec2iEqual(const Vec2i a, const Vec2i b);
bool Vec2iIsZero(const Vec2i v);
Vec2i Vec2iNorm(Vec2i v);
Vec2i Vec2iClamp(Vec2i v, Vec2i lo, Vec2i hi);
int DistanceSquared(Vec2i a, Vec2i b);
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment