载入中...
搜索中...
未找到
Math.cpp
浏览该文件的文档.
1#include "math/Math.h"
2#include "math/Vec2.h"
3#include "math/Vec3.h"
4#include "math/Mat4.h"
5#include "math/Steering.h"
6
7#include "common/Exception.h"
8
9#include <simplesquirrel/simplesquirrel.hpp>
10
11#include <glm/glm.hpp>
12#include <glm/gtc/matrix_transform.hpp>
13#include <glm/gtc/noise.hpp>
14
15#include <algorithm>
16#include <cctype>
17#include <chrono>
18#include <cmath>
19#include <cstdint>
20#include <sstream>
21#include <string>
22#include <string_view>
23#include <vector>
24
25#ifndef M_PI
26#define M_PI 3.14159265358979323846
27#endif
28
29namespace eve::math {
30namespace {
31
32float clamp01(float t) { return std::clamp(t, 0.f, 1.f); }
33
34float noiseToUnit(float n) {
35 // glm::simplex / perlin is roughly [-1, 1]; map to [0, 1] like LÖVE.
36 return clamp01(n * 0.5f + 0.5f);
37}
38
39float hash11(float p) {
40 p = p - std::floor(p);
41 p *= 0.1031f;
42 p = p - std::floor(p);
43 p *= p + 33.33f;
44 p *= p + p;
45 return p - std::floor(p);
46}
47
48float hash21(float x, float y) {
49 glm::vec3 p3 = glm::fract(glm::vec3(x, y, x) * 0.1031f);
50 p3 += glm::dot(p3, glm::vec3(p3.y + 33.33f, p3.z + 33.33f, p3.x + 33.33f));
51 return glm::fract((p3.x + p3.y) * p3.z);
52}
53
54float hash31(float x, float y, float z) {
55 glm::vec3 p3 = glm::fract(glm::vec3(x, y, z) * 0.1031f);
56 p3 += glm::dot(p3, glm::vec3(p3.y + 33.33f, p3.z + 33.33f, p3.x + 33.33f));
57 return glm::fract((p3.x + p3.y) * p3.z);
58}
59
60bool parseSteeringCoordinate(std::string_view field, float &value) {
61 std::string input(field);
62 std::size_t consumed = 0;
63 try {
64 value = std::stof(input, &consumed);
65 } catch (...) {
66 return false;
67 }
68 while (consumed < input.size() &&
69 std::isspace(static_cast<unsigned char>(input[consumed])) != 0)
70 ++consumed;
71 return consumed == input.size() && std::isfinite(value);
72}
73
74std::vector<steering::Vector2> parseSteeringPoints2(const std::string &text) {
75 std::vector<steering::Vector2> result;
76 std::stringstream input(text);
77 std::string point;
78 while (std::getline(input, point, ',')) {
79 const auto separator = point.find(':');
80 if (separator == std::string::npos || point.find(':', separator + 1) != std::string::npos)
81 continue;
82 steering::Vector2 value;
83 if (parseSteeringCoordinate(std::string_view(point).substr(0, separator), value.x) &&
84 parseSteeringCoordinate(std::string_view(point).substr(separator + 1), value.y))
85 result.push_back(value);
86 }
87 return result;
88}
89
90std::vector<steering::Vector3> parseSteeringPoints3(const std::string &text) {
91 std::vector<steering::Vector3> result;
92 std::stringstream input(text);
93 std::string point;
94 while (std::getline(input, point, ',')) {
95 const auto first = point.find(':');
96 const auto second = first == std::string::npos ? first : point.find(':', first + 1);
97 if (first == std::string::npos || second == std::string::npos ||
98 point.find(':', second + 1) != std::string::npos)
99 continue;
100 steering::Vector3 value;
101 if (parseSteeringCoordinate(std::string_view(point).substr(0, first), value.x) &&
102 parseSteeringCoordinate(
103 std::string_view(point).substr(first + 1, second - first - 1), value.y) &&
104 parseSteeringCoordinate(std::string_view(point).substr(second + 1), value.z))
105 result.push_back(value);
106 }
107 return result;
108}
109
110glm::vec2 voronoiPoint(int ix, int iy) {
111 float hx = hash21(float(ix), float(iy));
112 float hy = hash21(float(ix) + 19.19f, float(iy) + 47.47f);
113 return glm::vec2(float(ix) + hx, float(iy) + hy);
114}
115
116void voronoiF1F2(float x, float y, float &f1, float &f2) {
117 int ix = int(std::floor(x));
118 int iy = int(std::floor(y));
119 f1 = 1e9f;
120 f2 = 1e9f;
121 for (int j = -1; j <= 1; ++j) {
122 for (int i = -1; i <= 1; ++i) {
123 glm::vec2 p = voronoiPoint(ix + i, iy + j);
124 float d = glm::length(glm::vec2(x, y) - p);
125 if (d < f1) {
126 f2 = f1;
127 f1 = d;
128 } else if (d < f2) {
129 f2 = d;
130 }
131 }
132 }
133}
134
135} // namespace
136
138
139Math::Math() : seed_(1), rng_(1) {}
140
141Vec2 *Math::newVec2(float x, float y) { return new Vec2(x, y); }
142Vec3 *Math::newVec3(float x, float y, float z) { return new Vec3(x, y, z); }
143
144Mat4 *Math::newMat4() { return new Mat4(); }
145
146Mat4 *Math::newMat4Translation(float x, float y, float z) {
147 auto *m = new Mat4();
148 m->translate(x, y, z);
149 return m;
150}
151
152Mat4 *Math::newMat4Scale(float sx, float sy, float sz) {
153 auto *m = new Mat4();
154 m->scale(sx, sy, sz);
155 return m;
156}
157
159 auto *m = new Mat4();
160 m->rotateZ(radians);
161 return m;
162}
163
164float Math::clamp(float x, float lo, float hi) const {
165 if (lo > hi) std::swap(lo, hi);
166 return std::clamp(x, lo, hi);
167}
168
169float Math::lerp(float a, float b, float t) const { return a + (b - a) * t; }
170
171float Math::smoothstep(float edge0, float edge1, float x) const {
172 if (edge0 == edge1) return x < edge0 ? 0.f : 1.f;
173 float t = clamp01((x - edge0) / (edge1 - edge0));
174 return t * t * (3.f - 2.f * t);
175}
176
177float Math::remap(float x, float inMin, float inMax, float outMin, float outMax) const {
178 if (inMin == inMax) return outMin;
179 float t = (x - inMin) / (inMax - inMin);
180 return outMin + (outMax - outMin) * t;
181}
182
183float Math::degToRad(float deg) const { return deg * float(M_PI) / 180.f; }
184float Math::radToDeg(float rad) const { return rad * 180.f / float(M_PI); }
185
186float Math::sign(float x) const {
187 if (x > 0.f) return 1.f;
188 if (x < 0.f) return -1.f;
189 return 0.f;
190}
191
192float Math::fract(float x) const { return x - std::floor(x); }
193
194float Math::approach(float current, float target, float maxDelta) const {
195 float d = target - current;
196 if (std::fabs(d) <= maxDelta) return target;
197 return current + sign(d) * maxDelta;
198}
199
200float Math::wrap(float x, float lo, float hi) const {
201 if (lo == hi) return lo;
202 if (lo > hi) std::swap(lo, hi);
203 float range = hi - lo;
204 float t = std::fmod(x - lo, range);
205 if (t < 0.f) t += range;
206 return lo + t;
207}
208
209float Math::pingPong(float t, float length) const {
210 if (length <= 0.f) return 0.f;
211 t = wrap(t, 0.f, length * 2.f);
212 return length - std::fabs(t - length);
213}
214
215Vec2 *Math::steeringSeek2(float x, float y, float targetX, float targetY, float maxSpeed) const {
217 steering::Vector2{targetX, targetY}, maxSpeed);
218 return new Vec2(value.x, value.y);
219}
220
221Vec3 *Math::steeringSeek3(float x, float y, float z, float targetX, float targetY, float targetZ,
222 float maxSpeed) const {
223 const auto value = steering::seek({x, y, z}, {targetX, targetY, targetZ}, maxSpeed);
224 return new Vec3(value.x, value.y, value.z);
225}
226
227Vec2 *Math::steeringFlee2(float x, float y, float targetX, float targetY, float maxSpeed) const {
229 steering::Vector2{targetX, targetY}, maxSpeed);
230 return new Vec2(value.x, value.y);
231}
232
233Vec3 *Math::steeringFlee3(float x, float y, float z, float targetX, float targetY, float targetZ,
234 float maxSpeed) const {
235 const auto value = steering::flee({x, y, z}, {targetX, targetY, targetZ}, maxSpeed);
236 return new Vec3(value.x, value.y, value.z);
237}
238
239Vec2 *Math::steeringArrive2(float x, float y, float targetX, float targetY, float maxSpeed,
240 float slowRadius, float stopRadius) const {
241 const auto value =
243 slowRadius, stopRadius);
244 return new Vec2(value.x, value.y);
245}
246
247Vec3 *Math::steeringArrive3(float x, float y, float z, float targetX, float targetY, float targetZ,
248 float maxSpeed, float slowRadius, float stopRadius) const {
249 const auto value = steering::arrive({x, y, z}, {targetX, targetY, targetZ}, maxSpeed,
250 slowRadius, stopRadius);
251 return new Vec3(value.x, value.y, value.z);
252}
253
254Vec2 *Math::steeringSeparation2(float x, float y, const std::string &neighbors, float radius,
255 float maxAcceleration) const {
256 const auto parsed = parseSteeringPoints2(neighbors);
257 const auto value =
259 return new Vec2(value.x, value.y);
260}
261
262Vec3 *Math::steeringSeparation3(float x, float y, float z, const std::string &neighbors,
263 float radius, float maxAcceleration) const {
264 const auto parsed = parseSteeringPoints3(neighbors);
265 const auto value = steering::separation({x, y, z}, parsed, radius, maxAcceleration);
266 return new Vec3(value.x, value.y, value.z);
267}
268
269int Math::steeringPathTarget2(float x, float y, const std::string &points, int current,
270 float tolerance) const {
271 const auto parsed = parseSteeringPoints2(points);
272 return steering::pathTarget(steering::Vector2{x, y}, parsed, current, tolerance);
273}
274
275int Math::steeringPathTarget3(float x, float y, float z, const std::string &points, int current,
276 float tolerance) const {
277 const auto parsed = parseSteeringPoints3(points);
278 return steering::pathTarget({x, y, z}, parsed, current, tolerance);
279}
280
281Vec2 *Math::steeringAvoid2(float x, float y, float velocityX, float velocityY, float obstacleX,
282 float obstacleY, float obstacleRadius, float lookAhead,
283 float maxAcceleration) const {
284 const auto value =
285 steering::avoid(steering::Vector2{x, y}, steering::Vector2{velocityX, velocityY},
286 steering::Vector2{obstacleX, obstacleY}, obstacleRadius, lookAhead,
288 return new Vec2(value.x, value.y);
289}
290
291Vec3 *Math::steeringAvoid3(float x, float y, float z, float velocityX, float velocityY,
292 float velocityZ, float obstacleX, float obstacleY, float obstacleZ,
293 float obstacleRadius, float lookAhead, float maxAcceleration) const {
294 const auto value = steering::avoid({x, y, z}, {velocityX, velocityY, velocityZ},
295 {obstacleX, obstacleY, obstacleZ}, obstacleRadius, lookAhead,
297 return new Vec3(value.x, value.y, value.z);
298}
299
300float Math::inverseLerp(float a, float b, float x) const {
301 if (a == b) return 0.f;
302 return (x - a) / (b - a);
303}
304
305float Math::smootherstep(float edge0, float edge1, float x) const {
306 if (edge0 == edge1) return x < edge0 ? 0.f : 1.f;
307 float t = clamp01((x - edge0) / (edge1 - edge0));
308 return t * t * t * (t * (t * 6.f - 15.f) + 10.f);
309}
310
311float Math::bias(float t, float b) const {
312 t = clamp01(t);
313 if (b <= 0.f) return 0.f;
314 if (b >= 1.f) return 1.f;
315 return t / ((1.f / b - 2.f) * (1.f - t) + 1.f);
316}
317
318float Math::gain(float t, float g) const {
319 t = clamp01(t);
320 if (t < 0.5f) return bias(t * 2.f, g) * 0.5f;
321 return bias(t * 2.f - 1.f, 1.f - g) * 0.5f + 0.5f;
322}
323
324float Math::ease(float t, const std::string &kind) const {
325 t = clamp01(t);
326 if (kind == "linear" || kind.empty()) return t;
327 if (kind == "inQuad") return t * t;
328 if (kind == "outQuad") return 1.f - (1.f - t) * (1.f - t);
329 if (kind == "inOutQuad")
330 return t < 0.5f ? 2.f * t * t : 1.f - std::pow(-2.f * t + 2.f, 2.f) * 0.5f;
331 if (kind == "inCubic") return t * t * t;
332 if (kind == "outCubic") return 1.f - std::pow(1.f - t, 3.f);
333 if (kind == "inOutCubic")
334 return t < 0.5f ? 4.f * t * t * t : 1.f - std::pow(-2.f * t + 2.f, 3.f) * 0.5f;
335 if (kind == "inSine") return 1.f - std::cos(t * float(M_PI) * 0.5f);
336 if (kind == "outSine") return std::sin(t * float(M_PI) * 0.5f);
337 if (kind == "inOutSine") return -(std::cos(float(M_PI) * t) - 1.f) * 0.5f;
338 if (kind == "inExpo") return t <= 0.f ? 0.f : std::pow(2.f, 10.f * t - 10.f);
339 if (kind == "outExpo") return t >= 1.f ? 1.f : 1.f - std::pow(2.f, -10.f * t);
340 if (kind == "inOutExpo") {
341 if (t <= 0.f) return 0.f;
342 if (t >= 1.f) return 1.f;
343 return t < 0.5f ? std::pow(2.f, 20.f * t - 10.f) * 0.5f
344 : (2.f - std::pow(2.f, -20.f * t + 10.f)) * 0.5f;
345 }
346 throw Exception("Math.ease: unknown kind '%s'", kind.c_str());
347}
348
349float Math::step(float edge, float x) const { return x < edge ? 0.f : 1.f; }
350
351float Math::quantize(float x, float stepSize) const {
352 if (stepSize == 0.f) return x;
353 return std::floor(x / stepSize) * stepSize;
354}
355
356float Math::snap(float x, float grid) const {
357 if (grid == 0.f) return x;
358 return std::round(x / grid) * grid;
359}
360
361float Math::length2(float x, float y) const { return std::sqrt(x * x + y * y); }
362float Math::length3(float x, float y, float z) const {
363 return std::sqrt(x * x + y * y + z * z);
364}
365
366float Math::distance2(float x1, float y1, float x2, float y2) const {
367 return length2(x2 - x1, y2 - y1);
368}
369
370float Math::distance3(float x1, float y1, float z1, float x2, float y2, float z2) const {
371 return length3(x2 - x1, y2 - y1, z2 - z1);
372}
373
374float Math::dot2(float x1, float y1, float x2, float y2) const { return x1 * x2 + y1 * y2; }
375float Math::dot3(float x1, float y1, float z1, float x2, float y2, float z2) const {
376 return x1 * x2 + y1 * y2 + z1 * z2;
377}
378
379float Math::cross2(float x1, float y1, float x2, float y2) const { return x1 * y2 - y1 * x2; }
380float Math::angle2(float x, float y) const { return std::atan2(y, x); }
381
382float Math::angleBetween2(float x1, float y1, float x2, float y2) const {
383 return std::atan2(y2, x2) - std::atan2(y1, x1);
384}
385
386float Math::lerpAngle(float a, float b, float t) const {
387 float twoPi = float(M_PI) * 2.f;
388 float diff = std::fmod(b - a + float(M_PI), twoPi);
389 if (diff < 0.f) diff += twoPi;
390 diff -= float(M_PI);
391 return a + diff * t;
392}
393
394float Math::normalize2X(float x, float y) const {
395 float len = length2(x, y);
396 return len > 0.f ? x / len : 0.f;
397}
398float Math::normalize2Y(float x, float y) const {
399 float len = length2(x, y);
400 return len > 0.f ? y / len : 0.f;
401}
402float Math::normalize3X(float x, float y, float z) const {
403 float len = length3(x, y, z);
404 return len > 0.f ? x / len : 0.f;
405}
406float Math::normalize3Y(float x, float y, float z) const {
407 float len = length3(x, y, z);
408 return len > 0.f ? y / len : 0.f;
409}
410float Math::normalize3Z(float x, float y, float z) const {
411 float len = length3(x, y, z);
412 return len > 0.f ? z / len : 0.f;
413}
414
415float Math::rotate2X(float x, float y, float radians) const {
416 float c = std::cos(radians), s = std::sin(radians);
417 return x * c - y * s;
418}
419float Math::rotate2Y(float x, float y, float radians) const {
420 float c = std::cos(radians), s = std::sin(radians);
421 return x * s + y * c;
422}
423
424float Math::polarX(float radius, float radians) const { return radius * std::cos(radians); }
425float Math::polarY(float radius, float radians) const { return radius * std::sin(radians); }
426float Math::cartesianRadius(float x, float y) const { return length2(x, y); }
427float Math::cartesianAngle(float x, float y) const { return angle2(x, y); }
428
429bool Math::pointInCircle(float px, float py, float cx, float cy, float radius) const {
430 if (radius < 0.f) return false;
431 return distance2(px, py, cx, cy) <= radius;
432}
433
434bool Math::pointInRect(float px, float py, float rx, float ry, float rw, float rh) const {
435 return px >= rx && py >= ry && px <= rx + rw && py <= ry + rh;
436}
437
438bool Math::circlesOverlap(float x1, float y1, float r1, float x2, float y2, float r2) const {
439 if (r1 < 0.f || r2 < 0.f) return false;
440 float rr = r1 + r2;
441 float dx = x2 - x1, dy = y2 - y1;
442 return dx * dx + dy * dy <= rr * rr;
443}
444
445bool Math::rectsOverlap(float x1, float y1, float w1, float h1, float x2, float y2, float w2,
446 float h2) const {
447 return x1 <= x2 + w2 && x1 + w1 >= x2 && y1 <= y2 + h2 && y1 + h1 >= y2;
448}
449
450bool Math::circleRectOverlap(float cx, float cy, float radius, float rx, float ry, float rw,
451 float rh) const {
452 if (radius < 0.f) return false;
453 float nearestX = std::clamp(cx, rx, rx + rw);
454 float nearestY = std::clamp(cy, ry, ry + rh);
455 float dx = cx - nearestX, dy = cy - nearestY;
456 return dx * dx + dy * dy <= radius * radius;
457}
458
459bool Math::segmentsIntersect(float ax, float ay, float bx, float by, float cx, float cy, float dx,
460 float dy) const {
461 auto orient = [](float px, float py, float qx, float qy, float rx, float ry) {
462 return (qy - py) * (rx - qx) - (qx - px) * (ry - qy);
463 };
464 auto onSeg = [](float px, float py, float qx, float qy, float rx, float ry) {
465 return std::min(px, rx) <= qx && qx <= std::max(px, rx) && std::min(py, ry) <= qy &&
466 qy <= std::max(py, ry);
467 };
468 float o1 = orient(ax, ay, bx, by, cx, cy);
469 float o2 = orient(ax, ay, bx, by, dx, dy);
470 float o3 = orient(cx, cy, dx, dy, ax, ay);
471 float o4 = orient(cx, cy, dx, dy, bx, by);
472 if (o1 * o2 < 0.f && o3 * o4 < 0.f) return true;
473 constexpr float eps = 1e-6f;
474 if (std::fabs(o1) <= eps && onSeg(ax, ay, cx, cy, bx, by)) return true;
475 if (std::fabs(o2) <= eps && onSeg(ax, ay, dx, dy, bx, by)) return true;
476 if (std::fabs(o3) <= eps && onSeg(cx, cy, ax, ay, dx, dy)) return true;
477 if (std::fabs(o4) <= eps && onSeg(cx, cy, bx, by, dx, dy)) return true;
478 return false;
479}
480
481float Math::raycastCircle2(float ox, float oy, float dx, float dy, float cx, float cy,
482 float radius) const {
483 if (radius < 0.f) return -1.f;
484 float fx = ox - cx, fy = oy - cy;
485 float a = dx * dx + dy * dy;
486 if (a <= 1e-12f) return -1.f;
487 float b = 2.f * (fx * dx + fy * dy);
488 float c = fx * fx + fy * fy - radius * radius;
489 float disc = b * b - 4.f * a * c;
490 if (disc < 0.f) return -1.f;
491 float s = std::sqrt(disc);
492 float t0 = (-b - s) / (2.f * a);
493 float t1 = (-b + s) / (2.f * a);
494 if (t0 >= 0.f) return t0;
495 if (t1 >= 0.f) return t1;
496 return -1.f;
497}
498
499float Math::raycastRect2(float ox, float oy, float dx, float dy, float rx, float ry, float rw,
500 float rh) const {
501 constexpr float inf = 1e30f;
502 float tMin = 0.f;
503 float tMax = inf;
504 auto slab = [&](float o, float d, float minV, float maxV) -> bool {
505 if (std::fabs(d) < 1e-12f) {
506 return o >= minV && o <= maxV;
507 }
508 float inv = 1.f / d;
509 float t1 = (minV - o) * inv;
510 float t2 = (maxV - o) * inv;
511 if (t1 > t2) std::swap(t1, t2);
512 tMin = std::max(tMin, t1);
513 tMax = std::min(tMax, t2);
514 return tMin <= tMax;
515 };
516 if (!slab(ox, dx, rx, rx + rw)) return -1.f;
517 if (!slab(oy, dy, ry, ry + rh)) return -1.f;
518 if (tMax < 0.f) return -1.f;
519 return tMin >= 0.f ? tMin : 0.f;
520}
521
522namespace {
523float closestSegmentT(float px, float py, float ax, float ay, float bx, float by) {
524 float abx = bx - ax, aby = by - ay;
525 float denom = abx * abx + aby * aby;
526 if (denom <= 1e-12f) return 0.f;
527 float t = ((px - ax) * abx + (py - ay) * aby) / denom;
528 return std::clamp(t, 0.f, 1.f);
529}
530float closestSegmentT3(float px, float py, float pz, float ax, float ay, float az, float bx,
531 float by, float bz) {
532 float abx = bx - ax, aby = by - ay, abz = bz - az;
533 float denom = abx * abx + aby * aby + abz * abz;
534 if (denom <= 1e-12f) return 0.f;
535 float t = ((px - ax) * abx + (py - ay) * aby + (pz - az) * abz) / denom;
536 return std::clamp(t, 0.f, 1.f);
537}
538} // namespace
539
540float Math::closestPointOnSegment2X(float px, float py, float ax, float ay, float bx,
541 float by) const {
542 float t = closestSegmentT(px, py, ax, ay, bx, by);
543 return ax + (bx - ax) * t;
544}
545float Math::closestPointOnSegment2Y(float px, float py, float ax, float ay, float bx,
546 float by) const {
547 float t = closestSegmentT(px, py, ax, ay, bx, by);
548 return ay + (by - ay) * t;
549}
550
551bool Math::pointInSphere(float px, float py, float pz, float cx, float cy, float cz,
552 float radius) const {
553 if (radius < 0.f) return false;
554 return distance3(px, py, pz, cx, cy, cz) <= radius;
555}
556
557bool Math::pointInBox(float px, float py, float pz, float minX, float minY, float minZ, float maxX,
558 float maxY, float maxZ) const {
559 return px >= minX && px <= maxX && py >= minY && py <= maxY && pz >= minZ && pz <= maxZ;
560}
561
562bool Math::spheresOverlap(float x1, float y1, float z1, float r1, float x2, float y2, float z2,
563 float r2) const {
564 if (r1 < 0.f || r2 < 0.f) return false;
565 float rr = r1 + r2;
566 float dx = x2 - x1, dy = y2 - y1, dz = z2 - z1;
567 return dx * dx + dy * dy + dz * dz <= rr * rr;
568}
569
570bool Math::boxesOverlap(float minAx, float minAy, float minAz, float maxAx, float maxAy,
571 float maxAz, float minBx, float minBy, float minBz, float maxBx,
572 float maxBy, float maxBz) const {
573 return minAx <= maxBx && maxAx >= minBx && minAy <= maxBy && maxAy >= minBy &&
574 minAz <= maxBz && maxAz >= minBz;
575}
576
577float Math::raycastSphere(float ox, float oy, float oz, float dx, float dy, float dz, float cx,
578 float cy, float cz, float radius) const {
579 if (radius < 0.f) return -1.f;
580 float fx = ox - cx, fy = oy - cy, fz = oz - cz;
581 float a = dx * dx + dy * dy + dz * dz;
582 if (a <= 1e-12f) return -1.f;
583 float b = 2.f * (fx * dx + fy * dy + fz * dz);
584 float c = fx * fx + fy * fy + fz * fz - radius * radius;
585 float disc = b * b - 4.f * a * c;
586 if (disc < 0.f) return -1.f;
587 float s = std::sqrt(disc);
588 float t0 = (-b - s) / (2.f * a);
589 float t1 = (-b + s) / (2.f * a);
590 if (t0 >= 0.f) return t0;
591 if (t1 >= 0.f) return t1;
592 return -1.f;
593}
594
595float Math::raycastBox(float ox, float oy, float oz, float dx, float dy, float dz, float minX,
596 float minY, float minZ, float maxX, float maxY, float maxZ) const {
597 constexpr float inf = 1e30f;
598 float tMin = 0.f;
599 float tMax = inf;
600 auto slab = [&](float o, float d, float minV, float maxV) -> bool {
601 if (std::fabs(d) < 1e-12f) {
602 return o >= minV && o <= maxV;
603 }
604 float inv = 1.f / d;
605 float t1 = (minV - o) * inv;
606 float t2 = (maxV - o) * inv;
607 if (t1 > t2) std::swap(t1, t2);
608 tMin = std::max(tMin, t1);
609 tMax = std::min(tMax, t2);
610 return tMin <= tMax;
611 };
612 if (!slab(ox, dx, minX, maxX)) return -1.f;
613 if (!slab(oy, dy, minY, maxY)) return -1.f;
614 if (!slab(oz, dz, minZ, maxZ)) return -1.f;
615 if (tMax < 0.f) return -1.f;
616 return tMin >= 0.f ? tMin : 0.f;
617}
618
619float Math::raycastPlane(float ox, float oy, float oz, float dx, float dy, float dz, float px,
620 float py, float pz, float nx, float ny, float nz) const {
621 float denom = nx * dx + ny * dy + nz * dz;
622 if (std::fabs(denom) < 1e-12f) return -1.f;
623 float t = (nx * (px - ox) + ny * (py - oy) + nz * (pz - oz)) / denom;
624 return t >= 0.f ? t : -1.f;
625}
626
627float Math::closestPointOnSegment3X(float px, float py, float pz, float ax, float ay, float az,
628 float bx, float by, float bz) const {
629 float t = closestSegmentT3(px, py, pz, ax, ay, az, bx, by, bz);
630 return ax + (bx - ax) * t;
631}
632float Math::closestPointOnSegment3Y(float px, float py, float pz, float ax, float ay, float az,
633 float bx, float by, float bz) const {
634 float t = closestSegmentT3(px, py, pz, ax, ay, az, bx, by, bz);
635 return ay + (by - ay) * t;
636}
637float Math::closestPointOnSegment3Z(float px, float py, float pz, float ax, float ay, float az,
638 float bx, float by, float bz) const {
639 float t = closestSegmentT3(px, py, pz, ax, ay, az, bx, by, bz);
640 return az + (bz - az) * t;
641}
642
643float Math::bilinear(float v00, float v10, float v01, float v11, float u, float v) const {
644 float a = lerp(v00, v10, u);
645 float b = lerp(v01, v11, u);
646 return lerp(a, b, v);
647}
648
649void Math::setRandomSeed(uint32_t seed) {
650 seed_ = seed == 0 ? 1u : seed;
651 rng_.seed(seed_);
652}
653
655 auto us = std::chrono::duration_cast<std::chrono::microseconds>(
656 std::chrono::steady_clock::now().time_since_epoch())
657 .count();
658 setRandomSeed(static_cast<uint32_t>(us) ^ 0xA5A5A5A5u);
659}
660
661uint32_t Math::getRandomSeed() const { return seed_; }
662
664 std::uniform_real_distribution<float> dist(0.f, 1.f);
665 return dist(rng_);
666}
667
668float Math::randomRange(float min, float max) {
669 if (min > max) std::swap(min, max);
670 std::uniform_real_distribution<float> dist(min, max);
671 return dist(rng_);
672}
673
674int Math::randomInt(int min, int maxInclusive) {
675 if (min > maxInclusive) std::swap(min, maxInclusive);
676 std::uniform_int_distribution<int> dist(min, maxInclusive);
677 return dist(rng_);
678}
679
680float Math::randomGaussian(float mean, float stddev) {
681 std::normal_distribution<float> dist(mean, stddev);
682 return dist(rng_);
683}
684
685float Math::hash1(float x) const { return hash11(x); }
686float Math::hash2(float x, float y) const { return hash21(x, y); }
687float Math::hash3(float x, float y, float z) const { return hash31(x, y, z); }
688
689float Math::noise1(float x) const { return noiseToUnit(glm::simplex(glm::vec2(x, 0.f))); }
690float Math::noise2(float x, float y) const { return noiseToUnit(glm::simplex(glm::vec2(x, y))); }
691float Math::noise3(float x, float y, float z) const {
692 return noiseToUnit(glm::simplex(glm::vec3(x, y, z)));
693}
694
695float Math::simplex1(float x) const { return noise1(x); }
696float Math::simplex2(float x, float y) const { return noise2(x, y); }
697float Math::simplex3(float x, float y, float z) const { return noise3(x, y, z); }
698
699float Math::perlin2(float x, float y) const { return noiseToUnit(glm::perlin(glm::vec2(x, y))); }
700float Math::perlin3(float x, float y, float z) const {
701 return noiseToUnit(glm::perlin(glm::vec3(x, y, z)));
702}
703
704float Math::white2(float x, float y) const { return hash21(std::floor(x), std::floor(y)); }
705
706float Math::value2(float x, float y) const {
707 const float x0 = std::floor(x);
708 const float y0 = std::floor(y);
709 const float fx = x - x0;
710 const float fy = y - y0;
711 const float u = fx * fx * (3.f - 2.f * fx);
712 const float v = fy * fy * (3.f - 2.f * fy);
713 const float n00 = hash21(x0, y0);
714 const float n10 = hash21(x0 + 1.f, y0);
715 const float n01 = hash21(x0, y0 + 1.f);
716 const float n11 = hash21(x0 + 1.f, y0 + 1.f);
717 const float nx0 = n00 + (n10 - n00) * u;
718 const float nx1 = n01 + (n11 - n01) * u;
719 return nx0 + (nx1 - nx0) * v;
720}
721
722float Math::fbm2(float x, float y, int octaves, float lacunarity, float gain) const {
723 if (octaves < 1) octaves = 1;
724 if (octaves > 16) octaves = 16;
725 float sum = 0.f, amp = 1.f, freq = 1.f, norm = 0.f;
726 for (int i = 0; i < octaves; ++i) {
727 sum += noise2(x * freq, y * freq) * amp;
728 norm += amp;
729 amp *= gain;
730 freq *= lacunarity;
731 }
732 return norm > 0.f ? sum / norm : 0.f;
733}
734
735float Math::fbm3(float x, float y, float z, int octaves, float lacunarity, float gain) const {
736 if (octaves < 1) octaves = 1;
737 if (octaves > 16) octaves = 16;
738 float sum = 0.f, amp = 1.f, freq = 1.f, norm = 0.f;
739 for (int i = 0; i < octaves; ++i) {
740 sum += noise3(x * freq, y * freq, z * freq) * amp;
741 norm += amp;
742 amp *= gain;
743 freq *= lacunarity;
744 }
745 return norm > 0.f ? sum / norm : 0.f;
746}
747
748float Math::ridged2(float x, float y, int octaves, float lacunarity, float gain) const {
749 if (octaves < 1) octaves = 1;
750 if (octaves > 16) octaves = 16;
751 float sum = 0.f, amp = 0.5f, freq = 1.f, prev = 1.f;
752 for (int i = 0; i < octaves; ++i) {
753 float n = noise2(x * freq, y * freq);
754 n = 1.f - std::fabs(n * 2.f - 1.f);
755 n = n * n;
756 sum += n * amp * prev;
757 prev = n;
758 freq *= lacunarity;
759 amp *= gain;
760 }
761 return clamp01(sum);
762}
763
764float Math::ridged3(float x, float y, float z, int octaves, float lacunarity, float gain) const {
765 if (octaves < 1) octaves = 1;
766 if (octaves > 16) octaves = 16;
767 float sum = 0.f, amp = 0.5f, freq = 1.f, prev = 1.f;
768 for (int i = 0; i < octaves; ++i) {
769 float n = noise3(x * freq, y * freq, z * freq);
770 n = 1.f - std::fabs(n * 2.f - 1.f);
771 n = n * n;
772 sum += n * amp * prev;
773 prev = n;
774 freq *= lacunarity;
775 amp *= gain;
776 }
777 return clamp01(sum);
778}
779
780float Math::turbulence2(float x, float y, int octaves, float lacunarity, float gain) const {
781 if (octaves < 1) octaves = 1;
782 if (octaves > 16) octaves = 16;
783 float sum = 0.f, amp = 1.f, freq = 1.f, norm = 0.f;
784 for (int i = 0; i < octaves; ++i) {
785 sum += std::fabs(noise2(x * freq, y * freq) * 2.f - 1.f) * amp;
786 norm += amp;
787 amp *= gain;
788 freq *= lacunarity;
789 }
790 return norm > 0.f ? clamp01(sum / norm) : 0.f;
791}
792
793float Math::billow2(float x, float y, int octaves, float lacunarity, float gain) const {
794 return turbulence2(x, y, octaves, lacunarity, gain);
795}
796
797float Math::voronoi2(float x, float y) const {
798 float f1, f2;
799 voronoiF1F2(x, y, f1, f2);
800 return f1;
801}
802
803float Math::voronoiEdge2(float x, float y) const {
804 float f1, f2;
805 voronoiF1F2(x, y, f1, f2);
806 return f2 - f1;
807}
808
809float Math::worley2(float x, float y) const { return clamp01(1.f - voronoi2(x, y)); }
810
811float Math::warpNoise2(float x, float y, float warpAmp) const {
812 float wx = noise2(x, y) - 0.5f;
813 float wy = noise2(x + 5.2f, y + 1.3f) - 0.5f;
814 return noise2(x + wx * warpAmp, y + wy * warpAmp);
815}
816
817float Math::warpNoise2Deep(float x, float y, float warpAmp) const {
818 const float qx = noise2(x, y) - 0.5f;
819 const float qy = noise2(x + 5.2f, y + 1.3f) - 0.5f;
820 const float rx = noise2(x + warpAmp * qx + 1.7f, y + warpAmp * qy + 9.2f) - 0.5f;
821 const float ry = noise2(x + warpAmp * qx + 8.3f, y + warpAmp * qy + 2.8f) - 0.5f;
822 return noise2(x + warpAmp * rx, y + warpAmp * ry);
823}
824
825float Math::voronoiF2_2(float x, float y) const {
826 float f1, f2;
827 voronoiF1F2(x, y, f1, f2);
828 return f2;
829}
830
831float Math::worleyManhattan2(float x, float y) const {
832 const int ix = int(std::floor(x));
833 const int iy = int(std::floor(y));
834 float f1 = 1e9f;
835 for (int j = -1; j <= 1; ++j) {
836 for (int i = -1; i <= 1; ++i) {
837 const glm::vec2 p = voronoiPoint(ix + i, iy + j);
838 f1 = std::min(f1, std::fabs(x - p.x) + std::fabs(y - p.y));
839 }
840 }
841 return f1;
842}
843
844float Math::worleyChebyshev2(float x, float y) const {
845 const int ix = int(std::floor(x));
846 const int iy = int(std::floor(y));
847 float f1 = 1e9f;
848 for (int j = -1; j <= 1; ++j) {
849 for (int i = -1; i <= 1; ++i) {
850 const glm::vec2 p = voronoiPoint(ix + i, iy + j);
851 f1 = std::min(f1, std::max(std::fabs(x - p.x), std::fabs(y - p.y)));
852 }
853 }
854 return f1;
855}
856
857float Math::worleySmooth2(float x, float y, float smoothness) const {
858 smoothness = std::max(1e-4f, smoothness);
859 const int ix = int(std::floor(x));
860 const int iy = int(std::floor(y));
861 float acc = 0.f;
862 for (int j = -1; j <= 1; ++j) {
863 for (int i = -1; i <= 1; ++i) {
864 const glm::vec2 p = voronoiPoint(ix + i, iy + j);
865 const float dx = x - p.x;
866 const float dy = y - p.y;
867 acc += std::exp(-(dx * dx + dy * dy) / (smoothness * smoothness));
868 }
869 }
870 return clamp01(1.f - std::exp(-acc));
871}
872
873float Math::curlNoise2X(float x, float y, float eps) const {
874 eps = std::max(eps, 1e-6f);
875 return (value2(x, y + eps) - value2(x, y - eps)) / (2.f * eps);
876}
877
878float Math::curlNoise2Y(float x, float y, float eps) const {
879 eps = std::max(eps, 1e-6f);
880 return -(value2(x + eps, y) - value2(x - eps, y)) / (2.f * eps);
881}
882
883float Math::hexDistance2(float x, float y) const {
884 constexpr float hexFactor = 0.86602540378f;
885 auto posMod = [](float v, float m) {
886 float r = std::fmod(v, m);
887 return r < 0.f ? r + m : r;
888 };
889 const float gposX = x / hexFactor;
890 float hx = std::floor(gposX);
891 float hy = std::floor(y);
892 const float sy = (posMod(hx + 1.f, 4.f) >= 2.f) ? 1.f : 0.f;
893 hx += posMod(hx, 2.f);
894 hy += posMod(hy + sy, 2.f);
895 float gdx = gposX - hx;
896 float gdy = y - hy;
897 if (std::fabs(gdx) * (hexFactor * hexFactor) + std::fabs(gdy) * 0.5f > 1.f) {
898 hx += (gdx >= 0.f ? 1.f : -1.f) * 2.f;
899 hy += (gdy >= 0.f ? 1.f : -1.f);
900 }
901 float px = std::fabs(x - hx * hexFactor);
902 float py = std::fabs(y - hy);
903 return std::fabs(std::max(px * hexFactor + py * 0.5f, py) - 1.f);
904}
905
906float Math::hexEdge2(float x, float y, float width, float soft) const {
907 const float d = hexDistance2(x, y);
908 const float band = std::max(soft, 1e-4f);
909 const float t = clamp01((d - width) / band);
910 return 1.f - (t * t * (3.f - 2.f * t));
911}
912
913float Math::gyroid3(float x, float y, float z) const {
914 const float g = std::sin(x) * std::cos(y) + std::sin(y) * std::cos(z) + std::sin(z) * std::cos(x);
915 return clamp01(g / 3.f * 0.5f + 0.5f);
916}
917
918float Math::gyroidFbm3(float x, float y, float z, int octaves) const {
919 if (octaves < 1) octaves = 1;
920 if (octaves > 8) octaves = 8;
921 float result = 0.f, a = 0.5f, seedZ = z, norm = 0.f;
922 for (int i = 0; i < octaves; ++i) {
923 seedZ += result * 0.5f;
924 const float g = std::sin(x / a) * std::cos(y / a) + std::sin(y / a) * std::cos(seedZ / a) +
925 std::sin(seedZ / a) * std::cos(x / a);
926 result += std::fabs(g) * a;
927 norm += a;
928 a *= 0.5f;
929 }
930 return norm > 0.f ? clamp01(result / (norm * 1.5f)) : 0.f;
931}
932
933float Math::swiss2(float x, float y, int octaves, float lacunarity, float gain, float warpStrength) const {
934 if (octaves < 1) octaves = 1;
935 if (octaves > 16) octaves = 16;
936 float sum = 0.f, amp = 1.f, norm = 0.f, freq = 1.f;
937 float px = x, py = y;
938 for (int i = 0; i < octaves; ++i) {
939 const float n = value2(px, py) * 2.f - 1.f;
940 sum += n * amp;
941 norm += amp;
942 freq *= lacunarity;
943 px = x * freq + sum * warpStrength;
944 py = y * freq + sum * warpStrength;
945 amp *= gain;
946 }
947 return norm > 0.f ? clamp01(sum / norm * 0.5f + 0.5f) : 0.5f;
948}
949
950float Math::hybrid2(float x, float y, int octaves, float lacunarity, float gain, float offset) const {
951 if (octaves < 1) octaves = 1;
952 if (octaves > 16) octaves = 16;
953 float freq = 1.f;
954 float signal = (value2(x, y) + offset) * gain;
955 float result = signal;
956 float weight = clamp01(signal);
957 float amp = gain;
958 float norm = 1.f;
959 for (int i = 1; i < octaves; ++i) {
960 freq *= lacunarity;
961 amp *= gain;
962 signal = (value2(x * freq, y * freq) + offset) * gain;
963 result += weight * signal * amp;
964 norm += amp;
965 weight = clamp01(weight * signal);
966 }
967 return norm > 0.f ? clamp01(result / (norm * (1.f + offset))) : 0.f;
968}
969
970float Math::jordan2(float x, float y, int octaves, float lacunarity, float gain, float warpStrength) const {
971 if (octaves < 1) octaves = 1;
972 if (octaves > 16) octaves = 16;
973 float sum = 0.f, amp = 1.f, norm = 0.f, freq = 1.f;
974 float dx = 0.f, dy = 0.f;
975 constexpr float kEps = 1e-3f;
976 for (int i = 0; i < octaves; ++i) {
977 const float px = x * freq + dx * warpStrength;
978 const float py = y * freq + dy * warpStrength;
979 const float n = value2(px, py) * 2.f - 1.f;
980 const float dnx = (value2(px + kEps, py) - value2(px - kEps, py)) / (2.f * kEps);
981 const float dny = (value2(px, py + kEps) - value2(px, py - kEps)) / (2.f * kEps);
982 sum += n * amp;
983 norm += amp;
984 dx += dnx * amp;
985 dy += dny * amp;
986 amp *= gain;
987 freq *= lacunarity;
988 }
989 return norm > 0.f ? clamp01(sum / norm * 0.5f + 0.5f) : 0.5f;
990}
991
992float Math::gabor2(float x, float y, float dirX, float dirY, float frequency) const {
993 const int ix = int(std::floor(x));
994 const int iy = int(std::floor(y));
995 const float fx = x - float(ix);
996 const float fy = y - float(iy);
997 constexpr float kCellVar = 0.8f;
998 constexpr float kDirVar = 0.4f;
999 float va = 0.f;
1000 float wt = 0.f;
1001 for (int j = -1; j <= 1; ++j) {
1002 for (int i = -1; i <= 1; ++i) {
1003 const float cx = float(ix + i);
1004 const float cy = float(iy + j);
1005 const float hx = hash21(cx, cy) - 0.5f;
1006 const float hy = hash21(cx * 3.f + 11.f, cy * 7.f + 5.f) - 0.5f;
1007 const float ox = float(i) - 0.5f;
1008 const float oy = float(j) - 0.5f;
1009 const float ppx = fx + ox - hx;
1010 const float ppy = fy + oy - hy;
1011 const float d2 = ppx * ppx + ppy * ppy;
1012 const float w = std::exp(-d2 * 4.f);
1013 const float dx = kDirVar * hx + dirX;
1014 const float dy = kDirVar * hy + dirY;
1015 wt += w;
1016 va += std::cos((ppx * dx + ppy * dy) * frequency / kCellVar) * w;
1017 }
1018 }
1019 return wt > 0.f ? clamp01(va / wt * 0.5f + 0.5f) : 0.5f;
1020}
1021
1022float Math::gaborFbm2(float x, float y, int octaves, float dirX, float dirY) const {
1023 if (octaves < 1) octaves = 1;
1024 if (octaves > 8) octaves = 8;
1025 float sum = 0.f, freq = 1.f, norm = 0.f, amp = 1.f;
1026 float px = x, py = y;
1027 for (int i = 0; i < octaves; ++i) {
1028 const float n = gabor2(px * freq, py * freq, dirX, dirY, 6.2831853f) * 2.f - 1.f;
1029 sum += std::fabs(n) * amp;
1030 norm += amp;
1031 px += -0.01f * sum;
1032 py += 0.07f * sum;
1033 amp *= 0.5f;
1034 freq *= 2.2f;
1035 }
1036 return norm > 0.f ? clamp01(sum / norm) : 0.f;
1037}
1038
1039float Math::valueDx2(float x, float y, float eps) const {
1040 eps = std::max(eps, 1e-6f);
1041 return (value2(x + eps, y) - value2(x - eps, y)) / (2.f * eps);
1042}
1043
1044float Math::valueDy2(float x, float y, float eps) const {
1045 eps = std::max(eps, 1e-6f);
1046 return (value2(x, y + eps) - value2(x, y - eps)) / (2.f * eps);
1047}
1048
1049float Math::valueSlope2(float x, float y, float eps) const {
1050 const float dx = valueDx2(x, y, eps);
1051 const float dy = valueDy2(x, y, eps);
1052 return std::sqrt(dx * dx + dy * dy);
1053}
1054
1055float Math::isoLine2(float x, float y, int levels, float width) const {
1056 if (levels < 1) levels = 1;
1057 width = std::max(1e-4f, width);
1058 const float n = value2(x, y);
1059 const float scaled = n * float(levels);
1060 const float v = std::fabs(std::fmod(scaled + 0.5f, 1.f) - 0.5f);
1061 const float t = clamp01(v / width);
1062 return 1.f - (t * t * (3.f - 2.f * t));
1063}
1064
1065float Math::banding2(float x, float y, int bands) const {
1066 if (bands < 1) bands = 1;
1067 const float n = value2(x, y);
1068 return std::floor(n * float(bands)) / float(bands);
1069}
1070
1071float Math::fbmColor2(float x, float y, int channel, int octaves, float lacunarity, float gain) const {
1072 channel = ((channel % 3) + 3) % 3;
1073 static constexpr float ox[3] = {0.f, 19.1f, 5.2f};
1074 static constexpr float oy[3] = {0.f, 7.3f, 31.7f};
1075 return fbm2(x + ox[channel], y + oy[channel], octaves, lacunarity, gain);
1076}
1077
1078float Math::white3(float x, float y, float z) const { return hash31(std::floor(x), std::floor(y), std::floor(z)); }
1079
1080float Math::value3(float x, float y, float z) const {
1081 const float x0 = std::floor(x);
1082 const float y0 = std::floor(y);
1083 const float z0 = std::floor(z);
1084 const float fx = x - x0;
1085 const float fy = y - y0;
1086 const float fz = z - z0;
1087 const float u = fx * fx * (3.f - 2.f * fx);
1088 const float v = fy * fy * (3.f - 2.f * fy);
1089 const float w = fz * fz * (3.f - 2.f * fz);
1090 const float n000 = hash31(x0, y0, z0);
1091 const float n100 = hash31(x0 + 1.f, y0, z0);
1092 const float n010 = hash31(x0, y0 + 1.f, z0);
1093 const float n110 = hash31(x0 + 1.f, y0 + 1.f, z0);
1094 const float n001 = hash31(x0, y0, z0 + 1.f);
1095 const float n101 = hash31(x0 + 1.f, y0, z0 + 1.f);
1096 const float n011 = hash31(x0, y0 + 1.f, z0 + 1.f);
1097 const float n111 = hash31(x0 + 1.f, y0 + 1.f, z0 + 1.f);
1098 const float nx00 = n000 + (n100 - n000) * u;
1099 const float nx10 = n010 + (n110 - n010) * u;
1100 const float nx01 = n001 + (n101 - n001) * u;
1101 const float nx11 = n011 + (n111 - n011) * u;
1102 const float nxy0 = nx00 + (nx10 - nx00) * v;
1103 const float nxy1 = nx01 + (nx11 - nx01) * v;
1104 return nxy0 + (nxy1 - nxy0) * w;
1105}
1106
1107float Math::worley3(float x, float y, float z) const {
1108 const int ix = int(std::floor(x));
1109 const int iy = int(std::floor(y));
1110 const int iz = int(std::floor(z));
1111 float f1 = 1e9f;
1112 for (int k = -1; k <= 1; ++k) {
1113 for (int j = -1; j <= 1; ++j) {
1114 for (int i = -1; i <= 1; ++i) {
1115 const float cx = float(ix + i);
1116 const float cy = float(iy + j);
1117 const float cz = float(iz + k);
1118 const float px = cx + hash31(cx, cy, cz);
1119 const float py = cy + hash31(cx + 19.f, cy + 47.f, cz + 3.f);
1120 const float pz = cz + hash31(cx + 7.f, cy + 13.f, cz + 29.f);
1121 const float dx = x - px;
1122 const float dy = y - py;
1123 const float dz = z - pz;
1124 f1 = std::min(f1, std::sqrt(dx * dx + dy * dy + dz * dz));
1125 }
1126 }
1127 }
1128 return clamp01(1.f - f1);
1129}
1130
1131float Math::bezierQuadratic(float t, float p0, float p1, float p2) const {
1132 t = clamp01(t);
1133 float u = 1.f - t;
1134 return u * u * p0 + 2.f * u * t * p1 + t * t * p2;
1135}
1136
1137float Math::bezierCubic(float t, float p0, float p1, float p2, float p3) const {
1138 t = clamp01(t);
1139 float u = 1.f - t;
1140 float uu = u * u;
1141 float tt = t * t;
1142 return uu * u * p0 + 3.f * uu * t * p1 + 3.f * u * tt * p2 + tt * t * p3;
1143}
1144
1145float Math::bezierQuadratic2X(float t, float x0, float /*y0*/, float x1, float /*y1*/, float x2,
1146 float /*y2*/) const {
1147 return bezierQuadratic(t, x0, x1, x2);
1148}
1149
1150float Math::bezierQuadratic2Y(float t, float /*x0*/, float y0, float /*x1*/, float y1, float /*x2*/,
1151 float y2) const {
1152 return bezierQuadratic(t, y0, y1, y2);
1153}
1154
1155float Math::bezierCubic2X(float t, float x0, float /*y0*/, float x1, float /*y1*/, float x2,
1156 float /*y2*/, float x3, float /*y3*/) const {
1157 return bezierCubic(t, x0, x1, x2, x3);
1158}
1159
1160float Math::bezierCubic2Y(float t, float /*x0*/, float y0, float /*x1*/, float y1, float /*x2*/,
1161 float y2, float /*x3*/, float y3) const {
1162 return bezierCubic(t, y0, y1, y2, y3);
1163}
1164
1165void Math::expose(ssq::Table &table) {
1166 auto cls = table.addClass(name, Math::create, false);
1167 expose(cls);
1168
1169 auto v2 = table.addClass<Vec2>(
1170 "Vec2", std::function<Vec2 *()>([]() -> Vec2 * { return nullptr; }), true);
1171 v2.addFunc("getX", &Vec2::getX);
1172 v2.addFunc("getY", &Vec2::getY);
1173 v2.addFunc("setX", &Vec2::setX);
1174 v2.addFunc("setY", &Vec2::setY);
1175 v2.addFunc("set", &Vec2::set);
1176 v2.addFunc("length", &Vec2::length);
1177 v2.addFunc("lengthSquared", &Vec2::lengthSquared);
1178 v2.addFunc("normalize", &Vec2::normalize);
1179 v2.addFunc("normalized", &Vec2::normalized);
1180 v2.addFunc("dot", &Vec2::dot);
1181 v2.addFunc("cross", &Vec2::cross);
1182 v2.addFunc("distanceTo", &Vec2::distanceTo);
1183 v2.addFunc("angle", &Vec2::angle);
1184 v2.addFunc("add", &Vec2::add);
1185 v2.addFunc("sub", &Vec2::sub);
1186 v2.addFunc("scale", &Vec2::scale);
1187 v2.addFunc("lerpTo", &Vec2::lerpTo);
1188 v2.addFunc("clone", &Vec2::clone);
1189
1190 auto v3 = table.addClass<Vec3>(
1191 "Vec3", std::function<Vec3 *()>([]() -> Vec3 * { return nullptr; }), true);
1192 v3.addFunc("getX", &Vec3::getX);
1193 v3.addFunc("getY", &Vec3::getY);
1194 v3.addFunc("getZ", &Vec3::getZ);
1195 v3.addFunc("setX", &Vec3::setX);
1196 v3.addFunc("setY", &Vec3::setY);
1197 v3.addFunc("setZ", &Vec3::setZ);
1198 v3.addFunc("set", &Vec3::set);
1199 v3.addFunc("length", &Vec3::length);
1200 v3.addFunc("lengthSquared", &Vec3::lengthSquared);
1201 v3.addFunc("normalize", &Vec3::normalize);
1202 v3.addFunc("normalized", &Vec3::normalized);
1203 v3.addFunc("dot", &Vec3::dot);
1204 v3.addFunc("cross", &Vec3::cross);
1205 v3.addFunc("distanceTo", &Vec3::distanceTo);
1206 v3.addFunc("add", &Vec3::add);
1207 v3.addFunc("sub", &Vec3::sub);
1208 v3.addFunc("scale", &Vec3::scale);
1209 v3.addFunc("lerpTo", &Vec3::lerpTo);
1210 v3.addFunc("clone", &Vec3::clone);
1211
1212 auto m4 = table.addClass<Mat4>(
1213 "Mat4", std::function<Mat4 *()>([]() -> Mat4 * { return nullptr; }), true);
1214 m4.addFunc("identity", &Mat4::identity);
1215 m4.addFunc("translate", &Mat4::translate);
1216 m4.addFunc("rotateX", &Mat4::rotateX);
1217 m4.addFunc("rotateY", &Mat4::rotateY);
1218 m4.addFunc("rotateZ", &Mat4::rotateZ);
1219 m4.addFunc("scale", &Mat4::scale);
1220 m4.addFunc("multiply", &Mat4::multiply);
1221 m4.addFunc("multiplied", &Mat4::multiplied);
1222 m4.addFunc("transformVec3", &Mat4::transformVec3);
1223 m4.addFunc("transformPoint2", &Mat4::transformPoint2);
1224 m4.addFunc("get", &Mat4::get);
1225 m4.addFunc("set", &Mat4::set);
1226 m4.addFunc("clone", &Mat4::clone);
1227}
1228
1229void Math::expose(ssq::Class &cls) {
1230 cls.addFunc("getName", &Math::getName);
1231 cls.addFunc("newVec2", &Math::newVec2);
1232 cls.addFunc("newVec3", &Math::newVec3);
1233 cls.addFunc("newMat4", &Math::newMat4);
1234 cls.addFunc("newMat4Translation", &Math::newMat4Translation);
1235 cls.addFunc("newMat4Scale", &Math::newMat4Scale);
1236 cls.addFunc("newMat4RotationZ", &Math::newMat4RotationZ);
1237
1238 cls.addFunc("clamp", &Math::clamp);
1239 cls.addFunc("lerp", &Math::lerp);
1240 cls.addFunc("smoothstep", &Math::smoothstep);
1241 cls.addFunc("smoothMax", &Math::smoothMax);
1242 cls.addFunc("remap", &Math::remap);
1243 cls.addFunc("degToRad", &Math::degToRad);
1244 cls.addFunc("radToDeg", &Math::radToDeg);
1245 cls.addFunc("sign", &Math::sign);
1246 cls.addFunc("fract", &Math::fract);
1247 cls.addFunc("approach", &Math::approach);
1248 cls.addFunc("wrap", &Math::wrap);
1249 cls.addFunc("pingPong", &Math::pingPong);
1250 cls.addFunc("inverseLerp", &Math::inverseLerp);
1251 cls.addFunc("smootherstep", &Math::smootherstep);
1252 cls.addFunc("bias", &Math::bias);
1253 cls.addFunc("gain", &Math::gain);
1254 cls.addFunc("ease", &Math::ease);
1255 cls.addFunc("step", &Math::step);
1256 cls.addFunc("quantize", &Math::quantize);
1257 cls.addFunc("snap", &Math::snap);
1258
1259 cls.addFunc("length2", &Math::length2);
1260 cls.addFunc("length3", &Math::length3);
1261 cls.addFunc("distance2", &Math::distance2);
1262 cls.addFunc("distance3", &Math::distance3);
1263 cls.addFunc("dot2", &Math::dot2);
1264 cls.addFunc("dot3", &Math::dot3);
1265 cls.addFunc("cross2", &Math::cross2);
1266 cls.addFunc("angle2", &Math::angle2);
1267 cls.addFunc("angleBetween2", &Math::angleBetween2);
1268 cls.addFunc("lerpAngle", &Math::lerpAngle);
1269 cls.addFunc("normalize2X", &Math::normalize2X);
1270 cls.addFunc("normalize2Y", &Math::normalize2Y);
1271 cls.addFunc("normalize3X", &Math::normalize3X);
1272 cls.addFunc("normalize3Y", &Math::normalize3Y);
1273 cls.addFunc("normalize3Z", &Math::normalize3Z);
1274 cls.addFunc("steeringSeek2", &Math::steeringSeek2);
1275 cls.addFunc("steeringSeek3", &Math::steeringSeek3);
1276 cls.addFunc("steeringFlee2", &Math::steeringFlee2);
1277 cls.addFunc("steeringFlee3", &Math::steeringFlee3);
1278 cls.addFunc("steeringArrive2", &Math::steeringArrive2);
1279 cls.addFunc("steeringArrive3", &Math::steeringArrive3);
1280 cls.addFunc("steeringSeparation2", &Math::steeringSeparation2);
1281 cls.addFunc("steeringSeparation3", &Math::steeringSeparation3);
1282 cls.addFunc("steeringPathTarget2", &Math::steeringPathTarget2);
1283 cls.addFunc("steeringPathTarget3", &Math::steeringPathTarget3);
1284 cls.addFunc("steeringAvoid2", &Math::steeringAvoid2);
1285 cls.addFunc("steeringAvoid3", &Math::steeringAvoid3);
1286 cls.addFunc("rotate2X", &Math::rotate2X);
1287 cls.addFunc("rotate2Y", &Math::rotate2Y);
1288 cls.addFunc("polarX", &Math::polarX);
1289 cls.addFunc("polarY", &Math::polarY);
1290 cls.addFunc("cartesianRadius", &Math::cartesianRadius);
1291 cls.addFunc("cartesianAngle", &Math::cartesianAngle);
1292 cls.addFunc("pointInCircle", &Math::pointInCircle);
1293 cls.addFunc("pointInRect", &Math::pointInRect);
1294 cls.addFunc("circlesOverlap", &Math::circlesOverlap);
1295 cls.addFunc("rectsOverlap", &Math::rectsOverlap);
1296 cls.addFunc("circleRectOverlap", &Math::circleRectOverlap);
1297 cls.addFunc("segmentsIntersect", &Math::segmentsIntersect);
1298 cls.addFunc("raycastCircle2", &Math::raycastCircle2);
1299 cls.addFunc("raycastRect2", &Math::raycastRect2);
1300 cls.addFunc("closestPointOnSegment2X", &Math::closestPointOnSegment2X);
1301 cls.addFunc("closestPointOnSegment2Y", &Math::closestPointOnSegment2Y);
1302 cls.addFunc("pointInSphere", &Math::pointInSphere);
1303 cls.addFunc("pointInBox", &Math::pointInBox);
1304 cls.addFunc("spheresOverlap", &Math::spheresOverlap);
1305 cls.addFunc("boxesOverlap", &Math::boxesOverlap);
1306 cls.addFunc("raycastSphere", &Math::raycastSphere);
1307 cls.addFunc("raycastBox", &Math::raycastBox);
1308 cls.addFunc("raycastPlane", &Math::raycastPlane);
1309 cls.addFunc("closestPointOnSegment3X", &Math::closestPointOnSegment3X);
1310 cls.addFunc("closestPointOnSegment3Y", &Math::closestPointOnSegment3Y);
1311 cls.addFunc("closestPointOnSegment3Z", &Math::closestPointOnSegment3Z);
1312 cls.addFunc("bilinear", &Math::bilinear);
1313
1314 cls.addFunc("setRandomSeed", &Math::setRandomSeed);
1315 cls.addFunc("setRandomSeedFromTime", &Math::setRandomSeedFromTime);
1316 cls.addFunc("getRandomSeed", &Math::getRandomSeed);
1317 cls.addFunc("random", &Math::random);
1318 cls.addFunc("randomRange", &Math::randomRange);
1319 cls.addFunc("randomInt", &Math::randomInt);
1320 cls.addFunc("randomGaussian", &Math::randomGaussian);
1321
1322 cls.addFunc("hash1", &Math::hash1);
1323 cls.addFunc("hash2", &Math::hash2);
1324 cls.addFunc("hash3", &Math::hash3);
1325
1326 cls.addFunc("noise1", &Math::noise1);
1327 cls.addFunc("noise2", &Math::noise2);
1328 cls.addFunc("noise3", &Math::noise3);
1329 cls.addFunc("simplex1", &Math::simplex1);
1330 cls.addFunc("simplex2", &Math::simplex2);
1331 cls.addFunc("simplex3", &Math::simplex3);
1332 cls.addFunc("perlin2", &Math::perlin2);
1333 cls.addFunc("perlin3", &Math::perlin3);
1334 cls.addFunc("white2", &Math::white2);
1335 cls.addFunc("value2", &Math::value2);
1336 cls.addFunc("fbm2", &Math::fbm2);
1337 cls.addFunc("fbm3", &Math::fbm3);
1338 cls.addFunc("ridged2", &Math::ridged2);
1339 cls.addFunc("ridged3", &Math::ridged3);
1340 cls.addFunc("turbulence2", &Math::turbulence2);
1341 cls.addFunc("billow2", &Math::billow2);
1342 cls.addFunc("voronoi2", &Math::voronoi2);
1343 cls.addFunc("voronoiEdge2", &Math::voronoiEdge2);
1344 cls.addFunc("worley2", &Math::worley2);
1345 cls.addFunc("warpNoise2", &Math::warpNoise2);
1346 cls.addFunc("warpNoise2Deep", &Math::warpNoise2Deep);
1347 cls.addFunc("voronoiF2_2", &Math::voronoiF2_2);
1348 cls.addFunc("worleyManhattan2", &Math::worleyManhattan2);
1349 cls.addFunc("worleyChebyshev2", &Math::worleyChebyshev2);
1350 cls.addFunc("worleySmooth2", &Math::worleySmooth2);
1351 cls.addFunc("curlNoise2X", &Math::curlNoise2X);
1352 cls.addFunc("curlNoise2Y", &Math::curlNoise2Y);
1353 cls.addFunc("hexDistance2", &Math::hexDistance2);
1354 cls.addFunc("hexEdge2", &Math::hexEdge2);
1355 cls.addFunc("gyroid3", &Math::gyroid3);
1356 cls.addFunc("gyroidFbm3", &Math::gyroidFbm3);
1357 cls.addFunc("swiss2", &Math::swiss2);
1358 cls.addFunc("hybrid2", &Math::hybrid2);
1359 cls.addFunc("jordan2", &Math::jordan2);
1360 cls.addFunc("gabor2", &Math::gabor2);
1361 cls.addFunc("gaborFbm2", &Math::gaborFbm2);
1362 cls.addFunc("valueDx2", &Math::valueDx2);
1363 cls.addFunc("valueDy2", &Math::valueDy2);
1364 cls.addFunc("valueSlope2", &Math::valueSlope2);
1365 cls.addFunc("isoLine2", &Math::isoLine2);
1366 cls.addFunc("banding2", &Math::banding2);
1367 cls.addFunc("fbmColor2", &Math::fbmColor2);
1368 cls.addFunc("white3", &Math::white3);
1369 cls.addFunc("value3", &Math::value3);
1370 cls.addFunc("worley3", &Math::worley3);
1371
1372 cls.addFunc("bezierQuadratic", &Math::bezierQuadratic);
1373 cls.addFunc("bezierCubic", &Math::bezierCubic);
1374 cls.addFunc("bezierQuadratic2X", &Math::bezierQuadratic2X);
1375 cls.addFunc("bezierQuadratic2Y", &Math::bezierQuadratic2Y);
1376 cls.addFunc("bezierCubic2X", &Math::bezierCubic2X);
1377 cls.addFunc("bezierCubic2Y", &Math::bezierCubic2Y);
1378}
1379
1380} // namespace eve::math
double z
double y
double m[16]
double x
LogicalId target
float w
Definition AnimClip.cpp:738
const std::string & s
float cx
Definition CardTypes.cpp:36
float cy
Definition CardTypes.cpp:37
glm::vec4 p[6]
HSQOBJECT cls
Definition ECS.cpp:39
std::string name
Definition ECS.cpp:154
EvpackChunkInput input
Definition Evpack.cpp:170
float maxAcceleration
tensor::Graph g
Definition GpuGraph.cpp:7
float soft[4]
float u
Definition Grass.cpp:233
glm::vec3 n
Definition Grass.cpp:63
double r
float v
std::int32_t second
std::int32_t c
std::int32_t first
std::vector< Colorf > px
std::uint32_t width
float length
size_t offset
Range range
Poco::JSON::Object::Ptr result
MeleePoint3 b
Definition MeleeHit.cpp:41
double radius
Definition MeleeHit.cpp:42
MeleePoint3 a
Definition MeleeHit.cpp:40
#define Module_IMPL(ModuleName, newExpr)
Definition Module.h:27
#define M_PI
glm::dvec3 dx
glm::dvec3 dz
std::shared_ptr< const std::vector< glm::vec2 > > points
Object::Ptr value
float d
float t
std::string text
std::string kind
double current
float dy
Definition Shadow.cpp:151
float bias
Definition Shadow.cpp:149
float targetX
uint32_t seed
Definition TreeMesh.cpp:276
double weight
double oy
double ox
double gain
glm::vec3 point
EVENGINE_API_FOUNDATION public API.
Definition Exception.h:13
virtual std::string getName() const =0
Returns the name.
Column-major 4x4 matrix wrapping glm::mat4.
Definition Mat4.h:13
Vec3 * transformVec3(const Vec3 *v) const
Definition Mat4.cpp:39
Vec2 * transformPoint2(const Vec2 *v) const
Definition Mat4.cpp:45
void translate(float x, float y, float z)
Post-multiplies a translation.
Definition Mat4.cpp:17
float get(int index) const
Column-major element 0..15.
Definition Mat4.cpp:51
void identity()
Resets to the identity matrix.
Definition Mat4.cpp:15
void scale(float sx, float sy, float sz)
Scales by scalar s. @ownership Caller deletes.
Definition Mat4.cpp:25
void multiply(const Mat4 *other)
Post-multiplies by other (column-vector convention).
Definition Mat4.cpp:29
Mat4 * clone() const
Definition Mat4.cpp:61
void rotateX(float radians)
Post-multiplies a rotation about X (radians).
Definition Mat4.cpp:21
void rotateZ(float radians)
Post-multiplies a rotation about Z (radians).
Definition Mat4.cpp:23
Mat4 * multiplied(const Mat4 *other) const
Definition Mat4.cpp:34
void set(int index, float value)
Sets all components.
Definition Mat4.cpp:56
void rotateY(float radians)
Post-multiplies a rotation about Y (radians).
Definition Mat4.cpp:22
Math module — glm-backed vectors/matrices, noise, bezier, random. Script: math <- eve....
Definition Math.h:23
float warpNoise2Deep(float x, float y, float warpAmp=1.f) const
Two-pass iq-style domain warp (noisecreater DomainWarp / Smoke).
Definition Math.cpp:817
float value3(float x, float y, float z) const
Smooth 3D value noise in [0,1].
Definition Math.cpp:1080
Vec2 * steeringFlee2(float x, float y, float targetX, float targetY, float maxSpeed) const
Creates a 2D flee velocity. @ownership owned @lifetime Caller deletes the result.
Definition Math.cpp:227
float jordan2(float x, float y, int octaves, float lacunarity, float gain, float warpStrength) const
Musgrave Jordan turbulence remapped to [0,1].
Definition Math.cpp:970
Vec2 * steeringAvoid2(float x, float y, float velocityX, float velocityY, float obstacleX, float obstacleY, float obstacleRadius, float lookAhead, float maxAcceleration) const
Creates 2D avoidance acceleration. @ownership owned @lifetime Caller deletes the result.
Definition Math.cpp:281
bool pointInSphere(float px, float py, float pz, float cx, float cy, float cz, float radius) const
True if point is inside or on the sphere.
Definition Math.cpp:551
float bezierQuadratic(float t, float p0, float p1, float p2) const
1D quadratic Bezier at t in [0,1].
Definition Math.cpp:1131
Vec3 * steeringFlee3(float x, float y, float z, float targetX, float targetY, float targetZ, float maxSpeed) const
Creates a 3D flee velocity. @ownership owned @lifetime Caller deletes the result.
Definition Math.cpp:233
float hexDistance2(float x, float y) const
Distance to nearest hex edge.
Definition Math.cpp:883
bool spheresOverlap(float x1, float y1, float z1, float r1, float x2, float y2, float z2, float r2) const
True if two spheres overlap.
Definition Math.cpp:562
Mat4 * newMat4Scale(float sx, float sy, float sz)
Allocates a scale Mat4. @ownership Caller deletes.
Definition Math.cpp:152
float warpNoise2(float x, float y, float warpAmp=1.f) const
Domain warp: sample noise at (x,y) + warpAmp * (noise-0.5). Useful for organic terrain / caves.
Definition Math.cpp:811
float normalize3X(float x, float y, float z) const
X of the normalized 3D vector (zero-safe).
Definition Math.cpp:402
bool boxesOverlap(float minAx, float minAy, float minAz, float maxAx, float maxAy, float maxAz, float minBx, float minBy, float minBz, float maxBx, float maxBy, float maxBz) const
True if two AABBs overlap.
Definition Math.cpp:570
float normalize3Z(float x, float y, float z) const
Z of the normalized 3D vector (zero-safe).
Definition Math.cpp:410
float perlin3(float x, float y, float z) const
Perlin noise in 3D, range [0,1].
Definition Math.cpp:700
float voronoi2(float x, float y) const
Worley / Voronoi F1 distance in [0, ~1.5] (cell size 1). voronoiEdge2 = F2 - F1 (cell borders).
Definition Math.cpp:797
float approach(float current, float target, float maxDelta) const
Moves current toward target by at most maxDelta.
Definition Math.cpp:194
float worleySmooth2(float x, float y, float smoothness) const
Smooth-min Worley (metaball cellular) in [0,1].
Definition Math.cpp:857
float gyroidFbm3(float x, float y, float z, int octaves) const
Absolute-gyroid fBm remapped to [0,1].
Definition Math.cpp:918
float turbulence2(float x, float y, int octaves=4, float lacunarity=2.f, float gain=0.5f) const
2D turbulence / billow (absolute fBm).
Definition Math.cpp:780
int steeringPathTarget3(float x, float y, float z, const std::string &points, int current, float tolerance) const
Selects a 3D path point from CSV x:y:z points, or -1 for no valid points.
Definition Math.cpp:275
Math()
Initializes RNG and math helpers.
Definition Math.cpp:139
float closestPointOnSegment2Y(float px, float py, float ax, float ay, float bx, float by) const
Y of the closest point on segment AB to P.
Definition Math.cpp:545
Mat4 * newMat4Translation(float x, float y, float z)
Allocates a translation Mat4. @ownership Caller deletes.
Definition Math.cpp:146
float normalize2Y(float x, float y) const
Y of the normalized 2D vector (zero-safe).
Definition Math.cpp:398
float gaborFbm2(float x, float y, int octaves, float dirX, float dirY) const
Absolute-Gabor fBm remapped to [0,1].
Definition Math.cpp:1022
Vec2 * steeringSeek2(float x, float y, float targetX, float targetY, float maxSpeed) const
Creates a 2D seek velocity. @ownership owned @lifetime Caller deletes the result.
Definition Math.cpp:215
float curlNoise2Y(float x, float y, float eps) const
Curl-noise Y from value-noise potential (finite differences).
Definition Math.cpp:878
float length3(float x, float y, float z) const
3D vector length from components.
Definition Math.cpp:362
float ease(float t, const std::string &kind) const
Easing on [0,1]. kind: "linear"|"inQuad"|"outQuad"|"inOutQuad"|"inCubic"|"outCubic"|"inOutCubic"| "in...
Definition Math.cpp:324
float fbmColor2(float x, float y, int channel, int octaves, float lacunarity, float gain) const
Decorrelated fBm color channel (0/1/2).
Definition Math.cpp:1071
float step(float edge, float x) const
Heaviside step: 0 if x < edge else 1.
Definition Math.cpp:349
float bezierQuadratic2X(float t, float x0, float y0, float x1, float y1, float x2, float y2) const
X of a 2D quadratic Bezier at t.
Definition Math.cpp:1145
float angle2(float x, float y) const
Atan2 angle of (x,y) in radians.
Definition Math.cpp:380
float raycastPlane(float ox, float oy, float oz, float dx, float dy, float dz, float px, float py, float pz, float nx, float ny, float nz) const
Ray vs infinite plane through (px,py,pz) with normal (nx,ny,nz). Returns parametric t,...
Definition Math.cpp:619
int steeringPathTarget2(float x, float y, const std::string &points, int current, float tolerance) const
Selects a 2D path point from CSV x:y points, or -1 for no valid points.
Definition Math.cpp:269
float raycastBox(float ox, float oy, float oz, float dx, float dy, float dz, float minX, float minY, float minZ, float maxX, float maxY, float maxZ) const
Ray vs AABB; parametric t >= 0 on hit, else -1.
Definition Math.cpp:595
float valueSlope2(float x, float y, float eps) const
Gradient magnitude of value2.
Definition Math.cpp:1049
float angleBetween2(float x1, float y1, float x2, float y2) const
Signed angle from first vector to second.
Definition Math.cpp:382
float smoothMax(float a, float b, float width) const
C1 smooth maximum of two finite heights; see common/SmoothMax.h.
Definition MathSmooth.cpp:6
float value2(float x, float y) const
Smooth 2D value noise in [0,1].
Definition Math.cpp:706
float cartesianAngle(float x, float y) const
Atan2 angle of (x,y).
Definition Math.cpp:427
float normalize3Y(float x, float y, float z) const
Y of the normalized 3D vector (zero-safe).
Definition Math.cpp:406
float gyroid3(float x, float y, float z) const
Gyroid field remapped to [0,1].
Definition Math.cpp:913
float closestPointOnSegment2X(float px, float py, float ax, float ay, float bx, float by) const
X of the closest point on segment AB to P.
Definition Math.cpp:540
bool circleRectOverlap(float cx, float cy, float radius, float rx, float ry, float rw, float rh) const
True if circle and axis-aligned rect overlap.
Definition Math.cpp:450
float smootherstep(float edge0, float edge1, float x) const
Ken Perlin smootherstep between edge0 and edge1.
Definition Math.cpp:305
float closestPointOnSegment3Y(float px, float py, float pz, float ax, float ay, float az, float bx, float by, float bz) const
Y of the closest point on segment AB to P.
Definition Math.cpp:632
float valueDy2(float x, float y, float eps) const
∂/∂y of value2 via central differences.
Definition Math.cpp:1044
float random()
Uniform float in [0, 1).
Definition Math.cpp:663
float fract(float x) const
Fractional part of x.
Definition Math.cpp:192
float noise1(float x) const
1D Simplex noise in [0,1]. Kept as noise1 for script compatibility; prefer simplex1 for clarity.
Definition Math.cpp:689
Mat4 * newMat4()
Allocates an identity Mat4. @ownership Caller deletes.
Definition Math.cpp:144
Vec2 * steeringSeparation2(float x, float y, const std::string &neighbors, float radius, float maxAcceleration) const
Creates 2D separation acceleration from CSV. @ownership owned @lifetime Caller deletes the result.
Definition Math.cpp:254
float simplex3(float x, float y, float z) const
Alias of noise3 (explicit Simplex).
Definition Math.cpp:697
float smoothstep(float edge0, float edge1, float x) const
Hermite smoothstep between edge0 and edge1.
Definition Math.cpp:171
float degToRad(float deg) const
Degrees to radians.
Definition Math.cpp:183
float randomRange(float min, float max)
Uniform float in [min, max).
Definition Math.cpp:668
bool rectsOverlap(float x1, float y1, float w1, float h1, float x2, float y2, float w2, float h2) const
True if two axis-aligned rects overlap.
Definition Math.cpp:445
float simplex1(float x) const
Alias of noise1 (explicit Simplex).
Definition Math.cpp:695
float normalize2X(float x, float y) const
X of the normalized 2D vector (zero-safe).
Definition Math.cpp:394
Vec3 * steeringSeparation3(float x, float y, float z, const std::string &neighbors, float radius, float maxAcceleration) const
Creates 3D separation acceleration from CSV. @ownership owned @lifetime Caller deletes the result.
Definition Math.cpp:262
Vec3 * steeringSeek3(float x, float y, float z, float targetX, float targetY, float targetZ, float maxSpeed) const
Creates a 3D seek velocity. @ownership owned @lifetime Caller deletes the result.
Definition Math.cpp:221
Vec3 * steeringArrive3(float x, float y, float z, float targetX, float targetY, float targetZ, float maxSpeed, float slowRadius, float stopRadius) const
Creates a 3D arrive velocity. @ownership owned @lifetime Caller deletes the result.
Definition Math.cpp:247
float snap(float x, float grid) const
Snaps x to the nearest grid multiple.
Definition Math.cpp:356
float gabor2(float x, float y, float dirX, float dirY, float frequency) const
Gabor / Voronoi-mix wavelet remapped to [0,1].
Definition Math.cpp:992
float polarX(float radius, float radians) const
X of polar (radius, radians).
Definition Math.cpp:424
float rotate2X(float x, float y, float radians) const
Rotate (x,y) by radians around origin.
Definition Math.cpp:415
float wrap(float x, float lo, float hi) const
Wraps x into [lo, hi).
Definition Math.cpp:200
float worleyManhattan2(float x, float y) const
Worley with Manhattan metric; F1 distance.
Definition Math.cpp:831
float voronoiEdge2(float x, float y) const
2D Worley F2-F1 edge distance.
Definition Math.cpp:803
float sign(float x) const
Sign of x (-1, 0, or 1).
Definition Math.cpp:186
float simplex2(float x, float y) const
Alias of noise2 (explicit Simplex).
Definition Math.cpp:696
float cross2(float x1, float y1, float x2, float y2) const
2D cross product (scalar z-component).
Definition Math.cpp:379
float clamp(float x, float lo, float hi) const
Clamps x into [lo, hi].
Definition Math.cpp:164
float closestPointOnSegment3X(float px, float py, float pz, float ax, float ay, float az, float bx, float by, float bz) const
X of the closest point on segment AB to P.
Definition Math.cpp:627
float rotate2Y(float x, float y, float radians) const
Y after rotating (x,y) by radians about the origin.
Definition Math.cpp:419
float swiss2(float x, float y, int octaves, float lacunarity, float gain, float warpStrength) const
Musgrave Swiss turbulence remapped to [0,1].
Definition Math.cpp:933
float closestPointOnSegment3Z(float px, float py, float pz, float ax, float ay, float az, float bx, float by, float bz) const
Z of the closest point on segment AB to P.
Definition Math.cpp:637
float bezierCubic2Y(float t, float x0, float y0, float x1, float y1, float x2, float y2, float x3, float y3) const
Y of a 2D cubic Bezier at t.
Definition Math.cpp:1160
float noise3(float x, float y, float z) const
3D Simplex noise in [0,1].
Definition Math.cpp:691
float perlin2(float x, float y) const
Perlin noise in 2D, range [0,1].
Definition Math.cpp:699
bool pointInCircle(float px, float py, float cx, float cy, float radius) const
True if point is inside or on the circle.
Definition Math.cpp:429
float hash2(float x, float y) const
Deterministic 2D hash mapped to [0,1].
Definition Math.cpp:686
float bezierQuadratic2Y(float t, float x0, float y0, float x1, float y1, float x2, float y2) const
Y of a 2D quadratic Bezier at t.
Definition Math.cpp:1150
float dot3(float x1, float y1, float z1, float x2, float y2, float z2) const
3D dot product of two vectors.
Definition Math.cpp:375
float noise2(float x, float y) const
2D Simplex noise in [0,1].
Definition Math.cpp:690
Vec3 * steeringAvoid3(float x, float y, float z, float velocityX, float velocityY, float velocityZ, float obstacleX, float obstacleY, float obstacleZ, float obstacleRadius, float lookAhead, float maxAcceleration) const
Creates 3D avoidance acceleration. @ownership owned @lifetime Caller deletes the result.
Definition Math.cpp:291
bool pointInBox(float px, float py, float pz, float minX, float minY, float minZ, float maxX, float maxY, float maxZ) const
Inclusive AABB test against [min,max] on each axis.
Definition Math.cpp:557
void setRandomSeedFromTime()
Seeds the RNG from the system clock.
Definition Math.cpp:654
float curlNoise2X(float x, float y, float eps) const
Curl-noise X from value-noise potential (finite differences).
Definition Math.cpp:873
Vec3 * newVec3(float x=0.f, float y=0.f, float z=0.f)
Allocates a Vec3. @ownership Caller deletes.
Definition Math.cpp:142
float ridged3(float x, float y, float z, int octaves=4, float lacunarity=2.f, float gain=0.5f) const
3D ridged multifractal noise.
Definition Math.cpp:764
uint32_t getRandomSeed() const
Current RNG seed value.
Definition Math.cpp:661
float bezierCubic(float t, float p0, float p1, float p2, float p3) const
1D cubic Bezier at t in [0,1].
Definition Math.cpp:1137
float gain(float t, float g) const
Schlick gain shaping of t in [0,1].
Definition Math.cpp:318
float worleyChebyshev2(float x, float y) const
Worley with Chebyshev metric; F1 distance.
Definition Math.cpp:844
float bilinear(float v00, float v10, float v01, float v11, float u, float v) const
Bilinear sample of 4 corners (v00,v10,v01,v11) with u,v in [0,1].
Definition Math.cpp:643
float ridged2(float x, float y, int octaves=4, float lacunarity=2.f, float gain=0.5f) const
2D ridged multifractal noise.
Definition Math.cpp:748
float isoLine2(float x, float y, int levels, float width) const
Contour mask of value2 in [0,1] (1 on lines).
Definition Math.cpp:1055
float billow2(float x, float y, int octaves=4, float lacunarity=2.f, float gain=0.5f) const
Alias of turbulence2 (NoiseCreator billow naming).
Definition Math.cpp:793
float cartesianRadius(float x, float y) const
Length of (x,y).
Definition Math.cpp:426
float pingPong(float t, float length) const
Triangle-wave ping-pong of t over [0, length].
Definition Math.cpp:209
float voronoiF2_2(float x, float y) const
Worley F2 distance (second-nearest feature).
Definition Math.cpp:825
float hash1(float x) const
Deterministic 1D hash mapped to [0,1].
Definition Math.cpp:685
float worley3(float x, float y, float z) const
Texture-friendly 3D Worley clamp(1-F1).
Definition Math.cpp:1107
float hexEdge2(float x, float y, float width, float soft) const
Hex edge line mask in [0,1].
Definition Math.cpp:906
float distance2(float x1, float y1, float x2, float y2) const
2D distance between two points.
Definition Math.cpp:366
float bias(float t, float b) const
Schlick bias/gain — shape [0,1] distributions (procgen falloff).
Definition Math.cpp:311
float raycastRect2(float ox, float oy, float dx, float dy, float rx, float ry, float rw, float rh) const
Ray vs axis-aligned rect (x,y,w,h). Returns parametric t >= 0, else -1.
Definition Math.cpp:499
float distance3(float x1, float y1, float z1, float x2, float y2, float z2) const
3D distance between two points.
Definition Math.cpp:370
void setRandomSeed(uint32_t seed)
Sets the module RNG seed.
Definition Math.cpp:649
float length2(float x, float y) const
2D vector length from components.
Definition Math.cpp:361
float radToDeg(float rad) const
Radians to degrees.
Definition Math.cpp:184
float inverseLerp(float a, float b, float x) const
Linear interpolation between a and b by t.
Definition Math.cpp:300
bool segmentsIntersect(float ax, float ay, float bx, float by, float cx, float cy, float dx, float dy) const
True if segments AB and CD intersect (including endpoints).
Definition Math.cpp:459
float hybrid2(float x, float y, int octaves, float lacunarity, float gain, float offset) const
Musgrave hybrid multifractal remapped to [0,1].
Definition Math.cpp:950
float remap(float x, float inMin, float inMax, float outMin, float outMax) const
Maps x from [inMin,inMax] into [outMin,outMax].
Definition Math.cpp:177
Mat4 * newMat4RotationZ(float radians)
Allocates a Z-rotation Mat4 (radians). @ownership Caller deletes.
Definition Math.cpp:158
Vec2 * newVec2(float x=0.f, float y=0.f)
Allocates a Vec2. @ownership Caller deletes.
Definition Math.cpp:141
float randomGaussian(float mean, float stddev)
Box-Muller Gaussian (mean, stddev).
Definition Math.cpp:680
float lerpAngle(float a, float b, float t) const
Shortest-path angle interpolation.
Definition Math.cpp:386
Vec2 * steeringArrive2(float x, float y, float targetX, float targetY, float maxSpeed, float slowRadius, float stopRadius) const
Creates a 2D arrive velocity. @ownership owned @lifetime Caller deletes the result.
Definition Math.cpp:239
float bezierCubic2X(float t, float x0, float y0, float x1, float y1, float x2, float y2, float x3, float y3) const
X of a 2D cubic Bezier at t.
Definition Math.cpp:1155
float banding2(float x, float y, int bands) const
Quantized banding of value2 in [0,1].
Definition Math.cpp:1065
float fbm3(float x, float y, float z, int octaves=4, float lacunarity=2.f, float gain=0.5f) const
3D fractal Brownian motion.
Definition Math.cpp:735
float dot2(float x1, float y1, float x2, float y2) const
2D dot product of two vectors.
Definition Math.cpp:374
float white3(float x, float y, float z) const
Lattice white noise from floor(x,y,z) in [0,1].
Definition Math.cpp:1078
float raycastCircle2(float ox, float oy, float dx, float dy, float cx, float cy, float radius) const
Ray vs circle. Hit point = (ox,oy) + t*(dx,dy). Returns t >= 0 on hit, else -1. Direction need not be...
Definition Math.cpp:481
float polarY(float radius, float radians) const
Y of polar (radius, radians).
Definition Math.cpp:425
float white2(float x, float y) const
Lattice white noise from floor(x), floor(y) in [0,1].
Definition Math.cpp:704
bool pointInRect(float px, float py, float rx, float ry, float rw, float rh) const
True if point is inside or on the axis-aligned rect.
Definition Math.cpp:434
float lerp(float a, float b, float t) const
Linear interpolation between a and b by t.
Definition Math.cpp:169
float quantize(float x, float stepSize) const
Quantizes x to multiples of stepSize.
Definition Math.cpp:351
float valueDx2(float x, float y, float eps) const
∂/∂x of value2 via central differences.
Definition Math.cpp:1039
bool circlesOverlap(float x1, float y1, float r1, float x2, float y2, float r2) const
True if two circles overlap.
Definition Math.cpp:438
float fbm2(float x, float y, int octaves=4, float lacunarity=2.f, float gain=0.5f) const
Fractal Brownian Motion / ridged / turbulence. octaves >= 1; lacunarity ~2; gain/persistence ~0....
Definition Math.cpp:722
float raycastSphere(float ox, float oy, float oz, float dx, float dy, float dz, float cx, float cy, float cz, float radius) const
Ray vs sphere; parametric t >= 0 on hit, else -1.
Definition Math.cpp:577
float worley2(float x, float y) const
Texture-friendly Worley: clamp(1 - F1, 0, 1).
Definition Math.cpp:809
int randomInt(int min, int maxInclusive)
Uniform inclusive integer in [min, maxInclusive].
Definition Math.cpp:674
float hash3(float x, float y, float z) const
Deterministic 3D hash mapped to [0,1].
Definition Math.cpp:687
2D float vector (script-facing math module value).
Definition Vec2.h:10
Vec2 * sub(const Vec2 *other) const
Definition Vec2.cpp:47
Vec2 * normalized() const
Definition Vec2.cpp:17
float cross(const Vec2 *other) const
Cross product with other.
Definition Vec2.cpp:28
float dot(const Vec2 *other) const
Atan2 angle in radians.
Definition Vec2.cpp:23
Vec2 * scale(float s) const
Definition Vec2.cpp:52
float angle() const
Atan2 angle in radians.
Definition Vec2.cpp:40
float distanceTo(const Vec2 *other) const
Euclidean distance to other.
Definition Vec2.cpp:33
void setX(float x)
Sets the X component.
Definition Vec2.h:21
float length() const
Magnitude (and squared magnitude).
Definition Vec2.h:31
void setY(float y)
Sets the Y component.
Definition Vec2.h:23
float lengthSquared() const
Squared Euclidean magnitude.
Definition Vec2.h:33
float getY() const
Y component.
Definition Vec2.h:19
float getX() const
Component accessors.
Definition Vec2.h:17
Vec2 * clone() const
Copies this vector.
Definition Vec2.cpp:59
void set(float x, float y)
Sets both components.
Definition Vec2.h:25
Vec2 * add(const Vec2 *other) const
Arithmetic helpers returning new (caller-owned) vectors.
Definition Vec2.cpp:42
void normalize()
Normalizes in place / returns a normalized copy.
Definition Vec2.cpp:9
Vec2 * lerpTo(const Vec2 *other, float t) const
Linear interpolation to other at t in [0,1].
Definition Vec2.cpp:54
3D float vector (script-facing math module value).
Definition Vec3.h:10
Vec3 * normalized() const
Definition Vec2.cpp:75
float getY() const
Y component.
Definition Vec3.h:19
Vec3 * cross(const Vec3 *other) const
Definition Vec2.cpp:86
Vec3 * clone() const
Copies this vector.
Definition Vec2.cpp:116
Vec3 * sub(const Vec3 *other) const
Definition Vec2.cpp:104
float getZ() const
Z component.
Definition Vec3.h:21
void setX(float x)
Sets the X component.
Definition Vec3.h:23
Vec3 * lerpTo(const Vec3 *other, float t) const
Linear interpolation to other at t in [0,1].
Definition Vec2.cpp:111
float length() const
Magnitude (and squared magnitude).
Definition Vec3.h:36
Vec3 * scale(float s) const
Definition Vec2.cpp:109
Vec3 * add(const Vec3 *other) const
Arithmetic helpers returning new (caller-owned) vectors.
Definition Vec2.cpp:99
void setY(float y)
Sets the Y component.
Definition Vec3.h:25
float dot(const Vec3 *other) const
Dot/cross product and distance.
Definition Vec2.cpp:81
float distanceTo(const Vec3 *other) const
Euclidean distance to other.
Definition Vec2.cpp:91
float lengthSquared() const
Squared Euclidean magnitude.
Definition Vec3.h:38
void normalize()
Normalizes in place / returns a normalized copy.
Definition Vec2.cpp:66
void setZ(float z)
Sets the Z component.
Definition Vec3.h:27
float getX() const
Component accessors.
Definition Vec3.h:17
void set(float x, float y, float z)
Sets all three components.
Definition Vec3.h:29
Vector2 arrive(Vector2 position, Vector2 target, float maxSpeed, float slowRadius, float stopRadius)
Slows toward target inside slowRadius and stops inside stopRadius.
Definition Steering.cpp:161
Vector2 seek(Vector2 position, Vector2 target, float maxSpeed)
Returns a velocity of at most maxSpeed directed from position to target.
Definition Steering.cpp:149
Vector2 avoid(Vector2 position, Vector2 velocity, Vector2 obstacle, float obstacleRadius, float lookAhead, float maxAcceleration)
Computes avoidance acceleration away from a predicted obstacle overlap.
Definition Steering.cpp:185
Vector2 separation(Vector2 position, std::span< const Vector2 > neighbors, float radius, float maxAcceleration)
Computes bounded separation acceleration from a borrowed neighbor snapshot.
Definition Steering.cpp:169
Vector2 flee(Vector2 position, Vector2 target, float maxSpeed)
Returns a velocity of at most maxSpeed directed away from target.
Definition Steering.cpp:155
int pathTarget(Vector2 position, std::span< const Vector2 > points, int current, float tolerance)
Selects the current path point, advancing across points within tolerance.
Definition Steering.cpp:177
Stateless steering vector algorithms shared by 2D and 3D callers.
Definition Steering.h:17
bool consumed
Definition Graphics.cpp:201