file_path
stringlengths 3
280
| file_language
stringclasses 66
values | content
stringlengths 1
1.04M
| repo_name
stringlengths 5
92
| repo_stars
int64 0
154k
| repo_description
stringlengths 0
402
| repo_primary_language
stringclasses 108
values | developer_username
stringlengths 1
25
| developer_name
stringlengths 0
30
| developer_company
stringlengths 0
82
|
|---|---|---|---|---|---|---|---|---|---|
src/modules/keyboard/keyboard.cc
|
C++
|
#include "keyboard.hh"
#include "engine.hh"
#include <unordered_map>
#include <string>
namespace joy {
namespace modules {
// Key name to SDL scancode mapping
static const std::unordered_map<std::string, SDL_Scancode> name_to_scancode = {
// Letters
{"a", SDL_SCANCODE_A}, {"b", SDL_SCANCODE_B}, {"c", SDL_SCANCODE_C}, {"d", SDL_SCANCODE_D},
{"e", SDL_SCANCODE_E}, {"f", SDL_SCANCODE_F}, {"g", SDL_SCANCODE_G}, {"h", SDL_SCANCODE_H},
{"i", SDL_SCANCODE_I}, {"j", SDL_SCANCODE_J}, {"k", SDL_SCANCODE_K}, {"l", SDL_SCANCODE_L},
{"m", SDL_SCANCODE_M}, {"n", SDL_SCANCODE_N}, {"o", SDL_SCANCODE_O}, {"p", SDL_SCANCODE_P},
{"q", SDL_SCANCODE_Q}, {"r", SDL_SCANCODE_R}, {"s", SDL_SCANCODE_S}, {"t", SDL_SCANCODE_T},
{"u", SDL_SCANCODE_U}, {"v", SDL_SCANCODE_V}, {"w", SDL_SCANCODE_W}, {"x", SDL_SCANCODE_X},
{"y", SDL_SCANCODE_Y}, {"z", SDL_SCANCODE_Z},
// Numbers
{"0", SDL_SCANCODE_0}, {"1", SDL_SCANCODE_1}, {"2", SDL_SCANCODE_2}, {"3", SDL_SCANCODE_3},
{"4", SDL_SCANCODE_4}, {"5", SDL_SCANCODE_5}, {"6", SDL_SCANCODE_6}, {"7", SDL_SCANCODE_7},
{"8", SDL_SCANCODE_8}, {"9", SDL_SCANCODE_9},
// Function keys
{"f1", SDL_SCANCODE_F1}, {"f2", SDL_SCANCODE_F2}, {"f3", SDL_SCANCODE_F3}, {"f4", SDL_SCANCODE_F4},
{"f5", SDL_SCANCODE_F5}, {"f6", SDL_SCANCODE_F6}, {"f7", SDL_SCANCODE_F7}, {"f8", SDL_SCANCODE_F8},
{"f9", SDL_SCANCODE_F9}, {"f10", SDL_SCANCODE_F10}, {"f11", SDL_SCANCODE_F11}, {"f12", SDL_SCANCODE_F12},
// Arrow keys
{"up", SDL_SCANCODE_UP}, {"down", SDL_SCANCODE_DOWN}, {"left", SDL_SCANCODE_LEFT}, {"right", SDL_SCANCODE_RIGHT},
// Modifiers
{"lshift", SDL_SCANCODE_LSHIFT}, {"rshift", SDL_SCANCODE_RSHIFT},
{"lctrl", SDL_SCANCODE_LCTRL}, {"rctrl", SDL_SCANCODE_RCTRL},
{"lalt", SDL_SCANCODE_LALT}, {"ralt", SDL_SCANCODE_RALT},
{"lgui", SDL_SCANCODE_LGUI}, {"rgui", SDL_SCANCODE_RGUI},
// Special keys
{"space", SDL_SCANCODE_SPACE}, {"return", SDL_SCANCODE_RETURN}, {"enter", SDL_SCANCODE_RETURN},
{"escape", SDL_SCANCODE_ESCAPE}, {"backspace", SDL_SCANCODE_BACKSPACE}, {"tab", SDL_SCANCODE_TAB},
{"insert", SDL_SCANCODE_INSERT}, {"delete", SDL_SCANCODE_DELETE},
{"home", SDL_SCANCODE_HOME}, {"end", SDL_SCANCODE_END},
{"pageup", SDL_SCANCODE_PAGEUP}, {"pagedown", SDL_SCANCODE_PAGEDOWN},
// Punctuation
{"-", SDL_SCANCODE_MINUS}, {"=", SDL_SCANCODE_EQUALS},
{"[", SDL_SCANCODE_LEFTBRACKET}, {"]", SDL_SCANCODE_RIGHTBRACKET},
{"\\", SDL_SCANCODE_BACKSLASH}, {";", SDL_SCANCODE_SEMICOLON},
{"'", SDL_SCANCODE_APOSTROPHE}, {"`", SDL_SCANCODE_GRAVE},
{",", SDL_SCANCODE_COMMA}, {".", SDL_SCANCODE_PERIOD}, {"/", SDL_SCANCODE_SLASH},
// Keypad
{"kp0", SDL_SCANCODE_KP_0}, {"kp1", SDL_SCANCODE_KP_1}, {"kp2", SDL_SCANCODE_KP_2},
{"kp3", SDL_SCANCODE_KP_3}, {"kp4", SDL_SCANCODE_KP_4}, {"kp5", SDL_SCANCODE_KP_5},
{"kp6", SDL_SCANCODE_KP_6}, {"kp7", SDL_SCANCODE_KP_7}, {"kp8", SDL_SCANCODE_KP_8},
{"kp9", SDL_SCANCODE_KP_9},
{"kp.", SDL_SCANCODE_KP_PERIOD}, {"kp/", SDL_SCANCODE_KP_DIVIDE},
{"kp*", SDL_SCANCODE_KP_MULTIPLY}, {"kp-", SDL_SCANCODE_KP_MINUS},
{"kp+", SDL_SCANCODE_KP_PLUS}, {"kpenter", SDL_SCANCODE_KP_ENTER},
// Misc
{"capslock", SDL_SCANCODE_CAPSLOCK}, {"scrolllock", SDL_SCANCODE_SCROLLLOCK},
{"numlock", SDL_SCANCODE_NUMLOCKCLEAR}, {"printscreen", SDL_SCANCODE_PRINTSCREEN},
{"pause", SDL_SCANCODE_PAUSE},
};
// Reverse mapping: scancode to name
static std::unordered_map<SDL_Scancode, std::string> scancode_to_name;
// Initialize reverse map (called once at startup)
static void initReverseScancodeCodes() {
static bool initialized = false;
if (initialized) return;
for (const auto &pair : name_to_scancode) {
// Only add if not already present (handles "return" and "enter" both mapping to RETURN)
if (scancode_to_name.find(pair.second) == scancode_to_name.end()) {
scancode_to_name[pair.second] = pair.first;
}
}
initialized = true;
}
Keyboard::Keyboard(Engine *engine)
: engine_(engine)
, key_repeat_(true)
{
initReverseScancodeCodes();
}
Keyboard::~Keyboard() {
}
SDL_Scancode Keyboard::scancodeFromName(const char *name) {
auto it = name_to_scancode.find(name);
if (it != name_to_scancode.end()) {
return it->second;
}
return SDL_SCANCODE_UNKNOWN;
}
const char *Keyboard::nameFromScancode(SDL_Scancode code) {
auto it = scancode_to_name.find(code);
if (it != scancode_to_name.end()) {
return it->second.c_str();
}
return nullptr;
}
bool Keyboard::isDown(const char **keys, int count) {
const bool *state = SDL_GetKeyboardState(nullptr);
if (!state) {
return false;
}
for (int i = 0; i < count; i++) {
SDL_Scancode code = scancodeFromName(keys[i]);
if (code != SDL_SCANCODE_UNKNOWN && state[code]) {
return true;
}
}
return false;
}
bool Keyboard::isScancodeDown(const int *scancodes, int count) {
const bool *state = SDL_GetKeyboardState(nullptr);
if (!state) {
return false;
}
for (int i = 0; i < count; i++) {
if (scancodes[i] >= 0 && scancodes[i] < SDL_SCANCODE_COUNT && state[scancodes[i]]) {
return true;
}
}
return false;
}
void Keyboard::setKeyRepeat(bool enable) {
key_repeat_ = enable;
}
bool Keyboard::hasKeyRepeat() const {
return key_repeat_;
}
SDL_Scancode Keyboard::getScancodeFromKey(const char *key) {
return scancodeFromName(key);
}
const char *Keyboard::getKeyFromScancode(SDL_Scancode scancode) {
return nameFromScancode(scancode);
}
void Keyboard::setTextInput(bool enable, int x, int y, int w, int h) {
SDL_Window *window = engine_->getWindow();
if (!window) {
return;
}
if (enable) {
if (x != 0 || y != 0 || w != 0 || h != 0) {
SDL_Rect rect = { x, y, w, h };
SDL_SetTextInputArea(window, &rect, 0);
}
SDL_StartTextInput(window);
} else {
SDL_StopTextInput(window);
}
}
bool Keyboard::hasTextInput() {
SDL_Window *window = engine_->getWindow();
if (!window) {
return false;
}
return SDL_TextInputActive(window);
}
const char *Keyboard::getKeyName(SDL_Scancode scancode) {
return nameFromScancode(scancode);
}
bool Keyboard::isKeyDown(SDL_Scancode scancode) {
const bool *state = SDL_GetKeyboardState(nullptr);
return state && state[scancode];
}
} // namespace modules
} // namespace joy
|
zyedidia/joy
| 1
|
A framework for building 2D desktop games in JavaScript, with a Love2D-inspired API
|
C++
|
zyedidia
|
Zachary Yedidia
|
Stanford University
|
src/modules/keyboard/keyboard.hh
|
C++ Header
|
#pragma once
#include "SDL3/SDL.h"
namespace js {
class Context;
class Value;
}
namespace joy {
class Engine;
namespace modules {
class Keyboard {
public:
Keyboard(Engine *engine);
~Keyboard();
// Check if keys are down
bool isDown(const char **keys, int count);
bool isScancodeDown(const int *scancodes, int count);
// Key repeat (tracked per-instance)
void setKeyRepeat(bool enable);
bool hasKeyRepeat() const;
// Scancode/key conversion
SDL_Scancode getScancodeFromKey(const char *key);
const char *getKeyFromScancode(SDL_Scancode scancode);
// Text input
void setTextInput(bool enable, int x = 0, int y = 0, int w = 0, int h = 0);
bool hasTextInput();
// Public API for other modules
static const char *getKeyName(SDL_Scancode scancode);
static bool isKeyDown(SDL_Scancode scancode);
// Helper functions for scancode/name conversion
static SDL_Scancode scancodeFromName(const char *name);
static const char *nameFromScancode(SDL_Scancode code);
// Initialize JS bindings
static void initJS(js::Context &ctx, js::Value &joy);
private:
Engine *engine_;
bool key_repeat_;
};
} // namespace modules
} // namespace joy
|
zyedidia/joy
| 1
|
A framework for building 2D desktop games in JavaScript, with a Love2D-inspired API
|
C++
|
zyedidia
|
Zachary Yedidia
|
Stanford University
|
src/modules/keyboard/keyboard_js.cc
|
C++
|
#include "js/js.hh"
#include "keyboard.hh"
#include "engine.hh"
namespace joy {
namespace modules {
// Helper to get Keyboard from JS context
static Keyboard *getKeyboard(js::FunctionArgs &args) {
Engine *engine = args.getContextOpaque<Engine>();
return engine ? engine->getKeyboardModule() : nullptr;
}
static void js_keyboard_isDown(js::FunctionArgs &args) {
Keyboard *keyboard = getKeyboard(args);
if (!keyboard) {
args.returnValue(js::Value::boolean(false));
return;
}
const bool *state = SDL_GetKeyboardState(nullptr);
if (!state) {
args.returnValue(js::Value::boolean(false));
return;
}
for (int i = 0; i < args.length(); i++) {
js::Value arg = args.arg(i);
std::string name = arg.toString(args.context());
SDL_Scancode code = Keyboard::scancodeFromName(name.c_str());
if (code != SDL_SCANCODE_UNKNOWN && state[code]) {
args.returnValue(js::Value::boolean(true));
return;
}
}
args.returnValue(js::Value::boolean(false));
}
static void js_keyboard_isScancodeDown(js::FunctionArgs &args) {
Keyboard *keyboard = getKeyboard(args);
if (!keyboard) {
args.returnValue(js::Value::boolean(false));
return;
}
const bool *state = SDL_GetKeyboardState(nullptr);
if (!state) {
args.returnValue(js::Value::boolean(false));
return;
}
for (int i = 0; i < args.length(); i++) {
js::Value arg = args.arg(i);
int code = arg.toInt32();
if (code >= 0 && code < SDL_SCANCODE_COUNT && state[code]) {
args.returnValue(js::Value::boolean(true));
return;
}
}
args.returnValue(js::Value::boolean(false));
}
static void js_keyboard_setKeyRepeat(js::FunctionArgs &args) {
Keyboard *keyboard = getKeyboard(args);
if (!keyboard || args.length() < 1) {
args.returnUndefined();
return;
}
bool enable = args.arg(0).toBool();
keyboard->setKeyRepeat(enable);
args.returnUndefined();
}
static void js_keyboard_hasKeyRepeat(js::FunctionArgs &args) {
Keyboard *keyboard = getKeyboard(args);
args.returnValue(js::Value::boolean(keyboard ? keyboard->hasKeyRepeat() : true));
}
static void js_keyboard_getScancodeFromKey(js::FunctionArgs &args) {
if (args.length() < 1) {
args.returnValue(js::Value::number(0));
return;
}
std::string name = args.arg(0).toString(args.context());
SDL_Scancode code = Keyboard::scancodeFromName(name.c_str());
args.returnValue(js::Value::number(static_cast<int>(code)));
}
static void js_keyboard_getKeyFromScancode(js::FunctionArgs &args) {
if (args.length() < 1) {
args.returnValue(js::Value::string(args.context(), ""));
return;
}
int code = args.arg(0).toInt32();
const char *name = Keyboard::nameFromScancode(static_cast<SDL_Scancode>(code));
args.returnValue(js::Value::string(args.context(), name ? name : ""));
}
static void js_keyboard_setTextInput(js::FunctionArgs &args) {
Keyboard *keyboard = getKeyboard(args);
if (!keyboard || args.length() < 1) {
args.returnUndefined();
return;
}
bool enable = args.arg(0).toBool();
if (args.length() >= 5) {
int x = args.arg(1).toInt32();
int y = args.arg(2).toInt32();
int w = args.arg(3).toInt32();
int h = args.arg(4).toInt32();
keyboard->setTextInput(enable, x, y, w, h);
} else {
keyboard->setTextInput(enable);
}
args.returnUndefined();
}
static void js_keyboard_hasTextInput(js::FunctionArgs &args) {
Keyboard *keyboard = getKeyboard(args);
args.returnValue(js::Value::boolean(keyboard && keyboard->hasTextInput()));
}
void Keyboard::initJS(js::Context &ctx, js::Value &joy) {
js::ModuleBuilder(ctx, "keyboard")
.function("isDown", js_keyboard_isDown, 1)
.function("isScancodeDown", js_keyboard_isScancodeDown, 1)
.function("setKeyRepeat", js_keyboard_setKeyRepeat, 1)
.function("hasKeyRepeat", js_keyboard_hasKeyRepeat, 0)
.function("getScancodeFromKey", js_keyboard_getScancodeFromKey, 1)
.function("getKeyFromScancode", js_keyboard_getKeyFromScancode, 1)
.function("setTextInput", js_keyboard_setTextInput, 5)
.function("hasTextInput", js_keyboard_hasTextInput, 0)
.attachTo(joy);
}
} // namespace modules
} // namespace joy
|
zyedidia/joy
| 1
|
A framework for building 2D desktop games in JavaScript, with a Love2D-inspired API
|
C++
|
zyedidia
|
Zachary Yedidia
|
Stanford University
|
src/modules/math/math.cc
|
C++
|
#include "math.hh"
#include "noise1234.hh"
#include "simplexnoise1234.hh"
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <sstream>
#include <iomanip>
#include <limits>
#include <list>
#include <algorithm>
#include <stdexcept>
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
namespace joy {
namespace modules {
// ============================================================================
// Triangulation helpers
// ============================================================================
static bool is_oriented_ccw(const Vector2 &a, const Vector2 &b, const Vector2 &c) {
return ((b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x)) >= 0;
}
static bool on_same_side(const Vector2 &a, const Vector2 &b, const Vector2 &c, const Vector2 &d) {
float px = d.x - c.x, py = d.y - c.y;
float l = px * (a.y - c.y) - py * (a.x - c.x);
float m = px * (b.y - c.y) - py * (b.x - c.x);
return l * m >= 0;
}
static bool point_in_triangle(const Vector2 &p, const Vector2 &a, const Vector2 &b, const Vector2 &c) {
return on_same_side(p, a, b, c) && on_same_side(p, b, a, c) && on_same_side(p, c, a, b);
}
static bool any_point_in_triangle(const std::list<const Vector2 *> &vertices, const Vector2 &a, const Vector2 &b, const Vector2 &c) {
for (const Vector2 *p : vertices) {
if ((p != &a) && (p != &b) && (p != &c) && point_in_triangle(*p, a, b, c))
return true;
}
return false;
}
static bool is_ear(const Vector2 &a, const Vector2 &b, const Vector2 &c, const std::list<const Vector2 *> &vertices) {
return is_oriented_ccw(a, b, c) && !any_point_in_triangle(vertices, a, b, c);
}
// ============================================================================
// Matrix4 Implementation
// ============================================================================
Matrix4::Matrix4() {
setIdentity();
}
Matrix4::Matrix4(float x, float y, float a, float sx, float sy, float ox, float oy, float kx, float ky) {
setTransformation(x, y, a, sx, sy, ox, oy, kx, ky);
}
void Matrix4::setIdentity() {
for (int i = 0; i < 16; i++) e[i] = 0;
e[0] = e[5] = e[10] = e[15] = 1;
}
void Matrix4::setTransformation(float x, float y, float a, float sx, float sy, float ox, float oy, float kx, float ky) {
float c = std::cos(a), s = std::sin(a);
// | sx*c - ky*s kx*c - sy*s 0 x - ox*(sx*c - ky*s) - oy*(kx*c - sy*s) |
// | sx*s + ky*c kx*s + sy*c 0 y - ox*(sx*s + ky*c) - oy*(kx*s + sy*c) |
// | 0 0 1 0 |
// | 0 0 0 1 |
e[0] = sx * c + kx * s;
e[1] = sx * s - kx * c;
e[2] = 0;
e[3] = 0;
e[4] = ky * c + sy * s;
e[5] = ky * s - sy * c;
e[6] = 0;
e[7] = 0;
e[8] = 0;
e[9] = 0;
e[10] = 1;
e[11] = 0;
e[12] = x - ox * e[0] - oy * e[4];
e[13] = y - ox * e[1] - oy * e[5];
e[14] = 0;
e[15] = 1;
}
void Matrix4::translate(float x, float y) {
e[12] += e[0] * x + e[4] * y;
e[13] += e[1] * x + e[5] * y;
}
void Matrix4::rotate(float angle) {
float c = std::cos(angle), s = std::sin(angle);
float e0 = e[0], e1 = e[1], e4 = e[4], e5 = e[5];
e[0] = c * e0 + s * e4;
e[1] = c * e1 + s * e5;
e[4] = c * e4 - s * e0;
e[5] = c * e5 - s * e1;
}
void Matrix4::scale(float x, float y) {
e[0] *= x;
e[1] *= x;
e[4] *= y;
e[5] *= y;
}
void Matrix4::shear(float kx, float ky) {
float e0 = e[0], e1 = e[1], e4 = e[4], e5 = e[5];
e[0] = e0 + kx * e4;
e[1] = e1 + kx * e5;
e[4] = ky * e0 + e4;
e[5] = ky * e1 + e5;
}
Matrix4 Matrix4::inverse() const {
Matrix4 inv;
float det;
inv.e[0] = e[5] * e[10] * e[15] - e[5] * e[11] * e[14] - e[9] * e[6] * e[15] + e[9] * e[7] * e[14] + e[13] * e[6] * e[11] - e[13] * e[7] * e[10];
inv.e[4] = -e[4] * e[10] * e[15] + e[4] * e[11] * e[14] + e[8] * e[6] * e[15] - e[8] * e[7] * e[14] - e[12] * e[6] * e[11] + e[12] * e[7] * e[10];
inv.e[8] = e[4] * e[9] * e[15] - e[4] * e[11] * e[13] - e[8] * e[5] * e[15] + e[8] * e[7] * e[13] + e[12] * e[5] * e[11] - e[12] * e[7] * e[9];
inv.e[12] = -e[4] * e[9] * e[14] + e[4] * e[10] * e[13] + e[8] * e[5] * e[14] - e[8] * e[6] * e[13] - e[12] * e[5] * e[10] + e[12] * e[6] * e[9];
inv.e[1] = -e[1] * e[10] * e[15] + e[1] * e[11] * e[14] + e[9] * e[2] * e[15] - e[9] * e[3] * e[14] - e[13] * e[2] * e[11] + e[13] * e[3] * e[10];
inv.e[5] = e[0] * e[10] * e[15] - e[0] * e[11] * e[14] - e[8] * e[2] * e[15] + e[8] * e[3] * e[14] + e[12] * e[2] * e[11] - e[12] * e[3] * e[10];
inv.e[9] = -e[0] * e[9] * e[15] + e[0] * e[11] * e[13] + e[8] * e[1] * e[15] - e[8] * e[3] * e[13] - e[12] * e[1] * e[11] + e[12] * e[3] * e[9];
inv.e[13] = e[0] * e[9] * e[14] - e[0] * e[10] * e[13] - e[8] * e[1] * e[14] + e[8] * e[2] * e[13] + e[12] * e[1] * e[10] - e[12] * e[2] * e[9];
inv.e[2] = e[1] * e[6] * e[15] - e[1] * e[7] * e[14] - e[5] * e[2] * e[15] + e[5] * e[3] * e[14] + e[13] * e[2] * e[7] - e[13] * e[3] * e[6];
inv.e[6] = -e[0] * e[6] * e[15] + e[0] * e[7] * e[14] + e[4] * e[2] * e[15] - e[4] * e[3] * e[14] - e[12] * e[2] * e[7] + e[12] * e[3] * e[6];
inv.e[10] = e[0] * e[5] * e[15] - e[0] * e[7] * e[13] - e[4] * e[1] * e[15] + e[4] * e[3] * e[13] + e[12] * e[1] * e[7] - e[12] * e[3] * e[5];
inv.e[14] = -e[0] * e[5] * e[14] + e[0] * e[6] * e[13] + e[4] * e[1] * e[14] - e[4] * e[2] * e[13] - e[12] * e[1] * e[6] + e[12] * e[2] * e[5];
inv.e[3] = -e[1] * e[6] * e[11] + e[1] * e[7] * e[10] + e[5] * e[2] * e[11] - e[5] * e[3] * e[10] - e[9] * e[2] * e[7] + e[9] * e[3] * e[6];
inv.e[7] = e[0] * e[6] * e[11] - e[0] * e[7] * e[10] - e[4] * e[2] * e[11] + e[4] * e[3] * e[10] + e[8] * e[2] * e[7] - e[8] * e[3] * e[6];
inv.e[11] = -e[0] * e[5] * e[11] + e[0] * e[7] * e[9] + e[4] * e[1] * e[11] - e[4] * e[3] * e[9] - e[8] * e[1] * e[7] + e[8] * e[3] * e[5];
inv.e[15] = e[0] * e[5] * e[10] - e[0] * e[6] * e[9] - e[4] * e[1] * e[10] + e[4] * e[2] * e[9] + e[8] * e[1] * e[6] - e[8] * e[2] * e[5];
det = e[0] * inv.e[0] + e[1] * inv.e[4] + e[2] * inv.e[8] + e[3] * inv.e[12];
if (det == 0) return Matrix4();
det = 1.0f / det;
for (int i = 0; i < 16; i++)
inv.e[i] *= det;
return inv;
}
Matrix4 Matrix4::operator*(const Matrix4 &other) const {
Matrix4 result;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
result.e[i * 4 + j] = 0;
for (int k = 0; k < 4; k++) {
result.e[i * 4 + j] += e[k * 4 + j] * other.e[i * 4 + k];
}
}
}
return result;
}
Matrix4 &Matrix4::operator*=(const Matrix4 &other) {
*this = *this * other;
return *this;
}
void Matrix4::transformXY(Vector2 *dst, const Vector2 *src, int count) const {
for (int i = 0; i < count; i++) {
dst[i].x = src[i].x * e[0] + src[i].y * e[4] + e[12];
dst[i].y = src[i].x * e[1] + src[i].y * e[5] + e[13];
}
}
// ============================================================================
// Math class implementation
// ============================================================================
Math::Math() {
rng_ = new RandomGenerator();
RandomGenerator::Seed seed;
seed.b64 = (uint64_t)time(nullptr);
rng_->setSeed(seed);
}
Math::~Math() {
delete rng_;
}
double Math::random() {
return rng_->random();
}
double Math::random(double max) {
return rng_->random(max);
}
double Math::random(double min, double max) {
return rng_->random(min, max);
}
double Math::randomNormal(double stddev, double mean) {
return rng_->randomNormal(stddev) + mean;
}
void Math::setRandomSeed(uint64_t seed) {
RandomGenerator::Seed s;
s.b64 = seed;
rng_->setSeed(s);
}
void Math::setRandomSeed(uint32_t low, uint32_t high) {
rng_->setSeed(low, high);
}
uint64_t Math::getRandomSeed() const {
return rng_->getSeed().b64;
}
void Math::getRandomSeed(uint32_t &low, uint32_t &high) const {
RandomGenerator::Seed s = rng_->getSeed();
low = s.b32.low;
high = s.b32.high;
}
void Math::setRandomState(const std::string &state) {
rng_->setState(state);
}
std::string Math::getRandomState() const {
return rng_->getState();
}
RandomGenerator *Math::newRandomGenerator() {
return new RandomGenerator();
}
RandomGenerator *Math::newRandomGenerator(uint64_t seed) {
RandomGenerator *rng = new RandomGenerator();
rng->setSeed(seed);
return rng;
}
RandomGenerator *Math::newRandomGenerator(uint32_t low, uint32_t high) {
RandomGenerator *rng = new RandomGenerator();
rng->setSeed(low, high);
return rng;
}
BezierCurve *Math::newBezierCurve(const std::vector<Vector2> &points) {
return new BezierCurve(points);
}
Transform *Math::newTransform() {
return new Transform();
}
Transform *Math::newTransform(float x, float y, float a, float sx, float sy, float ox, float oy, float kx, float ky) {
return new Transform(x, y, a, sx, sy, ox, oy, kx, ky);
}
double Math::noise(double x) {
return SimplexNoise1234::noise(x) * 0.5 + 0.5;
}
double Math::noise(double x, double y) {
return SimplexNoise1234::noise(x, y) * 0.5 + 0.5;
}
double Math::noise(double x, double y, double z) {
return Noise1234::noise(x, y, z) * 0.5 + 0.5;
}
double Math::noise(double x, double y, double z, double w) {
return Noise1234::noise(x, y, z, w) * 0.5 + 0.5;
}
float Math::gammaToLinear(float c) {
if (c <= 0.04045f)
return c / 12.92f;
else
return std::pow((c + 0.055f) / 1.055f, 2.4f);
}
float Math::linearToGamma(float c) {
if (c <= 0.0031308f)
return c * 12.92f;
else
return 1.055f * std::pow(c, 1.0f / 2.4f) - 0.055f;
}
std::vector<Triangle> Math::triangulate(const std::vector<Vector2> &polygon) {
if (polygon.size() < 3)
throw std::runtime_error("Not a polygon");
else if (polygon.size() == 3)
return std::vector<Triangle>(1, Triangle(polygon[0], polygon[1], polygon[2]));
std::vector<size_t> next_idx(polygon.size()), prev_idx(polygon.size());
size_t idx_lm = 0;
for (size_t i = 0; i < polygon.size(); ++i) {
const Vector2 &lm = polygon[idx_lm], &p = polygon[i];
if (p.x < lm.x || (p.x == lm.x && p.y < lm.y))
idx_lm = i;
next_idx[i] = i + 1;
prev_idx[i] = i - 1;
}
next_idx[next_idx.size() - 1] = 0;
prev_idx[0] = prev_idx.size() - 1;
if (!is_oriented_ccw(polygon[prev_idx[idx_lm]], polygon[idx_lm], polygon[next_idx[idx_lm]]))
next_idx.swap(prev_idx);
std::list<const Vector2 *> concave_vertices;
for (size_t i = 0; i < polygon.size(); ++i) {
if (!is_oriented_ccw(polygon[prev_idx[i]], polygon[i], polygon[next_idx[i]]))
concave_vertices.push_back(&polygon[i]);
}
std::vector<Triangle> triangles;
size_t n_vertices = polygon.size();
size_t current = 1, skipped = 0, next, prev;
while (n_vertices > 3) {
next = next_idx[current];
prev = prev_idx[current];
const Vector2 &a = polygon[prev], &b = polygon[current], &c = polygon[next];
if (is_ear(a, b, c, concave_vertices)) {
triangles.push_back(Triangle(a, b, c));
next_idx[prev] = next;
prev_idx[next] = prev;
concave_vertices.remove(&b);
--n_vertices;
skipped = 0;
} else if (++skipped > n_vertices) {
throw std::runtime_error("Cannot triangulate polygon.");
}
current = next;
}
next = next_idx[current];
prev = prev_idx[current];
triangles.push_back(Triangle(polygon[prev], polygon[current], polygon[next]));
return triangles;
}
bool Math::isConvex(const std::vector<Vector2> &polygon) {
if (polygon.size() < 3)
return false;
size_t i = polygon.size() - 2, j = polygon.size() - 1, k = 0;
Vector2 p = polygon[j] - polygon[i];
Vector2 q = polygon[k] - polygon[j];
float winding = Vector2::cross(p, q);
while (k + 1 < polygon.size()) {
i = j;
j = k;
k++;
p = polygon[j] - polygon[i];
q = polygon[k] - polygon[j];
if (Vector2::cross(p, q) * winding < 0)
return false;
}
return true;
}
// ============================================================================
// RandomGenerator implementation
// ============================================================================
static uint64_t wangHash64(uint64_t key) {
key = (~key) + (key << 21);
key = key ^ (key >> 24);
key = (key + (key << 3)) + (key << 8);
key = key ^ (key >> 14);
key = (key + (key << 2)) + (key << 4);
key = key ^ (key >> 28);
key = key + (key << 31);
return key;
}
RandomGenerator::RandomGenerator() : last_randomnormal_(std::numeric_limits<double>::infinity()) {
Seed newseed;
newseed.b32.low = 0xCBBF7A44;
newseed.b32.high = 0x0139408D;
setSeed(newseed);
}
RandomGenerator::~RandomGenerator() {
}
uint64_t RandomGenerator::rand() {
rng_state_.b64 ^= (rng_state_.b64 >> 12);
rng_state_.b64 ^= (rng_state_.b64 << 25);
rng_state_.b64 ^= (rng_state_.b64 >> 27);
return rng_state_.b64 * 2685821657736338717ULL;
}
double RandomGenerator::random() {
uint64_t r = rand();
union {
uint64_t i;
double d;
} u;
u.i = ((0x3FFULL) << 52) | (r >> 12);
return u.d - 1.0;
}
double RandomGenerator::random(double max) {
return random() * max;
}
double RandomGenerator::random(double min, double max) {
return random() * (max - min) + min;
}
double RandomGenerator::randomNormal(double stddev) {
if (last_randomnormal_ != std::numeric_limits<double>::infinity()) {
double r = last_randomnormal_;
last_randomnormal_ = std::numeric_limits<double>::infinity();
return r * stddev;
}
double r = std::sqrt(-2.0 * std::log(1.0 - random()));
double phi = 2.0 * M_PI * (1.0 - random());
last_randomnormal_ = r * std::cos(phi);
return r * std::sin(phi) * stddev;
}
void RandomGenerator::setSeed(Seed newseed) {
seed_ = newseed;
do {
newseed.b64 = wangHash64(newseed.b64);
} while (newseed.b64 == 0);
rng_state_ = newseed;
last_randomnormal_ = std::numeric_limits<double>::infinity();
}
void RandomGenerator::setSeed(uint64_t seed) {
Seed s;
s.b64 = seed;
setSeed(s);
}
void RandomGenerator::setSeed(uint32_t low, uint32_t high) {
Seed s;
s.b32.low = low;
s.b32.high = high;
setSeed(s);
}
RandomGenerator::Seed RandomGenerator::getSeed() const {
return seed_;
}
void RandomGenerator::setState(const std::string &statestr) {
if (statestr.find("0x") != 0 || statestr.size() < 3)
throw std::runtime_error("Invalid random state");
Seed state = {};
char *end = nullptr;
state.b64 = strtoull(statestr.c_str(), &end, 16);
if (end != nullptr && *end != 0)
throw std::runtime_error("Invalid random state");
rng_state_ = state;
last_randomnormal_ = std::numeric_limits<double>::infinity();
}
std::string RandomGenerator::getState() const {
std::stringstream ss;
ss << "0x" << std::setfill('0') << std::setw(16) << std::hex << rng_state_.b64;
return ss.str();
}
// ============================================================================
// BezierCurve implementation
// ============================================================================
static void subdivide(std::vector<Vector2> &points, int k) {
if (k <= 0)
return;
std::vector<Vector2> left, right;
left.reserve(points.size());
right.reserve(points.size());
for (size_t step = 1; step < points.size(); ++step) {
left.push_back(points[0]);
right.push_back(points[points.size() - step]);
for (size_t i = 0; i < points.size() - step; ++i)
points[i] = (points[i] + points[i + 1]) * 0.5f;
}
left.push_back(points[0]);
right.push_back(points[0]);
subdivide(left, k - 1);
subdivide(right, k - 1);
points.resize(left.size() + right.size() - 2);
for (size_t i = 0; i < left.size() - 1; ++i)
points[i] = left[i];
for (size_t i = 1; i < right.size(); ++i)
points[i - 1 + left.size() - 1] = right[right.size() - i - 1];
}
BezierCurve::BezierCurve(const std::vector<Vector2> &pts) : controlPoints_(pts) {
}
BezierCurve::~BezierCurve() {
}
BezierCurve *BezierCurve::getDerivative() const {
if (getDegree() < 1)
throw std::runtime_error("Cannot derive a curve of degree < 1.");
std::vector<Vector2> forward_differences(controlPoints_.size() - 1);
float degree = (float)getDegree();
for (size_t i = 0; i < forward_differences.size(); ++i)
forward_differences[i] = (controlPoints_[i + 1] - controlPoints_[i]) * degree;
return new BezierCurve(forward_differences);
}
const Vector2 &BezierCurve::getControlPoint(int i) const {
if (controlPoints_.size() == 0)
throw std::runtime_error("Curve contains no control points.");
while (i < 0)
i += controlPoints_.size();
while ((size_t)i >= controlPoints_.size())
i -= controlPoints_.size();
return controlPoints_[i];
}
void BezierCurve::setControlPoint(int i, const Vector2 &point) {
if (controlPoints_.size() == 0)
throw std::runtime_error("Curve contains no control points.");
while (i < 0)
i += controlPoints_.size();
while ((size_t)i >= controlPoints_.size())
i -= controlPoints_.size();
controlPoints_[i] = point;
}
void BezierCurve::insertControlPoint(const Vector2 &point, int i) {
if (controlPoints_.size() == 0)
i = 0;
else {
while (i < 0)
i += controlPoints_.size();
while ((size_t)i > controlPoints_.size())
i -= controlPoints_.size();
}
controlPoints_.insert(controlPoints_.begin() + i, point);
}
void BezierCurve::removeControlPoint(int i) {
if (controlPoints_.size() == 0)
throw std::runtime_error("No control points to remove.");
while (i < 0)
i += controlPoints_.size();
while ((size_t)i >= controlPoints_.size())
i -= controlPoints_.size();
controlPoints_.erase(controlPoints_.begin() + i);
}
void BezierCurve::translate(const Vector2 &t) {
for (size_t i = 0; i < controlPoints_.size(); ++i)
controlPoints_[i] += t;
}
void BezierCurve::rotate(double phi, const Vector2 ¢er) {
float c = std::cos(phi), s = std::sin(phi);
for (size_t i = 0; i < controlPoints_.size(); ++i) {
Vector2 v = controlPoints_[i] - center;
controlPoints_[i].x = c * v.x - s * v.y + center.x;
controlPoints_[i].y = s * v.x + c * v.y + center.y;
}
}
void BezierCurve::scale(double sc, const Vector2 ¢er) {
for (size_t i = 0; i < controlPoints_.size(); ++i)
controlPoints_[i] = (controlPoints_[i] - center) * (float)sc + center;
}
Vector2 BezierCurve::evaluate(double t) const {
if (t < 0 || t > 1)
throw std::runtime_error("Invalid evaluation parameter: must be between 0 and 1");
if (controlPoints_.size() < 2)
throw std::runtime_error("Invalid Bezier curve: Not enough control points.");
std::vector<Vector2> points(controlPoints_);
for (size_t step = 1; step < controlPoints_.size(); ++step)
for (size_t i = 0; i < controlPoints_.size() - step; ++i)
points[i] = points[i] * (float)(1 - t) + points[i + 1] * (float)t;
return points[0];
}
BezierCurve *BezierCurve::getSegment(double t1, double t2) const {
if (t1 < 0 || t2 > 1)
throw std::runtime_error("Invalid segment parameters: must be between 0 and 1");
if (t2 <= t1)
throw std::runtime_error("Invalid segment parameters: t1 must be smaller than t2");
std::vector<Vector2> points(controlPoints_);
std::vector<Vector2> left, right;
left.reserve(points.size());
right.reserve(points.size());
for (size_t step = 1; step < points.size(); ++step) {
left.push_back(points[0]);
for (size_t i = 0; i < points.size() - step; ++i)
points[i] = points[i] + (points[i + 1] - points[i]) * (float)t2;
}
left.push_back(points[0]);
double s = t1 / t2;
for (size_t step = 1; step < left.size(); ++step) {
right.push_back(left[left.size() - step]);
for (size_t i = 0; i < left.size() - step; ++i)
left[i] = left[i] + (left[i + 1] - left[i]) * (float)s;
}
right.push_back(left[0]);
std::reverse(right.begin(), right.end());
return new BezierCurve(right);
}
std::vector<Vector2> BezierCurve::render(int depth) const {
if (controlPoints_.size() < 2)
throw std::runtime_error("Invalid Bezier curve: Not enough control points.");
std::vector<Vector2> vertices(controlPoints_);
subdivide(vertices, depth);
return vertices;
}
std::vector<Vector2> BezierCurve::renderSegment(double start, double end, int depth) const {
if (controlPoints_.size() < 2)
throw std::runtime_error("Invalid Bezier curve: Not enough control points.");
std::vector<Vector2> vertices(controlPoints_);
subdivide(vertices, depth);
if (start == end) {
vertices.clear();
} else if (start < end) {
size_t start_idx = (size_t)(start * vertices.size());
size_t end_idx = (size_t)(end * vertices.size() + 0.5);
return std::vector<Vector2>(vertices.begin() + start_idx, vertices.begin() + end_idx);
} else {
size_t start_idx = (size_t)(end * vertices.size() + 0.5);
size_t end_idx = (size_t)(start * vertices.size());
return std::vector<Vector2>(vertices.begin() + start_idx, vertices.begin() + end_idx);
}
return vertices;
}
// ============================================================================
// Transform implementation
// ============================================================================
Transform::Transform() : matrix_(), inverseDirty_(true) {
}
Transform::Transform(const Matrix4 &m) : matrix_(m), inverseDirty_(true) {
}
Transform::Transform(float x, float y, float a, float sx, float sy, float ox, float oy, float kx, float ky)
: matrix_(x, y, a, sx, sy, ox, oy, kx, ky), inverseDirty_(true) {
}
Transform::~Transform() {
}
Transform *Transform::clone() const {
return new Transform(matrix_);
}
Transform *Transform::inverse() const {
return new Transform(matrix_.inverse());
}
void Transform::apply(Transform *other) {
matrix_ *= other->getMatrix();
inverseDirty_ = true;
}
void Transform::translate(float x, float y) {
matrix_.translate(x, y);
inverseDirty_ = true;
}
void Transform::rotate(float angle) {
matrix_.rotate(angle);
inverseDirty_ = true;
}
void Transform::scale(float x, float y) {
matrix_.scale(x, y);
inverseDirty_ = true;
}
void Transform::shear(float kx, float ky) {
matrix_.shear(kx, ky);
inverseDirty_ = true;
}
void Transform::reset() {
matrix_.setIdentity();
inverseDirty_ = true;
}
void Transform::setTransformation(float x, float y, float a, float sx, float sy, float ox, float oy, float kx, float ky) {
matrix_.setTransformation(x, y, a, sx, sy, ox, oy, kx, ky);
inverseDirty_ = true;
}
Vector2 Transform::transformPoint(Vector2 p) const {
Vector2 result;
matrix_.transformXY(&result, &p, 1);
return result;
}
Vector2 Transform::inverseTransformPoint(Vector2 p) {
Vector2 result;
getInverseMatrix().transformXY(&result, &p, 1);
return result;
}
void Transform::setMatrix(const Matrix4 &m) {
matrix_ = m;
inverseDirty_ = true;
}
bool Transform::isAffine2DTransform() const {
const float *e = matrix_.e;
return e[2] == 0 && e[3] == 0 && e[6] == 0 && e[7] == 0 && e[8] == 0 && e[9] == 0 && e[10] == 1 && e[11] == 0 && e[14] == 0 && e[15] == 1;
}
const Matrix4 &Transform::getInverseMatrix() {
if (inverseDirty_) {
inverseDirty_ = false;
inverseMatrix_ = matrix_.inverse();
}
return inverseMatrix_;
}
} // namespace modules
} // namespace joy
|
zyedidia/joy
| 1
|
A framework for building 2D desktop games in JavaScript, with a Love2D-inspired API
|
C++
|
zyedidia
|
Zachary Yedidia
|
Stanford University
|
src/modules/math/math.hh
|
C++ Header
|
#pragma once
#include <vector>
#include <string>
#include <cstdint>
namespace js {
class Context;
class Value;
} // namespace js
namespace joy {
namespace modules {
// Forward declarations
class RandomGenerator;
class BezierCurve;
class Transform;
// Vector2 structure for geometric operations
struct Vector2 {
float x, y;
Vector2() : x(0), y(0) {}
Vector2(float x_, float y_) : x(x_), y(y_) {}
Vector2 operator+(const Vector2 &other) const { return Vector2(x + other.x, y + other.y); }
Vector2 operator-(const Vector2 &other) const { return Vector2(x - other.x, y - other.y); }
Vector2 operator*(float s) const { return Vector2(x * s, y * s); }
Vector2 &operator+=(const Vector2 &other) { x += other.x; y += other.y; return *this; }
static float cross(const Vector2 &a, const Vector2 &b) { return a.x * b.y - a.y * b.x; }
};
// Triangle structure for triangulation
struct Triangle {
Triangle(const Vector2 &a_, const Vector2 &b_, const Vector2 &c_) : a(a_), b(b_), c(c_) {}
Vector2 a, b, c;
};
// 4x4 Matrix for Transform operations
class Matrix4 {
public:
float e[16];
Matrix4();
Matrix4(float x, float y, float a, float sx, float sy, float ox, float oy, float kx, float ky);
void setIdentity();
void setTransformation(float x, float y, float a, float sx, float sy, float ox, float oy, float kx, float ky);
void translate(float x, float y);
void rotate(float angle);
void scale(float x, float y);
void shear(float kx, float ky);
Matrix4 inverse() const;
Matrix4 operator*(const Matrix4 &other) const;
Matrix4 &operator*=(const Matrix4 &other);
void transformXY(Vector2 *dst, const Vector2 *src, int count) const;
};
// Math module class
class Math {
public:
Math();
~Math();
// Random number generation (uses internal RandomGenerator)
double random();
double random(double max);
double random(double min, double max);
double randomNormal(double stddev = 1.0, double mean = 0.0);
// Seed management
void setRandomSeed(uint64_t seed);
void setRandomSeed(uint32_t low, uint32_t high);
uint64_t getRandomSeed() const;
void getRandomSeed(uint32_t &low, uint32_t &high) const;
// State management
void setRandomState(const std::string &state);
std::string getRandomState() const;
// Factory functions for objects
RandomGenerator *newRandomGenerator();
RandomGenerator *newRandomGenerator(uint64_t seed);
RandomGenerator *newRandomGenerator(uint32_t low, uint32_t high);
BezierCurve *newBezierCurve(const std::vector<Vector2> &points);
Transform *newTransform();
Transform *newTransform(float x, float y, float a, float sx, float sy, float ox, float oy, float kx, float ky);
// Noise functions (returns values in [0, 1])
static double noise(double x);
static double noise(double x, double y);
static double noise(double x, double y, double z);
static double noise(double x, double y, double z, double w);
// Color conversion
static float gammaToLinear(float c);
static float linearToGamma(float c);
// Polygon functions
static std::vector<Triangle> triangulate(const std::vector<Vector2> &polygon);
static bool isConvex(const std::vector<Vector2> &polygon);
// Initialize JS bindings
static void initJS(js::Context &ctx, js::Value &joy);
private:
RandomGenerator *rng_;
};
// RandomGenerator class
class RandomGenerator {
public:
union Seed {
uint64_t b64;
struct {
uint32_t low;
uint32_t high;
} b32;
};
RandomGenerator();
~RandomGenerator();
uint64_t rand();
double random();
double random(double max);
double random(double min, double max);
double randomNormal(double stddev = 1.0);
void setSeed(Seed seed);
void setSeed(uint64_t seed);
void setSeed(uint32_t low, uint32_t high);
Seed getSeed() const;
void setState(const std::string &state);
std::string getState() const;
private:
Seed seed_;
Seed rng_state_;
double last_randomnormal_;
};
// BezierCurve class
class BezierCurve {
public:
BezierCurve(const std::vector<Vector2> &controlPoints);
~BezierCurve();
size_t getDegree() const { return controlPoints_.size() > 0 ? controlPoints_.size() - 1 : 0; }
size_t getControlPointCount() const { return controlPoints_.size(); }
BezierCurve *getDerivative() const;
BezierCurve *getSegment(double t1, double t2) const;
const Vector2 &getControlPoint(int i) const;
void setControlPoint(int i, const Vector2 &point);
void insertControlPoint(const Vector2 &point, int pos = -1);
void removeControlPoint(int i);
void translate(const Vector2 &t);
void rotate(double angle, const Vector2 ¢er = Vector2(0, 0));
void scale(double s, const Vector2 ¢er = Vector2(0, 0));
Vector2 evaluate(double t) const;
std::vector<Vector2> render(int depth = 5) const;
std::vector<Vector2> renderSegment(double start, double end, int depth = 5) const;
private:
std::vector<Vector2> controlPoints_;
};
// Transform class
class Transform {
public:
Transform();
Transform(const Matrix4 &m);
Transform(float x, float y, float a, float sx, float sy, float ox, float oy, float kx, float ky);
~Transform();
Transform *clone() const;
Transform *inverse() const;
void apply(Transform *other);
void translate(float x, float y);
void rotate(float angle);
void scale(float x, float y);
void shear(float kx, float ky);
void reset();
void setTransformation(float x, float y, float a, float sx, float sy, float ox, float oy, float kx, float ky);
Vector2 transformPoint(Vector2 p) const;
Vector2 inverseTransformPoint(Vector2 p);
const Matrix4 &getMatrix() const { return matrix_; }
void setMatrix(const Matrix4 &m);
bool isAffine2DTransform() const;
private:
const Matrix4 &getInverseMatrix();
Matrix4 matrix_;
Matrix4 inverseMatrix_;
bool inverseDirty_;
};
} // namespace modules
} // namespace joy
|
zyedidia/joy
| 1
|
A framework for building 2D desktop games in JavaScript, with a Love2D-inspired API
|
C++
|
zyedidia
|
Zachary Yedidia
|
Stanford University
|
src/modules/math/math_js.cc
|
C++
|
#include "js/js.hh"
#include "math.hh"
#include "engine.hh"
#include <cstdlib>
#include <vector>
namespace joy {
namespace modules {
// Helper to get Math module from JS context
static Math *getMath(js::FunctionArgs &args) {
Engine *engine = args.getContextOpaque<Engine>();
return engine ? engine->getMathModule() : nullptr;
}
// Class IDs for JS objects
static js::ClassID randomgenerator_class_id = 0;
static js::ClassID beziercurve_class_id = 0;
static js::ClassID transform_class_id = 0;
// ============================================================================
// RandomGenerator class
// ============================================================================
static void randomgenerator_finalizer(void *opaque) {
RandomGenerator *rng = static_cast<RandomGenerator *>(opaque);
delete rng;
}
static RandomGenerator *getRandomGenerator(js::FunctionArgs &args) {
js::Value thisVal = args.thisValue();
return static_cast<RandomGenerator *>(js::ClassBuilder::getOpaque(thisVal, randomgenerator_class_id));
}
static void js_rng_random(js::FunctionArgs &args) {
RandomGenerator *rng = getRandomGenerator(args);
if (!rng) {
args.returnUndefined();
return;
}
if (args.length() == 0) {
args.returnValue(js::Value::number(rng->random()));
} else if (args.length() == 1) {
double max = args.arg(0).toFloat64();
args.returnValue(js::Value::number(rng->random(max)));
} else {
double min = args.arg(0).toFloat64();
double max = args.arg(1).toFloat64();
args.returnValue(js::Value::number(rng->random(min, max)));
}
}
static void js_rng_randomNormal(js::FunctionArgs &args) {
RandomGenerator *rng = getRandomGenerator(args);
if (!rng) {
args.returnUndefined();
return;
}
double stddev = 1.0;
double mean = 0.0;
if (args.length() >= 1) stddev = args.arg(0).toFloat64();
if (args.length() >= 2) mean = args.arg(1).toFloat64();
args.returnValue(js::Value::number(rng->randomNormal(stddev) + mean));
}
static void js_rng_setSeed(js::FunctionArgs &args) {
RandomGenerator *rng = getRandomGenerator(args);
if (!rng || args.length() < 1) {
args.returnUndefined();
return;
}
if (args.length() >= 2) {
uint32_t low = static_cast<uint32_t>(args.arg(0).toFloat64());
uint32_t high = static_cast<uint32_t>(args.arg(1).toFloat64());
rng->setSeed(low, high);
} else {
uint64_t seed = static_cast<uint64_t>(args.arg(0).toFloat64());
rng->setSeed(seed);
}
args.returnUndefined();
}
static void js_rng_getSeed(js::FunctionArgs &args) {
RandomGenerator *rng = getRandomGenerator(args);
if (!rng) {
args.returnUndefined();
return;
}
RandomGenerator::Seed seed = rng->getSeed();
js::Value arr = js::Value::array(args.context());
arr.setProperty(args.context(), 0u, js::Value::number(static_cast<double>(seed.b32.low)));
arr.setProperty(args.context(), 1u, js::Value::number(static_cast<double>(seed.b32.high)));
args.returnValue(std::move(arr));
}
static void js_rng_setState(js::FunctionArgs &args) {
RandomGenerator *rng = getRandomGenerator(args);
if (!rng || args.length() < 1) {
args.returnUndefined();
return;
}
std::string state = args.arg(0).toString(args.context());
try {
rng->setState(state);
} catch (...) {
// Ignore invalid state
}
args.returnUndefined();
}
static void js_rng_getState(js::FunctionArgs &args) {
RandomGenerator *rng = getRandomGenerator(args);
if (!rng) {
args.returnUndefined();
return;
}
args.returnValue(js::Value::string(args.context(), rng->getState().c_str()));
}
// ============================================================================
// BezierCurve class
// ============================================================================
static void beziercurve_finalizer(void *opaque) {
BezierCurve *curve = static_cast<BezierCurve *>(opaque);
delete curve;
}
static BezierCurve *getBezierCurve(js::FunctionArgs &args) {
js::Value thisVal = args.thisValue();
return static_cast<BezierCurve *>(js::ClassBuilder::getOpaque(thisVal, beziercurve_class_id));
}
static void js_bezier_getDegree(js::FunctionArgs &args) {
BezierCurve *curve = getBezierCurve(args);
args.returnValue(js::Value::number(curve ? static_cast<double>(curve->getDegree()) : 0));
}
static void js_bezier_getControlPointCount(js::FunctionArgs &args) {
BezierCurve *curve = getBezierCurve(args);
args.returnValue(js::Value::number(curve ? static_cast<double>(curve->getControlPointCount()) : 0));
}
static void js_bezier_getControlPoint(js::FunctionArgs &args) {
BezierCurve *curve = getBezierCurve(args);
if (!curve || args.length() < 1) {
args.returnUndefined();
return;
}
int i = args.arg(0).toInt32() - 1; // Lua 1-based index
try {
const Vector2 &pt = curve->getControlPoint(i);
js::Value arr = js::Value::array(args.context());
arr.setProperty(args.context(), 0u, js::Value::number(pt.x));
arr.setProperty(args.context(), 1u, js::Value::number(pt.y));
args.returnValue(std::move(arr));
} catch (...) {
args.returnUndefined();
}
}
static void js_bezier_setControlPoint(js::FunctionArgs &args) {
BezierCurve *curve = getBezierCurve(args);
if (!curve || args.length() < 3) {
args.returnUndefined();
return;
}
int i = args.arg(0).toInt32() - 1;
float x = static_cast<float>(args.arg(1).toFloat64());
float y = static_cast<float>(args.arg(2).toFloat64());
try {
curve->setControlPoint(i, Vector2(x, y));
} catch (...) {
// Ignore
}
args.returnUndefined();
}
static void js_bezier_insertControlPoint(js::FunctionArgs &args) {
BezierCurve *curve = getBezierCurve(args);
if (!curve || args.length() < 2) {
args.returnUndefined();
return;
}
float x = static_cast<float>(args.arg(0).toFloat64());
float y = static_cast<float>(args.arg(1).toFloat64());
int pos = args.length() >= 3 ? args.arg(2).toInt32() - 1 : -1;
curve->insertControlPoint(Vector2(x, y), pos);
args.returnUndefined();
}
static void js_bezier_removeControlPoint(js::FunctionArgs &args) {
BezierCurve *curve = getBezierCurve(args);
if (!curve || args.length() < 1) {
args.returnUndefined();
return;
}
int i = args.arg(0).toInt32() - 1;
try {
curve->removeControlPoint(i);
} catch (...) {
// Ignore
}
args.returnUndefined();
}
static void js_bezier_translate(js::FunctionArgs &args) {
BezierCurve *curve = getBezierCurve(args);
if (!curve || args.length() < 2) {
args.returnUndefined();
return;
}
float x = static_cast<float>(args.arg(0).toFloat64());
float y = static_cast<float>(args.arg(1).toFloat64());
curve->translate(Vector2(x, y));
args.returnUndefined();
}
static void js_bezier_rotate(js::FunctionArgs &args) {
BezierCurve *curve = getBezierCurve(args);
if (!curve || args.length() < 1) {
args.returnUndefined();
return;
}
double angle = args.arg(0).toFloat64();
float ox = args.length() >= 2 ? static_cast<float>(args.arg(1).toFloat64()) : 0;
float oy = args.length() >= 3 ? static_cast<float>(args.arg(2).toFloat64()) : 0;
curve->rotate(angle, Vector2(ox, oy));
args.returnUndefined();
}
static void js_bezier_scale(js::FunctionArgs &args) {
BezierCurve *curve = getBezierCurve(args);
if (!curve || args.length() < 1) {
args.returnUndefined();
return;
}
double s = args.arg(0).toFloat64();
float ox = args.length() >= 2 ? static_cast<float>(args.arg(1).toFloat64()) : 0;
float oy = args.length() >= 3 ? static_cast<float>(args.arg(2).toFloat64()) : 0;
curve->scale(s, Vector2(ox, oy));
args.returnUndefined();
}
static void js_bezier_evaluate(js::FunctionArgs &args) {
BezierCurve *curve = getBezierCurve(args);
if (!curve || args.length() < 1) {
args.returnUndefined();
return;
}
double t = args.arg(0).toFloat64();
try {
Vector2 pt = curve->evaluate(t);
js::Value arr = js::Value::array(args.context());
arr.setProperty(args.context(), 0u, js::Value::number(pt.x));
arr.setProperty(args.context(), 1u, js::Value::number(pt.y));
args.returnValue(std::move(arr));
} catch (...) {
args.returnUndefined();
}
}
static void js_bezier_getDerivative(js::FunctionArgs &args) {
BezierCurve *curve = getBezierCurve(args);
if (!curve) {
args.returnValue(js::Value::null());
return;
}
try {
BezierCurve *deriv = curve->getDerivative();
js::Value obj = js::ClassBuilder::newInstance(args.context(), beziercurve_class_id);
js::ClassBuilder::setOpaque(obj, deriv);
args.returnValue(std::move(obj));
} catch (...) {
args.returnValue(js::Value::null());
}
}
static void js_bezier_getSegment(js::FunctionArgs &args) {
BezierCurve *curve = getBezierCurve(args);
if (!curve || args.length() < 2) {
args.returnValue(js::Value::null());
return;
}
double t1 = args.arg(0).toFloat64();
double t2 = args.arg(1).toFloat64();
try {
BezierCurve *seg = curve->getSegment(t1, t2);
js::Value obj = js::ClassBuilder::newInstance(args.context(), beziercurve_class_id);
js::ClassBuilder::setOpaque(obj, seg);
args.returnValue(std::move(obj));
} catch (...) {
args.returnValue(js::Value::null());
}
}
static void js_bezier_render(js::FunctionArgs &args) {
BezierCurve *curve = getBezierCurve(args);
if (!curve) {
args.returnValue(js::Value::array(args.context()));
return;
}
int depth = args.length() >= 1 ? args.arg(0).toInt32() : 5;
try {
std::vector<Vector2> pts = curve->render(depth);
js::Value arr = js::Value::array(args.context());
for (size_t i = 0; i < pts.size(); i++) {
arr.setProperty(args.context(), static_cast<uint32_t>(i * 2), js::Value::number(pts[i].x));
arr.setProperty(args.context(), static_cast<uint32_t>(i * 2 + 1), js::Value::number(pts[i].y));
}
args.returnValue(std::move(arr));
} catch (...) {
args.returnValue(js::Value::array(args.context()));
}
}
static void js_bezier_renderSegment(js::FunctionArgs &args) {
BezierCurve *curve = getBezierCurve(args);
if (!curve || args.length() < 2) {
args.returnValue(js::Value::array(args.context()));
return;
}
double start = args.arg(0).toFloat64();
double end = args.arg(1).toFloat64();
int depth = args.length() >= 3 ? args.arg(2).toInt32() : 5;
try {
std::vector<Vector2> pts = curve->renderSegment(start, end, depth);
js::Value arr = js::Value::array(args.context());
for (size_t i = 0; i < pts.size(); i++) {
arr.setProperty(args.context(), static_cast<uint32_t>(i * 2), js::Value::number(pts[i].x));
arr.setProperty(args.context(), static_cast<uint32_t>(i * 2 + 1), js::Value::number(pts[i].y));
}
args.returnValue(std::move(arr));
} catch (...) {
args.returnValue(js::Value::array(args.context()));
}
}
// ============================================================================
// Transform class
// ============================================================================
static void transform_finalizer(void *opaque) {
Transform *tr = static_cast<Transform *>(opaque);
delete tr;
}
static Transform *getTransform(js::FunctionArgs &args) {
js::Value thisVal = args.thisValue();
return static_cast<Transform *>(js::ClassBuilder::getOpaque(thisVal, transform_class_id));
}
static void js_transform_clone(js::FunctionArgs &args) {
Transform *tr = getTransform(args);
if (!tr) {
args.returnValue(js::Value::null());
return;
}
Transform *clone = tr->clone();
js::Value obj = js::ClassBuilder::newInstance(args.context(), transform_class_id);
js::ClassBuilder::setOpaque(obj, clone);
args.returnValue(std::move(obj));
}
static void js_transform_inverse(js::FunctionArgs &args) {
Transform *tr = getTransform(args);
if (!tr) {
args.returnValue(js::Value::null());
return;
}
Transform *inv = tr->inverse();
js::Value obj = js::ClassBuilder::newInstance(args.context(), transform_class_id);
js::ClassBuilder::setOpaque(obj, inv);
args.returnValue(std::move(obj));
}
static void js_transform_apply(js::FunctionArgs &args) {
Transform *tr = getTransform(args);
if (!tr || args.length() < 1) {
args.returnUndefined();
return;
}
Transform *other = static_cast<Transform *>(js::ClassBuilder::getOpaque(args.arg(0), transform_class_id));
if (other) {
tr->apply(other);
}
// Return this for chaining
args.returnValue(args.thisValue());
}
static void js_transform_translate(js::FunctionArgs &args) {
Transform *tr = getTransform(args);
if (!tr || args.length() < 2) {
args.returnValue(args.thisValue());
return;
}
float x = static_cast<float>(args.arg(0).toFloat64());
float y = static_cast<float>(args.arg(1).toFloat64());
tr->translate(x, y);
args.returnValue(args.thisValue());
}
static void js_transform_rotate(js::FunctionArgs &args) {
Transform *tr = getTransform(args);
if (!tr || args.length() < 1) {
args.returnValue(args.thisValue());
return;
}
float angle = static_cast<float>(args.arg(0).toFloat64());
tr->rotate(angle);
args.returnValue(args.thisValue());
}
static void js_transform_scale(js::FunctionArgs &args) {
Transform *tr = getTransform(args);
if (!tr || args.length() < 1) {
args.returnValue(args.thisValue());
return;
}
float sx = static_cast<float>(args.arg(0).toFloat64());
float sy = args.length() >= 2 ? static_cast<float>(args.arg(1).toFloat64()) : sx;
tr->scale(sx, sy);
args.returnValue(args.thisValue());
}
static void js_transform_shear(js::FunctionArgs &args) {
Transform *tr = getTransform(args);
if (!tr || args.length() < 2) {
args.returnValue(args.thisValue());
return;
}
float kx = static_cast<float>(args.arg(0).toFloat64());
float ky = static_cast<float>(args.arg(1).toFloat64());
tr->shear(kx, ky);
args.returnValue(args.thisValue());
}
static void js_transform_reset(js::FunctionArgs &args) {
Transform *tr = getTransform(args);
if (tr) {
tr->reset();
}
args.returnValue(args.thisValue());
}
static void js_transform_setTransformation(js::FunctionArgs &args) {
Transform *tr = getTransform(args);
if (!tr) {
args.returnValue(args.thisValue());
return;
}
float x = args.length() >= 1 ? static_cast<float>(args.arg(0).toFloat64()) : 0;
float y = args.length() >= 2 ? static_cast<float>(args.arg(1).toFloat64()) : 0;
float a = args.length() >= 3 ? static_cast<float>(args.arg(2).toFloat64()) : 0;
float sx = args.length() >= 4 ? static_cast<float>(args.arg(3).toFloat64()) : 1;
float sy = args.length() >= 5 ? static_cast<float>(args.arg(4).toFloat64()) : sx;
float ox = args.length() >= 6 ? static_cast<float>(args.arg(5).toFloat64()) : 0;
float oy = args.length() >= 7 ? static_cast<float>(args.arg(6).toFloat64()) : 0;
float kx = args.length() >= 8 ? static_cast<float>(args.arg(7).toFloat64()) : 0;
float ky = args.length() >= 9 ? static_cast<float>(args.arg(8).toFloat64()) : 0;
tr->setTransformation(x, y, a, sx, sy, ox, oy, kx, ky);
args.returnValue(args.thisValue());
}
static void js_transform_transformPoint(js::FunctionArgs &args) {
Transform *tr = getTransform(args);
if (!tr || args.length() < 2) {
args.returnUndefined();
return;
}
float x = static_cast<float>(args.arg(0).toFloat64());
float y = static_cast<float>(args.arg(1).toFloat64());
Vector2 result = tr->transformPoint(Vector2(x, y));
js::Value arr = js::Value::array(args.context());
arr.setProperty(args.context(), 0u, js::Value::number(result.x));
arr.setProperty(args.context(), 1u, js::Value::number(result.y));
args.returnValue(std::move(arr));
}
static void js_transform_inverseTransformPoint(js::FunctionArgs &args) {
Transform *tr = getTransform(args);
if (!tr || args.length() < 2) {
args.returnUndefined();
return;
}
float x = static_cast<float>(args.arg(0).toFloat64());
float y = static_cast<float>(args.arg(1).toFloat64());
Vector2 result = tr->inverseTransformPoint(Vector2(x, y));
js::Value arr = js::Value::array(args.context());
arr.setProperty(args.context(), 0u, js::Value::number(result.x));
arr.setProperty(args.context(), 1u, js::Value::number(result.y));
args.returnValue(std::move(arr));
}
static void js_transform_getMatrix(js::FunctionArgs &args) {
Transform *tr = getTransform(args);
if (!tr) {
args.returnUndefined();
return;
}
const Matrix4 &m = tr->getMatrix();
js::Value arr = js::Value::array(args.context());
for (int i = 0; i < 16; i++) {
arr.setProperty(args.context(), static_cast<uint32_t>(i), js::Value::number(m.e[i]));
}
args.returnValue(std::move(arr));
}
static void js_transform_setMatrix(js::FunctionArgs &args) {
Transform *tr = getTransform(args);
if (!tr) {
args.returnValue(args.thisValue());
return;
}
Matrix4 m;
if (args.length() == 1 && args.arg(0).isArray()) {
// Array of 16 values
js::Value arr = args.arg(0);
for (int i = 0; i < 16; i++) {
m.e[i] = static_cast<float>(arr.getProperty(args.context(), static_cast<uint32_t>(i)).toFloat64());
}
} else if (args.length() >= 16) {
// 16 separate arguments
for (int i = 0; i < 16; i++) {
m.e[i] = static_cast<float>(args.arg(i).toFloat64());
}
}
tr->setMatrix(m);
args.returnValue(args.thisValue());
}
static void js_transform_isAffine2DTransform(js::FunctionArgs &args) {
Transform *tr = getTransform(args);
args.returnValue(js::Value::boolean(tr ? tr->isAffine2DTransform() : false));
}
// ============================================================================
// Module-level math functions
// ============================================================================
// joy.math.random(min, max) or joy.math.random(max) or joy.math.random()
static void js_math_random(js::FunctionArgs &args) {
Math *math = getMath(args);
if (!math) {
args.returnUndefined();
return;
}
if (args.length() == 0) {
args.returnValue(js::Value::number(math->random()));
} else if (args.length() == 1) {
double max = args.arg(0).toFloat64();
// Love2D: random(max) returns integer in [1, max] when max >= 1
if (max >= 1) {
int result = static_cast<int>(math->random() * max) + 1;
if (result > max) result = static_cast<int>(max);
args.returnValue(js::Value::number(result));
} else {
args.returnValue(js::Value::number(math->random(max)));
}
} else {
double min = args.arg(0).toFloat64();
double max = args.arg(1).toFloat64();
// Love2D: random(min, max) returns integer in [min, max]
int result = static_cast<int>(min + math->random() * (max - min + 1));
if (result > max) result = static_cast<int>(max);
args.returnValue(js::Value::number(result));
}
}
static void js_math_randomNormal(js::FunctionArgs &args) {
Math *math = getMath(args);
if (!math) {
args.returnUndefined();
return;
}
double stddev = args.length() >= 1 ? args.arg(0).toFloat64() : 1.0;
double mean = args.length() >= 2 ? args.arg(1).toFloat64() : 0.0;
args.returnValue(js::Value::number(math->randomNormal(stddev, mean)));
}
static void js_math_setRandomSeed(js::FunctionArgs &args) {
Math *math = getMath(args);
if (!math || args.length() < 1) {
args.returnUndefined();
return;
}
if (args.length() >= 2) {
uint32_t low = static_cast<uint32_t>(args.arg(0).toFloat64());
uint32_t high = static_cast<uint32_t>(args.arg(1).toFloat64());
math->setRandomSeed(low, high);
} else {
uint64_t seed = static_cast<uint64_t>(args.arg(0).toFloat64());
math->setRandomSeed(seed);
}
args.returnUndefined();
}
static void js_math_getRandomSeed(js::FunctionArgs &args) {
Math *math = getMath(args);
if (!math) {
args.returnUndefined();
return;
}
uint32_t low, high;
math->getRandomSeed(low, high);
js::Value arr = js::Value::array(args.context());
arr.setProperty(args.context(), 0u, js::Value::number(static_cast<double>(low)));
arr.setProperty(args.context(), 1u, js::Value::number(static_cast<double>(high)));
args.returnValue(std::move(arr));
}
static void js_math_setRandomState(js::FunctionArgs &args) {
Math *math = getMath(args);
if (!math || args.length() < 1) {
args.returnUndefined();
return;
}
std::string state = args.arg(0).toString(args.context());
try {
math->setRandomState(state);
} catch (...) {
// Ignore
}
args.returnUndefined();
}
static void js_math_getRandomState(js::FunctionArgs &args) {
Math *math = getMath(args);
if (!math) {
args.returnUndefined();
return;
}
args.returnValue(js::Value::string(args.context(), math->getRandomState().c_str()));
}
static void js_math_newRandomGenerator(js::FunctionArgs &args) {
Math *math = getMath(args);
if (!math) {
args.returnValue(js::Value::null());
return;
}
RandomGenerator *rng;
if (args.length() >= 2) {
uint32_t low = static_cast<uint32_t>(args.arg(0).toFloat64());
uint32_t high = static_cast<uint32_t>(args.arg(1).toFloat64());
rng = math->newRandomGenerator(low, high);
} else if (args.length() >= 1) {
uint64_t seed = static_cast<uint64_t>(args.arg(0).toFloat64());
rng = math->newRandomGenerator(seed);
} else {
rng = math->newRandomGenerator();
}
js::Value obj = js::ClassBuilder::newInstance(args.context(), randomgenerator_class_id);
js::ClassBuilder::setOpaque(obj, rng);
args.returnValue(std::move(obj));
}
static void js_math_newBezierCurve(js::FunctionArgs &args) {
Math *math = getMath(args);
if (!math || args.length() < 1) {
args.returnValue(js::Value::null());
return;
}
std::vector<Vector2> points;
// Can accept either flat array [x1, y1, x2, y2, ...] or individual args
if (args.arg(0).isArray()) {
js::Value arr = args.arg(0);
js::Value lenVal = arr.getProperty(args.context(), "length");
int len = lenVal.toInt32();
for (int i = 0; i < len - 1; i += 2) {
float x = static_cast<float>(arr.getProperty(args.context(), static_cast<uint32_t>(i)).toFloat64());
float y = static_cast<float>(arr.getProperty(args.context(), static_cast<uint32_t>(i + 1)).toFloat64());
points.push_back(Vector2(x, y));
}
} else {
for (int i = 0; i < args.length() - 1; i += 2) {
float x = static_cast<float>(args.arg(i).toFloat64());
float y = static_cast<float>(args.arg(i + 1).toFloat64());
points.push_back(Vector2(x, y));
}
}
if (points.empty()) {
args.returnValue(js::Value::null());
return;
}
BezierCurve *curve = math->newBezierCurve(points);
js::Value obj = js::ClassBuilder::newInstance(args.context(), beziercurve_class_id);
js::ClassBuilder::setOpaque(obj, curve);
args.returnValue(std::move(obj));
}
static void js_math_newTransform(js::FunctionArgs &args) {
Math *math = getMath(args);
if (!math) {
args.returnValue(js::Value::null());
return;
}
Transform *tr;
if (args.length() == 0) {
tr = math->newTransform();
} else {
float x = args.length() >= 1 ? static_cast<float>(args.arg(0).toFloat64()) : 0;
float y = args.length() >= 2 ? static_cast<float>(args.arg(1).toFloat64()) : 0;
float a = args.length() >= 3 ? static_cast<float>(args.arg(2).toFloat64()) : 0;
float sx = args.length() >= 4 ? static_cast<float>(args.arg(3).toFloat64()) : 1;
float sy = args.length() >= 5 ? static_cast<float>(args.arg(4).toFloat64()) : sx;
float ox = args.length() >= 6 ? static_cast<float>(args.arg(5).toFloat64()) : 0;
float oy = args.length() >= 7 ? static_cast<float>(args.arg(6).toFloat64()) : 0;
float kx = args.length() >= 8 ? static_cast<float>(args.arg(7).toFloat64()) : 0;
float ky = args.length() >= 9 ? static_cast<float>(args.arg(8).toFloat64()) : 0;
tr = math->newTransform(x, y, a, sx, sy, ox, oy, kx, ky);
}
js::Value obj = js::ClassBuilder::newInstance(args.context(), transform_class_id);
js::ClassBuilder::setOpaque(obj, tr);
args.returnValue(std::move(obj));
}
static void js_math_noise(js::FunctionArgs &args) {
if (args.length() < 1) {
args.returnUndefined();
return;
}
double result;
if (args.length() == 1) {
result = Math::noise(args.arg(0).toFloat64());
} else if (args.length() == 2) {
result = Math::noise(args.arg(0).toFloat64(), args.arg(1).toFloat64());
} else if (args.length() == 3) {
result = Math::noise(args.arg(0).toFloat64(), args.arg(1).toFloat64(), args.arg(2).toFloat64());
} else {
result = Math::noise(args.arg(0).toFloat64(), args.arg(1).toFloat64(), args.arg(2).toFloat64(), args.arg(3).toFloat64());
}
args.returnValue(js::Value::number(result));
}
static void js_math_gammaToLinear(js::FunctionArgs &args) {
if (args.length() < 1) {
args.returnUndefined();
return;
}
// Can accept r, g, b or r, g, b, a or single value
if (args.length() >= 3) {
float r = Math::gammaToLinear(static_cast<float>(args.arg(0).toFloat64()));
float g = Math::gammaToLinear(static_cast<float>(args.arg(1).toFloat64()));
float b = Math::gammaToLinear(static_cast<float>(args.arg(2).toFloat64()));
js::Value arr = js::Value::array(args.context());
arr.setProperty(args.context(), 0u, js::Value::number(r));
arr.setProperty(args.context(), 1u, js::Value::number(g));
arr.setProperty(args.context(), 2u, js::Value::number(b));
if (args.length() >= 4) {
float a = static_cast<float>(args.arg(3).toFloat64()); // Alpha is not converted
arr.setProperty(args.context(), 3u, js::Value::number(a));
}
args.returnValue(std::move(arr));
} else {
float result = Math::gammaToLinear(static_cast<float>(args.arg(0).toFloat64()));
args.returnValue(js::Value::number(result));
}
}
static void js_math_linearToGamma(js::FunctionArgs &args) {
if (args.length() < 1) {
args.returnUndefined();
return;
}
if (args.length() >= 3) {
float r = Math::linearToGamma(static_cast<float>(args.arg(0).toFloat64()));
float g = Math::linearToGamma(static_cast<float>(args.arg(1).toFloat64()));
float b = Math::linearToGamma(static_cast<float>(args.arg(2).toFloat64()));
js::Value arr = js::Value::array(args.context());
arr.setProperty(args.context(), 0u, js::Value::number(r));
arr.setProperty(args.context(), 1u, js::Value::number(g));
arr.setProperty(args.context(), 2u, js::Value::number(b));
if (args.length() >= 4) {
float a = static_cast<float>(args.arg(3).toFloat64());
arr.setProperty(args.context(), 3u, js::Value::number(a));
}
args.returnValue(std::move(arr));
} else {
float result = Math::linearToGamma(static_cast<float>(args.arg(0).toFloat64()));
args.returnValue(js::Value::number(result));
}
}
static void js_math_triangulate(js::FunctionArgs &args) {
if (args.length() < 1) {
args.returnValue(js::Value::array(args.context()));
return;
}
std::vector<Vector2> polygon;
// Accept flat array [x1, y1, x2, y2, ...] or varargs
if (args.arg(0).isArray()) {
js::Value arr = args.arg(0);
js::Value lenVal = arr.getProperty(args.context(), "length");
int len = lenVal.toInt32();
for (int i = 0; i < len - 1; i += 2) {
float x = static_cast<float>(arr.getProperty(args.context(), static_cast<uint32_t>(i)).toFloat64());
float y = static_cast<float>(arr.getProperty(args.context(), static_cast<uint32_t>(i + 1)).toFloat64());
polygon.push_back(Vector2(x, y));
}
} else {
for (int i = 0; i < args.length() - 1; i += 2) {
float x = static_cast<float>(args.arg(i).toFloat64());
float y = static_cast<float>(args.arg(i + 1).toFloat64());
polygon.push_back(Vector2(x, y));
}
}
if (polygon.size() < 3) {
args.returnValue(js::Value::array(args.context()));
return;
}
try {
std::vector<Triangle> triangles = Math::triangulate(polygon);
js::Value result = js::Value::array(args.context());
for (size_t i = 0; i < triangles.size(); i++) {
const Triangle &tri = triangles[i];
js::Value triArr = js::Value::array(args.context());
triArr.setProperty(args.context(), 0u, js::Value::number(tri.a.x));
triArr.setProperty(args.context(), 1u, js::Value::number(tri.a.y));
triArr.setProperty(args.context(), 2u, js::Value::number(tri.b.x));
triArr.setProperty(args.context(), 3u, js::Value::number(tri.b.y));
triArr.setProperty(args.context(), 4u, js::Value::number(tri.c.x));
triArr.setProperty(args.context(), 5u, js::Value::number(tri.c.y));
result.setProperty(args.context(), static_cast<uint32_t>(i), std::move(triArr));
}
args.returnValue(std::move(result));
} catch (...) {
args.returnValue(js::Value::array(args.context()));
}
}
static void js_math_isConvex(js::FunctionArgs &args) {
if (args.length() < 1) {
args.returnValue(js::Value::boolean(false));
return;
}
std::vector<Vector2> polygon;
if (args.arg(0).isArray()) {
js::Value arr = args.arg(0);
js::Value lenVal = arr.getProperty(args.context(), "length");
int len = lenVal.toInt32();
for (int i = 0; i < len - 1; i += 2) {
float x = static_cast<float>(arr.getProperty(args.context(), static_cast<uint32_t>(i)).toFloat64());
float y = static_cast<float>(arr.getProperty(args.context(), static_cast<uint32_t>(i + 1)).toFloat64());
polygon.push_back(Vector2(x, y));
}
} else {
for (int i = 0; i < args.length() - 1; i += 2) {
float x = static_cast<float>(args.arg(i).toFloat64());
float y = static_cast<float>(args.arg(i + 1).toFloat64());
polygon.push_back(Vector2(x, y));
}
}
args.returnValue(js::Value::boolean(Math::isConvex(polygon)));
}
// ============================================================================
// Module initialization
// ============================================================================
void Math::initJS(js::Context &ctx, js::Value &joy) {
// Register RandomGenerator class
js::ClassDef rngDef;
rngDef.name = "RandomGenerator";
rngDef.finalizer = randomgenerator_finalizer;
randomgenerator_class_id = js::ClassBuilder::registerClass(ctx, rngDef);
js::Value rngProto = js::ModuleBuilder(ctx, "__rng_proto__")
.function("random", js_rng_random, 2)
.function("randomNormal", js_rng_randomNormal, 2)
.function("setSeed", js_rng_setSeed, 2)
.function("getSeed", js_rng_getSeed, 0)
.function("setState", js_rng_setState, 1)
.function("getState", js_rng_getState, 0)
.build();
js::ClassBuilder::setPrototype(ctx, randomgenerator_class_id, rngProto);
// Register BezierCurve class
js::ClassDef bezierDef;
bezierDef.name = "BezierCurve";
bezierDef.finalizer = beziercurve_finalizer;
beziercurve_class_id = js::ClassBuilder::registerClass(ctx, bezierDef);
js::Value bezierProto = js::ModuleBuilder(ctx, "__bezier_proto__")
.function("getDegree", js_bezier_getDegree, 0)
.function("getControlPointCount", js_bezier_getControlPointCount, 0)
.function("getControlPoint", js_bezier_getControlPoint, 1)
.function("setControlPoint", js_bezier_setControlPoint, 3)
.function("insertControlPoint", js_bezier_insertControlPoint, 3)
.function("removeControlPoint", js_bezier_removeControlPoint, 1)
.function("translate", js_bezier_translate, 2)
.function("rotate", js_bezier_rotate, 3)
.function("scale", js_bezier_scale, 3)
.function("evaluate", js_bezier_evaluate, 1)
.function("getDerivative", js_bezier_getDerivative, 0)
.function("getSegment", js_bezier_getSegment, 2)
.function("render", js_bezier_render, 1)
.function("renderSegment", js_bezier_renderSegment, 3)
.build();
js::ClassBuilder::setPrototype(ctx, beziercurve_class_id, bezierProto);
// Register Transform class
js::ClassDef transformDef;
transformDef.name = "Transform";
transformDef.finalizer = transform_finalizer;
transform_class_id = js::ClassBuilder::registerClass(ctx, transformDef);
js::Value transformProto = js::ModuleBuilder(ctx, "__transform_proto__")
.function("clone", js_transform_clone, 0)
.function("inverse", js_transform_inverse, 0)
.function("apply", js_transform_apply, 1)
.function("translate", js_transform_translate, 2)
.function("rotate", js_transform_rotate, 1)
.function("scale", js_transform_scale, 2)
.function("shear", js_transform_shear, 2)
.function("reset", js_transform_reset, 0)
.function("setTransformation", js_transform_setTransformation, 9)
.function("transformPoint", js_transform_transformPoint, 2)
.function("inverseTransformPoint", js_transform_inverseTransformPoint, 2)
.function("getMatrix", js_transform_getMatrix, 0)
.function("setMatrix", js_transform_setMatrix, 16)
.function("isAffine2DTransform", js_transform_isAffine2DTransform, 0)
.build();
js::ClassBuilder::setPrototype(ctx, transform_class_id, transformProto);
// Register math module functions
js::ModuleBuilder(ctx, "math")
.function("random", js_math_random, 2)
.function("randomNormal", js_math_randomNormal, 2)
.function("setRandomSeed", js_math_setRandomSeed, 2)
.function("getRandomSeed", js_math_getRandomSeed, 0)
.function("setRandomState", js_math_setRandomState, 1)
.function("getRandomState", js_math_getRandomState, 0)
.function("newRandomGenerator", js_math_newRandomGenerator, 2)
.function("newBezierCurve", js_math_newBezierCurve, 1)
.function("newTransform", js_math_newTransform, 9)
.function("noise", js_math_noise, 4)
.function("gammaToLinear", js_math_gammaToLinear, 4)
.function("linearToGamma", js_math_linearToGamma, 4)
.function("triangulate", js_math_triangulate, 1)
.function("isConvex", js_math_isConvex, 1)
.attachTo(joy);
}
} // namespace modules
} // namespace joy
|
zyedidia/joy
| 1
|
A framework for building 2D desktop games in JavaScript, with a Love2D-inspired API
|
C++
|
zyedidia
|
Zachary Yedidia
|
Stanford University
|
src/modules/math/noise1234.cc
|
C++
|
// Noise1234
// Author: Stefan Gustavson (stegu@itn.liu.se)
//
// This library is public domain software, released by the author
// into the public domain in February 2011. You may do anything
// you like with it. You may even remove all attributions,
// but of course I'd appreciate it if you kept my name somewhere.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// Modified for Joy engine to use double precision.
#include "noise1234.hh"
#define FADE(t) (t * t * t * (t * (t * 6 - 15) + 10))
#define FASTFLOOR(x) (((x) > 0) ? ((int)x) : ((int)x - 1))
#define LERP(t, a, b) ((a) + (t) * ((b) - (a)))
// Permutation table. This is just a random jumble of all numbers 0-255,
// repeated twice to avoid wrapping the index at 255 for each lookup.
unsigned char Noise1234::perm[] = {
151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225, 140, 36, 103, 30, 69, 142, 8, 99, 37, 240,
21, 10, 23, 190, 6, 148, 247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32, 57, 177, 33, 88,
237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175, 74, 165, 71, 134, 139, 48, 27, 166, 77, 146, 158, 231, 83,
111, 229, 122, 60, 211, 133, 230, 220, 105, 92, 41, 55, 46, 245, 40, 244, 102, 143, 54, 65, 25, 63, 161, 1, 216,
80, 73, 209, 76, 132, 187, 208, 89, 18, 169, 200, 196, 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186,
3, 64, 52, 217, 226, 250, 124, 123, 5, 202, 38, 147, 118, 126, 255, 82, 85, 212, 207, 206, 59, 227, 47, 16, 58,
17, 182, 189, 28, 42, 223, 183, 170, 213, 119, 248, 152, 2, 44, 154, 163, 70, 221, 153, 101, 155, 167, 43, 172, 9,
129, 22, 39, 253, 19, 98, 108, 110, 79, 113, 224, 232, 178, 185, 112, 104, 218, 246, 97, 228, 251, 34, 242, 193,
238, 210, 144, 12, 191, 179, 162, 241, 81, 51, 145, 235, 249, 14, 239, 107, 49, 192, 214, 31, 181, 199, 106, 157,
184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150, 254, 138, 236, 205, 93, 222, 114, 67, 29, 24, 72, 243, 141, 128,
195, 78, 66, 215, 61, 156, 180,
151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225, 140, 36, 103, 30, 69, 142, 8, 99, 37, 240,
21, 10, 23, 190, 6, 148, 247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32, 57, 177, 33, 88,
237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175, 74, 165, 71, 134, 139, 48, 27, 166, 77, 146, 158, 231, 83,
111, 229, 122, 60, 211, 133, 230, 220, 105, 92, 41, 55, 46, 245, 40, 244, 102, 143, 54, 65, 25, 63, 161, 1, 216,
80, 73, 209, 76, 132, 187, 208, 89, 18, 169, 200, 196, 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186,
3, 64, 52, 217, 226, 250, 124, 123, 5, 202, 38, 147, 118, 126, 255, 82, 85, 212, 207, 206, 59, 227, 47, 16, 58,
17, 182, 189, 28, 42, 223, 183, 170, 213, 119, 248, 152, 2, 44, 154, 163, 70, 221, 153, 101, 155, 167, 43, 172, 9,
129, 22, 39, 253, 19, 98, 108, 110, 79, 113, 224, 232, 178, 185, 112, 104, 218, 246, 97, 228, 251, 34, 242, 193,
238, 210, 144, 12, 191, 179, 162, 241, 81, 51, 145, 235, 249, 14, 239, 107, 49, 192, 214, 31, 181, 199, 106, 157,
184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150, 254, 138, 236, 205, 93, 222, 114, 67, 29, 24, 72, 243, 141, 128,
195, 78, 66, 215, 61, 156, 180
};
double Noise1234::grad(int hash, double x) {
int h = hash & 15;
double grad = 1.0 + (h & 7);
if (h & 8) grad = -grad;
return grad * x;
}
double Noise1234::grad(int hash, double x, double y) {
int h = hash & 7;
double u = h < 4 ? x : y;
double v = h < 4 ? y : x;
return ((h & 1) ? -u : u) + ((h & 2) ? -2.0 * v : 2.0 * v);
}
double Noise1234::grad(int hash, double x, double y, double z) {
int h = hash & 15;
double u = h < 8 ? x : y;
double v = h < 4 ? y : h == 12 || h == 14 ? x : z;
return ((h & 1) ? -u : u) + ((h & 2) ? -v : v);
}
double Noise1234::grad(int hash, double x, double y, double z, double t) {
int h = hash & 31;
double u = h < 24 ? x : y;
double v = h < 16 ? y : z;
double w = h < 8 ? z : t;
return ((h & 1) ? -u : u) + ((h & 2) ? -v : v) + ((h & 4) ? -w : w);
}
// 1D Perlin noise
double Noise1234::noise(double x) {
int ix0, ix1;
double fx0, fx1;
double s, n0, n1;
ix0 = FASTFLOOR(x);
fx0 = x - ix0;
fx1 = fx0 - 1.0;
ix1 = (ix0 + 1) & 0xff;
ix0 = ix0 & 0xff;
s = FADE(fx0);
n0 = grad(perm[ix0], fx0);
n1 = grad(perm[ix1], fx1);
return 0.188 * LERP(s, n0, n1);
}
// 2D Perlin noise
double Noise1234::noise(double x, double y) {
int ix0, iy0, ix1, iy1;
double fx0, fy0, fx1, fy1;
double s, t, nx0, nx1, n0, n1;
ix0 = FASTFLOOR(x);
iy0 = FASTFLOOR(y);
fx0 = x - ix0;
fy0 = y - iy0;
fx1 = fx0 - 1.0;
fy1 = fy0 - 1.0;
ix1 = (ix0 + 1) & 0xff;
iy1 = (iy0 + 1) & 0xff;
ix0 = ix0 & 0xff;
iy0 = iy0 & 0xff;
t = FADE(fy0);
s = FADE(fx0);
nx0 = grad(perm[ix0 + perm[iy0]], fx0, fy0);
nx1 = grad(perm[ix0 + perm[iy1]], fx0, fy1);
n0 = LERP(t, nx0, nx1);
nx0 = grad(perm[ix1 + perm[iy0]], fx1, fy0);
nx1 = grad(perm[ix1 + perm[iy1]], fx1, fy1);
n1 = LERP(t, nx0, nx1);
return 0.507 * LERP(s, n0, n1);
}
// 3D Perlin noise
double Noise1234::noise(double x, double y, double z) {
int ix0, iy0, ix1, iy1, iz0, iz1;
double fx0, fy0, fz0, fx1, fy1, fz1;
double s, t, r;
double nxy0, nxy1, nx0, nx1, n0, n1;
ix0 = FASTFLOOR(x);
iy0 = FASTFLOOR(y);
iz0 = FASTFLOOR(z);
fx0 = x - ix0;
fy0 = y - iy0;
fz0 = z - iz0;
fx1 = fx0 - 1.0;
fy1 = fy0 - 1.0;
fz1 = fz0 - 1.0;
ix1 = (ix0 + 1) & 0xff;
iy1 = (iy0 + 1) & 0xff;
iz1 = (iz0 + 1) & 0xff;
ix0 = ix0 & 0xff;
iy0 = iy0 & 0xff;
iz0 = iz0 & 0xff;
r = FADE(fz0);
t = FADE(fy0);
s = FADE(fx0);
nxy0 = grad(perm[ix0 + perm[iy0 + perm[iz0]]], fx0, fy0, fz0);
nxy1 = grad(perm[ix0 + perm[iy0 + perm[iz1]]], fx0, fy0, fz1);
nx0 = LERP(r, nxy0, nxy1);
nxy0 = grad(perm[ix0 + perm[iy1 + perm[iz0]]], fx0, fy1, fz0);
nxy1 = grad(perm[ix0 + perm[iy1 + perm[iz1]]], fx0, fy1, fz1);
nx1 = LERP(r, nxy0, nxy1);
n0 = LERP(t, nx0, nx1);
nxy0 = grad(perm[ix1 + perm[iy0 + perm[iz0]]], fx1, fy0, fz0);
nxy1 = grad(perm[ix1 + perm[iy0 + perm[iz1]]], fx1, fy0, fz1);
nx0 = LERP(r, nxy0, nxy1);
nxy0 = grad(perm[ix1 + perm[iy1 + perm[iz0]]], fx1, fy1, fz0);
nxy1 = grad(perm[ix1 + perm[iy1 + perm[iz1]]], fx1, fy1, fz1);
nx1 = LERP(r, nxy0, nxy1);
n1 = LERP(t, nx0, nx1);
return 0.936 * LERP(s, n0, n1);
}
// 4D Perlin noise
double Noise1234::noise(double x, double y, double z, double w) {
int ix0, iy0, iz0, iw0, ix1, iy1, iz1, iw1;
double fx0, fy0, fz0, fw0, fx1, fy1, fz1, fw1;
double s, t, r, q;
double nxyz0, nxyz1, nxy0, nxy1, nx0, nx1, n0, n1;
ix0 = FASTFLOOR(x);
iy0 = FASTFLOOR(y);
iz0 = FASTFLOOR(z);
iw0 = FASTFLOOR(w);
fx0 = x - ix0;
fy0 = y - iy0;
fz0 = z - iz0;
fw0 = w - iw0;
fx1 = fx0 - 1.0;
fy1 = fy0 - 1.0;
fz1 = fz0 - 1.0;
fw1 = fw0 - 1.0;
ix1 = (ix0 + 1) & 0xff;
iy1 = (iy0 + 1) & 0xff;
iz1 = (iz0 + 1) & 0xff;
iw1 = (iw0 + 1) & 0xff;
ix0 = ix0 & 0xff;
iy0 = iy0 & 0xff;
iz0 = iz0 & 0xff;
iw0 = iw0 & 0xff;
q = FADE(fw0);
r = FADE(fz0);
t = FADE(fy0);
s = FADE(fx0);
nxyz0 = grad(perm[ix0 + perm[iy0 + perm[iz0 + perm[iw0]]]], fx0, fy0, fz0, fw0);
nxyz1 = grad(perm[ix0 + perm[iy0 + perm[iz0 + perm[iw1]]]], fx0, fy0, fz0, fw1);
nxy0 = LERP(q, nxyz0, nxyz1);
nxyz0 = grad(perm[ix0 + perm[iy0 + perm[iz1 + perm[iw0]]]], fx0, fy0, fz1, fw0);
nxyz1 = grad(perm[ix0 + perm[iy0 + perm[iz1 + perm[iw1]]]], fx0, fy0, fz1, fw1);
nxy1 = LERP(q, nxyz0, nxyz1);
nx0 = LERP(r, nxy0, nxy1);
nxyz0 = grad(perm[ix0 + perm[iy1 + perm[iz0 + perm[iw0]]]], fx0, fy1, fz0, fw0);
nxyz1 = grad(perm[ix0 + perm[iy1 + perm[iz0 + perm[iw1]]]], fx0, fy1, fz0, fw1);
nxy0 = LERP(q, nxyz0, nxyz1);
nxyz0 = grad(perm[ix0 + perm[iy1 + perm[iz1 + perm[iw0]]]], fx0, fy1, fz1, fw0);
nxyz1 = grad(perm[ix0 + perm[iy1 + perm[iz1 + perm[iw1]]]], fx0, fy1, fz1, fw1);
nxy1 = LERP(q, nxyz0, nxyz1);
nx1 = LERP(r, nxy0, nxy1);
n0 = LERP(t, nx0, nx1);
nxyz0 = grad(perm[ix1 + perm[iy0 + perm[iz0 + perm[iw0]]]], fx1, fy0, fz0, fw0);
nxyz1 = grad(perm[ix1 + perm[iy0 + perm[iz0 + perm[iw1]]]], fx1, fy0, fz0, fw1);
nxy0 = LERP(q, nxyz0, nxyz1);
nxyz0 = grad(perm[ix1 + perm[iy0 + perm[iz1 + perm[iw0]]]], fx1, fy0, fz1, fw0);
nxyz1 = grad(perm[ix1 + perm[iy0 + perm[iz1 + perm[iw1]]]], fx1, fy0, fz1, fw1);
nxy1 = LERP(q, nxyz0, nxyz1);
nx0 = LERP(r, nxy0, nxy1);
nxyz0 = grad(perm[ix1 + perm[iy1 + perm[iz0 + perm[iw0]]]], fx1, fy1, fz0, fw0);
nxyz1 = grad(perm[ix1 + perm[iy1 + perm[iz0 + perm[iw1]]]], fx1, fy1, fz0, fw1);
nxy0 = LERP(q, nxyz0, nxyz1);
nxyz0 = grad(perm[ix1 + perm[iy1 + perm[iz1 + perm[iw0]]]], fx1, fy1, fz1, fw0);
nxyz1 = grad(perm[ix1 + perm[iy1 + perm[iz1 + perm[iw1]]]], fx1, fy1, fz1, fw1);
nxy1 = LERP(q, nxyz0, nxyz1);
nx1 = LERP(r, nxy0, nxy1);
n1 = LERP(t, nx0, nx1);
return 0.87 * LERP(s, n0, n1);
}
|
zyedidia/joy
| 1
|
A framework for building 2D desktop games in JavaScript, with a Love2D-inspired API
|
C++
|
zyedidia
|
Zachary Yedidia
|
Stanford University
|
src/modules/math/noise1234.hh
|
C++ Header
|
// Noise1234
// Author: Stefan Gustavson (stegu@itn.liu.se)
//
// This library is public domain software, released by the author
// into the public domain in February 2011. You may do anything
// you like with it. You may even remove all attributions,
// but of course I'd appreciate it if you kept my name somewhere.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// Modified for Joy engine to use double precision.
#pragma once
class Noise1234 {
public:
Noise1234() {}
~Noise1234() {}
// 1D, 2D, 3D and 4D float Perlin noise
static double noise(double x);
static double noise(double x, double y);
static double noise(double x, double y, double z);
static double noise(double x, double y, double z, double w);
private:
static unsigned char perm[];
static double grad(int hash, double x);
static double grad(int hash, double x, double y);
static double grad(int hash, double x, double y, double z);
static double grad(int hash, double x, double y, double z, double t);
};
|
zyedidia/joy
| 1
|
A framework for building 2D desktop games in JavaScript, with a Love2D-inspired API
|
C++
|
zyedidia
|
Zachary Yedidia
|
Stanford University
|
src/modules/math/simplexnoise1234.cc
|
C++
|
// SimplexNoise1234
// Copyright 2003-2011, Stefan Gustavson
//
// Contact: stegu@itn.liu.se
//
// This library is public domain software, released by the author
// into the public domain in February 2011. You may do anything
// you like with it. You may even remove all attributions,
// but of course I'd appreciate it if you kept my name somewhere.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// Modified for Joy engine to use double precision.
#include "simplexnoise1234.hh"
#define FASTFLOOR(x) (((x) > 0) ? ((int)x) : (((int)x) - 1))
// Permutation table. This is just a random jumble of all numbers 0-255,
// repeated twice to avoid wrapping the index at 255 for each lookup.
unsigned char SimplexNoise1234::perm[512] = {
151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225, 140, 36, 103, 30, 69, 142, 8, 99, 37, 240,
21, 10, 23, 190, 6, 148, 247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32, 57, 177, 33, 88,
237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175, 74, 165, 71, 134, 139, 48, 27, 166, 77, 146, 158, 231, 83,
111, 229, 122, 60, 211, 133, 230, 220, 105, 92, 41, 55, 46, 245, 40, 244, 102, 143, 54, 65, 25, 63, 161, 1, 216,
80, 73, 209, 76, 132, 187, 208, 89, 18, 169, 200, 196, 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186,
3, 64, 52, 217, 226, 250, 124, 123, 5, 202, 38, 147, 118, 126, 255, 82, 85, 212, 207, 206, 59, 227, 47, 16, 58,
17, 182, 189, 28, 42, 223, 183, 170, 213, 119, 248, 152, 2, 44, 154, 163, 70, 221, 153, 101, 155, 167, 43, 172, 9,
129, 22, 39, 253, 19, 98, 108, 110, 79, 113, 224, 232, 178, 185, 112, 104, 218, 246, 97, 228, 251, 34, 242, 193,
238, 210, 144, 12, 191, 179, 162, 241, 81, 51, 145, 235, 249, 14, 239, 107, 49, 192, 214, 31, 181, 199, 106, 157,
184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150, 254, 138, 236, 205, 93, 222, 114, 67, 29, 24, 72, 243, 141, 128,
195, 78, 66, 215, 61, 156, 180,
151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225, 140, 36, 103, 30, 69, 142, 8, 99, 37, 240,
21, 10, 23, 190, 6, 148, 247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32, 57, 177, 33, 88,
237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175, 74, 165, 71, 134, 139, 48, 27, 166, 77, 146, 158, 231, 83,
111, 229, 122, 60, 211, 133, 230, 220, 105, 92, 41, 55, 46, 245, 40, 244, 102, 143, 54, 65, 25, 63, 161, 1, 216,
80, 73, 209, 76, 132, 187, 208, 89, 18, 169, 200, 196, 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186,
3, 64, 52, 217, 226, 250, 124, 123, 5, 202, 38, 147, 118, 126, 255, 82, 85, 212, 207, 206, 59, 227, 47, 16, 58,
17, 182, 189, 28, 42, 223, 183, 170, 213, 119, 248, 152, 2, 44, 154, 163, 70, 221, 153, 101, 155, 167, 43, 172, 9,
129, 22, 39, 253, 19, 98, 108, 110, 79, 113, 224, 232, 178, 185, 112, 104, 218, 246, 97, 228, 251, 34, 242, 193,
238, 210, 144, 12, 191, 179, 162, 241, 81, 51, 145, 235, 249, 14, 239, 107, 49, 192, 214, 31, 181, 199, 106, 157,
184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150, 254, 138, 236, 205, 93, 222, 114, 67, 29, 24, 72, 243, 141, 128,
195, 78, 66, 215, 61, 156, 180
};
// Lookup table for 4D simplex traversal
static unsigned char simplex[64][4] = {
{0, 1, 2, 3}, {0, 1, 3, 2}, {0, 0, 0, 0}, {0, 2, 3, 1}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {1, 2, 3, 0},
{0, 2, 1, 3}, {0, 0, 0, 0}, {0, 3, 1, 2}, {0, 3, 2, 1}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {1, 3, 2, 0},
{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0},
{1, 2, 0, 3}, {0, 0, 0, 0}, {1, 3, 0, 2}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {2, 3, 0, 1}, {2, 3, 1, 0},
{1, 0, 2, 3}, {1, 0, 3, 2}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {2, 0, 3, 1}, {0, 0, 0, 0}, {2, 1, 3, 0},
{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0},
{2, 0, 1, 3}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {3, 0, 1, 2}, {3, 0, 2, 1}, {0, 0, 0, 0}, {3, 1, 2, 0},
{2, 1, 0, 3}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {3, 1, 0, 2}, {0, 0, 0, 0}, {3, 2, 0, 1}, {3, 2, 1, 0}
};
double SimplexNoise1234::grad(int hash, double x) {
int h = hash & 15;
double grad = 1.0 + (h & 7);
if (h & 8) grad = -grad;
return grad * x;
}
double SimplexNoise1234::grad(int hash, double x, double y) {
int h = hash & 7;
double u = h < 4 ? x : y;
double v = h < 4 ? y : x;
return ((h & 1) ? -u : u) + ((h & 2) ? -2.0 * v : 2.0 * v);
}
double SimplexNoise1234::grad(int hash, double x, double y, double z) {
int h = hash & 15;
double u = h < 8 ? x : y;
double v = h < 4 ? y : h == 12 || h == 14 ? x : z;
return ((h & 1) ? -u : u) + ((h & 2) ? -v : v);
}
double SimplexNoise1234::grad(int hash, double x, double y, double z, double t) {
int h = hash & 31;
double u = h < 24 ? x : y;
double v = h < 16 ? y : z;
double w = h < 8 ? z : t;
return ((h & 1) ? -u : u) + ((h & 2) ? -v : v) + ((h & 4) ? -w : w);
}
// 1D simplex noise
double SimplexNoise1234::noise(double x) {
int i0 = FASTFLOOR(x);
int i1 = i0 + 1;
double x0 = x - i0;
double x1 = x0 - 1.0;
double n0, n1;
double t0 = 1.0 - x0 * x0;
t0 *= t0;
n0 = t0 * t0 * grad(perm[i0 & 0xff], x0);
double t1 = 1.0 - x1 * x1;
t1 *= t1;
n1 = t1 * t1 * grad(perm[i1 & 0xff], x1);
return 0.395 * (n0 + n1);
}
// 2D simplex noise
double SimplexNoise1234::noise(double x, double y) {
const double F2 = 0.366025403; // 0.5*(sqrt(3.0)-1.0)
const double G2 = 0.211324865; // (3.0-sqrt(3.0))/6.0
double n0, n1, n2;
double s = (x + y) * F2;
double xs = x + s;
double ys = y + s;
int i = FASTFLOOR(xs);
int j = FASTFLOOR(ys);
double t = (i + j) * G2;
double X0 = i - t;
double Y0 = j - t;
double x0 = x - X0;
double y0 = y - Y0;
int i1, j1;
if (x0 > y0) { i1 = 1; j1 = 0; }
else { i1 = 0; j1 = 1; }
double x1 = x0 - i1 + G2;
double y1 = y0 - j1 + G2;
double x2 = x0 - 1.0 + 2.0 * G2;
double y2 = y0 - 1.0 + 2.0 * G2;
int ii = i & 0xff;
int jj = j & 0xff;
double t0 = 0.5 - x0 * x0 - y0 * y0;
if (t0 < 0.0) n0 = 0.0;
else { t0 *= t0; n0 = t0 * t0 * grad(perm[ii + perm[jj]], x0, y0); }
double t1 = 0.5 - x1 * x1 - y1 * y1;
if (t1 < 0.0) n1 = 0.0;
else { t1 *= t1; n1 = t1 * t1 * grad(perm[ii + i1 + perm[jj + j1]], x1, y1); }
double t2 = 0.5 - x2 * x2 - y2 * y2;
if (t2 < 0.0) n2 = 0.0;
else { t2 *= t2; n2 = t2 * t2 * grad(perm[ii + 1 + perm[jj + 1]], x2, y2); }
return 45.23 * (n0 + n1 + n2);
}
// 3D simplex noise
double SimplexNoise1234::noise(double x, double y, double z) {
const double F3 = 0.333333333;
const double G3 = 0.166666667;
double n0, n1, n2, n3;
double s = (x + y + z) * F3;
double xs = x + s;
double ys = y + s;
double zs = z + s;
int i = FASTFLOOR(xs);
int j = FASTFLOOR(ys);
int k = FASTFLOOR(zs);
double t = (double)(i + j + k) * G3;
double X0 = i - t;
double Y0 = j - t;
double Z0 = k - t;
double x0 = x - X0;
double y0 = y - Y0;
double z0 = z - Z0;
int i1, j1, k1;
int i2, j2, k2;
if (x0 >= y0) {
if (y0 >= z0) { i1 = 1; j1 = 0; k1 = 0; i2 = 1; j2 = 1; k2 = 0; }
else if (x0 >= z0) { i1 = 1; j1 = 0; k1 = 0; i2 = 1; j2 = 0; k2 = 1; }
else { i1 = 0; j1 = 0; k1 = 1; i2 = 1; j2 = 0; k2 = 1; }
} else {
if (y0 < z0) { i1 = 0; j1 = 0; k1 = 1; i2 = 0; j2 = 1; k2 = 1; }
else if (x0 < z0) { i1 = 0; j1 = 1; k1 = 0; i2 = 0; j2 = 1; k2 = 1; }
else { i1 = 0; j1 = 1; k1 = 0; i2 = 1; j2 = 1; k2 = 0; }
}
double x1 = x0 - i1 + G3;
double y1 = y0 - j1 + G3;
double z1 = z0 - k1 + G3;
double x2 = x0 - i2 + 2.0 * G3;
double y2 = y0 - j2 + 2.0 * G3;
double z2 = z0 - k2 + 2.0 * G3;
double x3 = x0 - 1.0 + 3.0 * G3;
double y3 = y0 - 1.0 + 3.0 * G3;
double z3 = z0 - 1.0 + 3.0 * G3;
int ii = i & 0xff;
int jj = j & 0xff;
int kk = k & 0xff;
double t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0;
if (t0 < 0.0) n0 = 0.0;
else { t0 *= t0; n0 = t0 * t0 * grad(perm[ii + perm[jj + perm[kk]]], x0, y0, z0); }
double t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1;
if (t1 < 0.0) n1 = 0.0;
else { t1 *= t1; n1 = t1 * t1 * grad(perm[ii + i1 + perm[jj + j1 + perm[kk + k1]]], x1, y1, z1); }
double t2 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2;
if (t2 < 0.0) n2 = 0.0;
else { t2 *= t2; n2 = t2 * t2 * grad(perm[ii + i2 + perm[jj + j2 + perm[kk + k2]]], x2, y2, z2); }
double t3 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3;
if (t3 < 0.0) n3 = 0.0;
else { t3 *= t3; n3 = t3 * t3 * grad(perm[ii + 1 + perm[jj + 1 + perm[kk + 1]]], x3, y3, z3); }
return 32.74 * (n0 + n1 + n2 + n3);
}
// 4D simplex noise
double SimplexNoise1234::noise(double x, double y, double z, double w) {
const double F4 = 0.309016994; // (sqrt(5.0)-1.0)/4.0
const double G4 = 0.138196601; // (5.0-sqrt(5.0))/20.0
double n0, n1, n2, n3, n4;
double s = (x + y + z + w) * F4;
double xs = x + s;
double ys = y + s;
double zs = z + s;
double ws = w + s;
int i = FASTFLOOR(xs);
int j = FASTFLOOR(ys);
int k = FASTFLOOR(zs);
int l = FASTFLOOR(ws);
double t = (i + j + k + l) * G4;
double X0 = i - t;
double Y0 = j - t;
double Z0 = k - t;
double W0 = l - t;
double x0 = x - X0;
double y0 = y - Y0;
double z0 = z - Z0;
double w0 = w - W0;
int c1 = (x0 > y0) ? 32 : 0;
int c2 = (x0 > z0) ? 16 : 0;
int c3 = (y0 > z0) ? 8 : 0;
int c4 = (x0 > w0) ? 4 : 0;
int c5 = (y0 > w0) ? 2 : 0;
int c6 = (z0 > w0) ? 1 : 0;
int c = c1 + c2 + c3 + c4 + c5 + c6;
int i1, j1, k1, l1;
int i2, j2, k2, l2;
int i3, j3, k3, l3;
i1 = simplex[c][0] >= 3 ? 1 : 0;
j1 = simplex[c][1] >= 3 ? 1 : 0;
k1 = simplex[c][2] >= 3 ? 1 : 0;
l1 = simplex[c][3] >= 3 ? 1 : 0;
i2 = simplex[c][0] >= 2 ? 1 : 0;
j2 = simplex[c][1] >= 2 ? 1 : 0;
k2 = simplex[c][2] >= 2 ? 1 : 0;
l2 = simplex[c][3] >= 2 ? 1 : 0;
i3 = simplex[c][0] >= 1 ? 1 : 0;
j3 = simplex[c][1] >= 1 ? 1 : 0;
k3 = simplex[c][2] >= 1 ? 1 : 0;
l3 = simplex[c][3] >= 1 ? 1 : 0;
double x1 = x0 - i1 + G4;
double y1 = y0 - j1 + G4;
double z1 = z0 - k1 + G4;
double w1 = w0 - l1 + G4;
double x2 = x0 - i2 + 2.0 * G4;
double y2 = y0 - j2 + 2.0 * G4;
double z2 = z0 - k2 + 2.0 * G4;
double w2 = w0 - l2 + 2.0 * G4;
double x3 = x0 - i3 + 3.0 * G4;
double y3 = y0 - j3 + 3.0 * G4;
double z3 = z0 - k3 + 3.0 * G4;
double w3 = w0 - l3 + 3.0 * G4;
double x4 = x0 - 1.0 + 4.0 * G4;
double y4 = y0 - 1.0 + 4.0 * G4;
double z4 = z0 - 1.0 + 4.0 * G4;
double w4 = w0 - 1.0 + 4.0 * G4;
int ii = i & 0xff;
int jj = j & 0xff;
int kk = k & 0xff;
int ll = l & 0xff;
double t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0 - w0 * w0;
if (t0 < 0.0) n0 = 0.0;
else { t0 *= t0; n0 = t0 * t0 * grad(perm[ii + perm[jj + perm[kk + perm[ll]]]], x0, y0, z0, w0); }
double t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1 - w1 * w1;
if (t1 < 0.0) n1 = 0.0;
else { t1 *= t1; n1 = t1 * t1 * grad(perm[ii + i1 + perm[jj + j1 + perm[kk + k1 + perm[ll + l1]]]], x1, y1, z1, w1); }
double t2 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2 - w2 * w2;
if (t2 < 0.0) n2 = 0.0;
else { t2 *= t2; n2 = t2 * t2 * grad(perm[ii + i2 + perm[jj + j2 + perm[kk + k2 + perm[ll + l2]]]], x2, y2, z2, w2); }
double t3 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3 - w3 * w3;
if (t3 < 0.0) n3 = 0.0;
else { t3 *= t3; n3 = t3 * t3 * grad(perm[ii + i3 + perm[jj + j3 + perm[kk + k3 + perm[ll + l3]]]], x3, y3, z3, w3); }
double t4 = 0.6 - x4 * x4 - y4 * y4 - z4 * z4 - w4 * w4;
if (t4 < 0.0) n4 = 0.0;
else { t4 *= t4; n4 = t4 * t4 * grad(perm[ii + 1 + perm[jj + 1 + perm[kk + 1 + perm[ll + 1]]]], x4, y4, z4, w4); }
return 27.3 * (n0 + n1 + n2 + n3 + n4);
}
|
zyedidia/joy
| 1
|
A framework for building 2D desktop games in JavaScript, with a Love2D-inspired API
|
C++
|
zyedidia
|
Zachary Yedidia
|
Stanford University
|
src/modules/math/simplexnoise1234.hh
|
C++ Header
|
// SimplexNoise1234
// Copyright 2003-2011, Stefan Gustavson
//
// Contact: stegu@itn.liu.se
//
// This library is public domain software, released by the author
// into the public domain in February 2011. You may do anything
// you like with it. You may even remove all attributions,
// but of course I'd appreciate it if you kept my name somewhere.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// Modified for Joy engine to use double precision.
#pragma once
class SimplexNoise1234 {
public:
SimplexNoise1234() {}
~SimplexNoise1234() {}
// 1D, 2D, 3D and 4D simplex noise
static double noise(double x);
static double noise(double x, double y);
static double noise(double x, double y, double z);
static double noise(double x, double y, double z, double w);
private:
static unsigned char perm[];
static double grad(int hash, double x);
static double grad(int hash, double x, double y);
static double grad(int hash, double x, double y, double z);
static double grad(int hash, double x, double y, double z, double t);
};
|
zyedidia/joy
| 1
|
A framework for building 2D desktop games in JavaScript, with a Love2D-inspired API
|
C++
|
zyedidia
|
Zachary Yedidia
|
Stanford University
|
src/modules/mouse/mouse.cc
|
C++
|
#include "mouse.hh"
#include "engine.hh"
#include <unordered_map>
#include <string>
#include <cstring>
namespace joy {
namespace modules {
// System cursor name to enum mapping
static const std::unordered_map<std::string, SystemCursor> name_to_system_cursor = {
{"arrow", SystemCursor::Arrow},
{"ibeam", SystemCursor::Ibeam},
{"wait", SystemCursor::Wait},
{"crosshair", SystemCursor::Crosshair},
{"waitarrow", SystemCursor::WaitArrow},
{"sizenwse", SystemCursor::SizeNWSE},
{"sizenesw", SystemCursor::SizeNESW},
{"sizewe", SystemCursor::SizeWE},
{"sizens", SystemCursor::SizeNS},
{"sizeall", SystemCursor::SizeAll},
{"no", SystemCursor::No},
{"hand", SystemCursor::Hand},
};
// System cursor enum to name mapping
static const char *system_cursor_names[] = {
"arrow",
"ibeam",
"wait",
"crosshair",
"waitarrow",
"sizenwse",
"sizenesw",
"sizewe",
"sizens",
"sizeall",
"no",
"hand",
};
// Cursor type names
static const char *cursor_type_names[] = {
"system",
"image",
};
// Map SystemCursor to SDL_SystemCursor
static SDL_SystemCursor toSDLSystemCursor(SystemCursor cursor) {
switch (cursor) {
case SystemCursor::Arrow: return SDL_SYSTEM_CURSOR_DEFAULT;
case SystemCursor::Ibeam: return SDL_SYSTEM_CURSOR_TEXT;
case SystemCursor::Wait: return SDL_SYSTEM_CURSOR_WAIT;
case SystemCursor::Crosshair: return SDL_SYSTEM_CURSOR_CROSSHAIR;
case SystemCursor::WaitArrow: return SDL_SYSTEM_CURSOR_PROGRESS;
case SystemCursor::SizeNWSE: return SDL_SYSTEM_CURSOR_NWSE_RESIZE;
case SystemCursor::SizeNESW: return SDL_SYSTEM_CURSOR_NESW_RESIZE;
case SystemCursor::SizeWE: return SDL_SYSTEM_CURSOR_EW_RESIZE;
case SystemCursor::SizeNS: return SDL_SYSTEM_CURSOR_NS_RESIZE;
case SystemCursor::SizeAll: return SDL_SYSTEM_CURSOR_MOVE;
case SystemCursor::No: return SDL_SYSTEM_CURSOR_NOT_ALLOWED;
case SystemCursor::Hand: return SDL_SYSTEM_CURSOR_POINTER;
default: return SDL_SYSTEM_CURSOR_DEFAULT;
}
}
// Cursor implementation
Cursor::Cursor()
: cursor_(nullptr)
, type_(CursorType::System)
, system_type_(SystemCursor::Arrow)
{
}
Cursor::~Cursor() {
if (cursor_) {
SDL_DestroyCursor(cursor_);
}
}
bool Cursor::initSystem(SystemCursor type) {
if (cursor_) {
SDL_DestroyCursor(cursor_);
cursor_ = nullptr;
}
SDL_SystemCursor sdl_cursor = toSDLSystemCursor(type);
cursor_ = SDL_CreateSystemCursor(sdl_cursor);
if (!cursor_) {
return false;
}
type_ = CursorType::System;
system_type_ = type;
return true;
}
bool Cursor::initFromPixels(const unsigned char *data, int width, int height, int hotx, int hoty) {
if (cursor_) {
SDL_DestroyCursor(cursor_);
cursor_ = nullptr;
}
// Create SDL surface from RGBA data
SDL_Surface *surface = SDL_CreateSurfaceFrom(
width, height,
SDL_PIXELFORMAT_RGBA32,
const_cast<unsigned char *>(data),
width * 4
);
if (!surface) {
return false;
}
cursor_ = SDL_CreateColorCursor(surface, hotx, hoty);
SDL_DestroySurface(surface);
if (!cursor_) {
return false;
}
type_ = CursorType::Image;
system_type_ = SystemCursor::Arrow; // Not applicable for image cursors
return true;
}
bool Cursor::getSystemCursor(const char *name, SystemCursor &out) {
auto it = name_to_system_cursor.find(name);
if (it != name_to_system_cursor.end()) {
out = it->second;
return true;
}
return false;
}
const char *Cursor::getSystemCursorName(SystemCursor cursor) {
int idx = static_cast<int>(cursor);
if (idx >= 0 && idx < static_cast<int>(SystemCursor::MaxEnum)) {
return system_cursor_names[idx];
}
return nullptr;
}
const char *Cursor::getCursorTypeName(CursorType type) {
int idx = static_cast<int>(type);
if (idx >= 0 && idx < static_cast<int>(CursorType::MaxEnum)) {
return cursor_type_names[idx];
}
return nullptr;
}
// Mouse implementation
Mouse::Mouse(Engine *engine)
: engine_(engine)
, current_cursor_(nullptr)
{
}
Mouse::~Mouse() {
}
void Mouse::getPosition(double &x, double &y) const {
float fx, fy;
SDL_GetMouseState(&fx, &fy);
x = static_cast<double>(fx);
y = static_cast<double>(fy);
}
void Mouse::setPosition(double x, double y) {
SDL_Window *window = engine_->getWindow();
if (window) {
SDL_WarpMouseInWindow(window, static_cast<float>(x), static_cast<float>(y));
}
}
double Mouse::getX() const {
double x, y;
getPosition(x, y);
return x;
}
double Mouse::getY() const {
double x, y;
getPosition(x, y);
return y;
}
void Mouse::setX(double x) {
setPosition(x, getY());
}
void Mouse::setY(double y) {
setPosition(getX(), y);
}
bool Mouse::isDown(const int *buttons, int count) const {
SDL_MouseButtonFlags state = SDL_GetMouseState(nullptr, nullptr);
for (int i = 0; i < count; i++) {
int button = buttons[i];
// Love2D uses 1-indexed buttons: 1=left, 2=right, 3=middle
// SDL uses: SDL_BUTTON_LEFT=1, SDL_BUTTON_MIDDLE=2, SDL_BUTTON_RIGHT=3
// Love2D: 1=left, 2=right, 3=middle
// SDL: 1=left, 2=middle, 3=right
// So we need to swap 2 and 3
int sdl_button = button;
if (button == 2) {
sdl_button = SDL_BUTTON_RIGHT;
} else if (button == 3) {
sdl_button = SDL_BUTTON_MIDDLE;
}
if (state & SDL_BUTTON_MASK(sdl_button)) {
return true;
}
}
return false;
}
void Mouse::setVisible(bool visible) {
if (visible) {
SDL_ShowCursor();
} else {
SDL_HideCursor();
}
}
bool Mouse::isVisible() const {
return SDL_CursorVisible();
}
void Mouse::setGrabbed(bool grabbed) {
SDL_Window *window = engine_->getWindow();
if (window) {
SDL_SetWindowMouseGrab(window, grabbed);
}
}
bool Mouse::isGrabbed() const {
SDL_Window *window = engine_->getWindow();
if (window) {
return SDL_GetWindowMouseGrab(window);
}
return false;
}
bool Mouse::setRelativeMode(bool relative) {
return SDL_SetWindowRelativeMouseMode(engine_->getWindow(), relative);
}
bool Mouse::getRelativeMode() const {
return SDL_GetWindowRelativeMouseMode(engine_->getWindow());
}
void Mouse::setCursor(Cursor *cursor) {
current_cursor_ = cursor;
if (cursor && cursor->getHandle()) {
SDL_SetCursor(cursor->getHandle());
}
}
void Mouse::setCursor() {
current_cursor_ = nullptr;
SDL_SetCursor(SDL_GetDefaultCursor());
}
bool Mouse::isCursorSupported() const {
// On desktop platforms, cursors are always supported
// On mobile/touch platforms, they may not be
#if defined(__ANDROID__) || defined(__IPHONEOS__)
return false;
#else
return true;
#endif
}
} // namespace modules
} // namespace joy
|
zyedidia/joy
| 1
|
A framework for building 2D desktop games in JavaScript, with a Love2D-inspired API
|
C++
|
zyedidia
|
Zachary Yedidia
|
Stanford University
|
src/modules/mouse/mouse.hh
|
C++ Header
|
#pragma once
#include "SDL3/SDL.h"
namespace js {
class Context;
class Value;
}
namespace joy {
class Engine;
namespace modules {
// System cursor types (matching Love2D CursorType enum)
enum class SystemCursor {
Arrow,
Ibeam,
Wait,
Crosshair,
WaitArrow,
SizeNWSE,
SizeNESW,
SizeWE,
SizeNS,
SizeAll,
No,
Hand,
MaxEnum
};
// Cursor type (system or custom image)
enum class CursorType {
System,
Image,
MaxEnum
};
// Cursor class - represents a hardware cursor
class Cursor {
public:
Cursor();
~Cursor();
// Disable copy
Cursor(const Cursor &) = delete;
Cursor &operator=(const Cursor &) = delete;
// Create from system cursor
bool initSystem(SystemCursor type);
// Create from image data (RGBA pixels)
bool initFromPixels(const unsigned char *data, int width, int height, int hotx, int hoty);
// Get SDL cursor handle
SDL_Cursor *getHandle() const { return cursor_; }
// Get cursor type
CursorType getType() const { return type_; }
// Get system cursor type (only valid if type is System)
SystemCursor getSystemType() const { return system_type_; }
// Convert system cursor name to enum
static bool getSystemCursor(const char *name, SystemCursor &out);
// Convert system cursor enum to name
static const char *getSystemCursorName(SystemCursor cursor);
// Convert cursor type enum to name
static const char *getCursorTypeName(CursorType type);
private:
SDL_Cursor *cursor_;
CursorType type_;
SystemCursor system_type_;
};
// Mouse module
class Mouse {
public:
Mouse(Engine *engine);
~Mouse();
// Position
void getPosition(double &x, double &y) const;
void setPosition(double x, double y);
double getX() const;
double getY() const;
void setX(double x);
void setY(double y);
// Button state
bool isDown(const int *buttons, int count) const;
// Visibility
void setVisible(bool visible);
bool isVisible() const;
// Grab
void setGrabbed(bool grabbed);
bool isGrabbed() const;
// Relative mode
bool setRelativeMode(bool relative);
bool getRelativeMode() const;
// Cursor management
void setCursor(Cursor *cursor);
void setCursor(); // Reset to default
Cursor *getCursor() const { return current_cursor_; }
// Check if cursors are supported
bool isCursorSupported() const;
// JavaScript bindings
static void initJS(js::Context &ctx, js::Value &joy);
private:
Engine *engine_;
Cursor *current_cursor_;
};
} // namespace modules
} // namespace joy
|
zyedidia/joy
| 1
|
A framework for building 2D desktop games in JavaScript, with a Love2D-inspired API
|
C++
|
zyedidia
|
Zachary Yedidia
|
Stanford University
|
src/modules/mouse/mouse_js.cc
|
C++
|
#include "js/js.hh"
#include "mouse.hh"
#include "engine.hh"
namespace joy {
namespace modules {
// Helper to get Mouse module from JS context
static Mouse *getMouse(js::FunctionArgs &args) {
Engine *engine = args.getContextOpaque<Engine>();
return engine ? engine->getMouseModule() : nullptr;
}
// Cursor class ID
static js::ClassID cursor_class_id = 0;
// Cursor finalizer
static void cursor_finalizer(void *opaque) {
Cursor *cursor = static_cast<Cursor *>(opaque);
delete cursor;
}
// Helper to get Cursor from this value
static Cursor *getCursor(js::FunctionArgs &args) {
js::Value thisVal = args.thisValue();
return static_cast<Cursor *>(js::ClassBuilder::getOpaque(thisVal, cursor_class_id));
}
// cursor:getType()
static void js_cursor_getType(js::FunctionArgs &args) {
Cursor *cursor = getCursor(args);
if (!cursor) {
args.returnValue(js::Value::string(args.context(), ""));
return;
}
const char *type_name = Cursor::getCursorTypeName(cursor->getType());
args.returnValue(js::Value::string(args.context(), type_name ? type_name : ""));
}
// joy.mouse.getPosition()
static void js_mouse_getPosition(js::FunctionArgs &args) {
Mouse *mouse = getMouse(args);
if (!mouse) {
args.returnValue(js::Value::number(0));
return;
}
double x, y;
mouse->getPosition(x, y);
js::Value result = js::Value::array(args.context());
result.setProperty(args.context(), 0u, js::Value::number(x));
result.setProperty(args.context(), 1u, js::Value::number(y));
args.returnValue(std::move(result));
}
// joy.mouse.getX()
static void js_mouse_getX(js::FunctionArgs &args) {
Mouse *mouse = getMouse(args);
args.returnValue(js::Value::number(mouse ? mouse->getX() : 0.0));
}
// joy.mouse.getY()
static void js_mouse_getY(js::FunctionArgs &args) {
Mouse *mouse = getMouse(args);
args.returnValue(js::Value::number(mouse ? mouse->getY() : 0.0));
}
// joy.mouse.setPosition(x, y)
static void js_mouse_setPosition(js::FunctionArgs &args) {
Mouse *mouse = getMouse(args);
if (!mouse || args.length() < 2) {
args.returnUndefined();
return;
}
double x = args.arg(0).toFloat64();
double y = args.arg(1).toFloat64();
mouse->setPosition(x, y);
args.returnUndefined();
}
// joy.mouse.setX(x)
static void js_mouse_setX(js::FunctionArgs &args) {
Mouse *mouse = getMouse(args);
if (!mouse || args.length() < 1) {
args.returnUndefined();
return;
}
double x = args.arg(0).toFloat64();
mouse->setX(x);
args.returnUndefined();
}
// joy.mouse.setY(y)
static void js_mouse_setY(js::FunctionArgs &args) {
Mouse *mouse = getMouse(args);
if (!mouse || args.length() < 1) {
args.returnUndefined();
return;
}
double y = args.arg(0).toFloat64();
mouse->setY(y);
args.returnUndefined();
}
// joy.mouse.isDown(button, ...)
static void js_mouse_isDown(js::FunctionArgs &args) {
Mouse *mouse = getMouse(args);
if (!mouse || args.length() < 1) {
args.returnValue(js::Value::boolean(false));
return;
}
// Collect all button arguments
int buttons[16];
int count = args.length();
if (count > 16) count = 16;
for (int i = 0; i < count; i++) {
buttons[i] = args.arg(i).toInt32();
}
bool down = mouse->isDown(buttons, count);
args.returnValue(js::Value::boolean(down));
}
// joy.mouse.setVisible(visible)
static void js_mouse_setVisible(js::FunctionArgs &args) {
Mouse *mouse = getMouse(args);
if (!mouse || args.length() < 1) {
args.returnUndefined();
return;
}
bool visible = args.arg(0).toBool();
mouse->setVisible(visible);
args.returnUndefined();
}
// joy.mouse.isVisible()
static void js_mouse_isVisible(js::FunctionArgs &args) {
Mouse *mouse = getMouse(args);
args.returnValue(js::Value::boolean(mouse ? mouse->isVisible() : true));
}
// joy.mouse.setGrabbed(grabbed)
static void js_mouse_setGrabbed(js::FunctionArgs &args) {
Mouse *mouse = getMouse(args);
if (!mouse || args.length() < 1) {
args.returnUndefined();
return;
}
bool grabbed = args.arg(0).toBool();
mouse->setGrabbed(grabbed);
args.returnUndefined();
}
// joy.mouse.isGrabbed()
static void js_mouse_isGrabbed(js::FunctionArgs &args) {
Mouse *mouse = getMouse(args);
args.returnValue(js::Value::boolean(mouse ? mouse->isGrabbed() : false));
}
// joy.mouse.setRelativeMode(enable)
static void js_mouse_setRelativeMode(js::FunctionArgs &args) {
Mouse *mouse = getMouse(args);
if (!mouse || args.length() < 1) {
args.returnUndefined();
return;
}
bool enable = args.arg(0).toBool();
mouse->setRelativeMode(enable);
args.returnUndefined();
}
// joy.mouse.getRelativeMode()
static void js_mouse_getRelativeMode(js::FunctionArgs &args) {
Mouse *mouse = getMouse(args);
args.returnValue(js::Value::boolean(mouse ? mouse->getRelativeMode() : false));
}
// joy.mouse.setCursor(cursor) or joy.mouse.setCursor()
static void js_mouse_setCursor(js::FunctionArgs &args) {
Mouse *mouse = getMouse(args);
if (!mouse) {
args.returnUndefined();
return;
}
if (args.length() < 1 || args.arg(0).isUndefined() || args.arg(0).isNull()) {
// Reset to default cursor
mouse->setCursor();
} else {
// Set custom cursor
js::Value cursorVal = args.arg(0);
Cursor *cursor = static_cast<Cursor *>(js::ClassBuilder::getOpaque(cursorVal, cursor_class_id));
if (cursor) {
mouse->setCursor(cursor);
}
}
args.returnUndefined();
}
// joy.mouse.getCursor()
static void js_mouse_getCursor(js::FunctionArgs &args) {
Mouse *mouse = getMouse(args);
if (!mouse || !mouse->getCursor()) {
args.returnValue(js::Value::null());
return;
}
// Note: We can't return the current cursor as a JS object without storing it
// For now, return null if we don't have tracking
// A full implementation would need to track the JS cursor object
args.returnValue(js::Value::null());
}
// joy.mouse.isCursorSupported()
static void js_mouse_isCursorSupported(js::FunctionArgs &args) {
Mouse *mouse = getMouse(args);
args.returnValue(js::Value::boolean(mouse ? mouse->isCursorSupported() : false));
}
// joy.mouse.getSystemCursor(type)
static void js_mouse_getSystemCursor(js::FunctionArgs &args) {
if (args.length() < 1) {
args.returnValue(js::Value::null());
return;
}
std::string type_name = args.arg(0).toString(args.context());
SystemCursor system_type;
if (!Cursor::getSystemCursor(type_name.c_str(), system_type)) {
args.returnValue(js::Value::null());
return;
}
Cursor *cursor = new Cursor();
if (!cursor->initSystem(system_type)) {
delete cursor;
args.returnValue(js::Value::null());
return;
}
js::Value obj = js::ClassBuilder::newInstance(args.context(), cursor_class_id);
js::ClassBuilder::setOpaque(obj, cursor);
args.returnValue(std::move(obj));
}
// joy.mouse.newCursor(imageData, hotx, hoty) - simplified version using pixel data
// For now, we'll support creating cursors from ImageData-like objects with width, height, and data
static void js_mouse_newCursor(js::FunctionArgs &args) {
if (args.length() < 1) {
args.returnValue(js::Value::null());
return;
}
js::Value imageData = args.arg(0);
// Try to get width, height, and data properties
js::Value widthVal = imageData.getProperty(args.context(), "width");
js::Value heightVal = imageData.getProperty(args.context(), "height");
js::Value dataVal = imageData.getProperty(args.context(), "data");
if (!widthVal.isNumber() || !heightVal.isNumber()) {
args.returnValue(js::Value::null());
return;
}
int width = widthVal.toInt32();
int height = heightVal.toInt32();
int hotx = 0;
int hoty = 0;
if (args.length() >= 2) {
hotx = args.arg(1).toInt32();
}
if (args.length() >= 3) {
hoty = args.arg(2).toInt32();
}
// Get pixel data from ArrayBuffer or Uint8Array
const unsigned char *pixels = nullptr;
size_t data_len = 0;
if (dataVal.isArrayBuffer()) {
pixels = static_cast<const unsigned char *>(dataVal.arrayBufferData());
data_len = dataVal.arrayBufferLength();
} else if (dataVal.isTypedArray()) {
// For typed arrays, try to get the underlying buffer
js::Value buffer = dataVal.getProperty(args.context(), "buffer");
if (buffer.isArrayBuffer()) {
pixels = static_cast<const unsigned char *>(buffer.arrayBufferData());
data_len = buffer.arrayBufferLength();
}
}
if (!pixels || data_len < static_cast<size_t>(width * height * 4)) {
args.returnValue(js::Value::null());
return;
}
Cursor *cursor = new Cursor();
if (!cursor->initFromPixels(pixels, width, height, hotx, hoty)) {
delete cursor;
args.returnValue(js::Value::null());
return;
}
js::Value obj = js::ClassBuilder::newInstance(args.context(), cursor_class_id);
js::ClassBuilder::setOpaque(obj, cursor);
args.returnValue(std::move(obj));
}
void Mouse::initJS(js::Context &ctx, js::Value &joy) {
// Register Cursor class
js::ClassDef cursorDef;
cursorDef.name = "Cursor";
cursorDef.finalizer = cursor_finalizer;
cursor_class_id = js::ClassBuilder::registerClass(ctx, cursorDef);
// Create Cursor prototype with methods
js::Value proto = js::ModuleBuilder(ctx, "__cursor_proto__")
.function("getType", js_cursor_getType, 0)
.build();
js::ClassBuilder::setPrototype(ctx, cursor_class_id, proto);
// Create mouse namespace
js::ModuleBuilder(ctx, "mouse")
.function("getPosition", js_mouse_getPosition, 0)
.function("getX", js_mouse_getX, 0)
.function("getY", js_mouse_getY, 0)
.function("setPosition", js_mouse_setPosition, 2)
.function("setX", js_mouse_setX, 1)
.function("setY", js_mouse_setY, 1)
.function("isDown", js_mouse_isDown, 1)
.function("setVisible", js_mouse_setVisible, 1)
.function("isVisible", js_mouse_isVisible, 0)
.function("setGrabbed", js_mouse_setGrabbed, 1)
.function("isGrabbed", js_mouse_isGrabbed, 0)
.function("setRelativeMode", js_mouse_setRelativeMode, 1)
.function("getRelativeMode", js_mouse_getRelativeMode, 0)
.function("setCursor", js_mouse_setCursor, 1)
.function("getCursor", js_mouse_getCursor, 0)
.function("isCursorSupported", js_mouse_isCursorSupported, 0)
.function("getSystemCursor", js_mouse_getSystemCursor, 1)
.function("newCursor", js_mouse_newCursor, 3)
.attachTo(joy);
}
} // namespace modules
} // namespace joy
|
zyedidia/joy
| 1
|
A framework for building 2D desktop games in JavaScript, with a Love2D-inspired API
|
C++
|
zyedidia
|
Zachary Yedidia
|
Stanford University
|
src/modules/sound/sound.cc
|
C++
|
#include "sound.hh"
#define STB_VORBIS_HEADER_ONLY
#include "stb_vorbis.c"
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <algorithm>
namespace joy {
namespace modules {
// SoundData implementation
SoundData::SoundData(int sampleCount, int sampleRate, int bitDepth, int channels)
: data_(nullptr)
, sampleCount_(sampleCount)
, sampleRate_(sampleRate)
, bitDepth_(bitDepth)
, channels_(channels)
{
size_t totalSamples = static_cast<size_t>(sampleCount) * channels;
data_ = static_cast<float *>(calloc(totalSamples, sizeof(float)));
}
SoundData::SoundData(float *data, int sampleCount, int sampleRate, int bitDepth, int channels)
: data_(data)
, sampleCount_(sampleCount)
, sampleRate_(sampleRate)
, bitDepth_(bitDepth)
, channels_(channels)
{
}
SoundData::~SoundData() {
if (data_) {
free(data_);
}
}
SoundData *SoundData::clone() const {
size_t totalSamples = static_cast<size_t>(sampleCount_) * channels_;
float *newData = static_cast<float *>(malloc(totalSamples * sizeof(float)));
if (newData) {
memcpy(newData, data_, totalSamples * sizeof(float));
}
return new SoundData(newData, sampleCount_, sampleRate_, bitDepth_, channels_);
}
double SoundData::getDuration() const {
return static_cast<double>(sampleCount_) / static_cast<double>(sampleRate_);
}
float SoundData::getSample(int index) const {
int totalSamples = sampleCount_ * channels_;
if (index < 0 || index >= totalSamples || !data_) {
return 0.0f;
}
return data_[index];
}
void SoundData::setSample(int index, float value) {
int totalSamples = sampleCount_ * channels_;
if (index < 0 || index >= totalSamples || !data_) {
return;
}
// Clamp to valid range
data_[index] = std::clamp(value, -1.0f, 1.0f);
}
float SoundData::getSample(int index, int channel) const {
if (index < 0 || index >= sampleCount_ || channel < 0 || channel >= channels_ || !data_) {
return 0.0f;
}
return data_[index * channels_ + channel];
}
void SoundData::setSample(int index, int channel, float value) {
if (index < 0 || index >= sampleCount_ || channel < 0 || channel >= channels_ || !data_) {
return;
}
// Clamp to valid range
data_[index * channels_ + channel] = std::clamp(value, -1.0f, 1.0f);
}
// Decoder implementation
Decoder::Decoder()
: vorbis_(nullptr)
, channels_(0)
, sampleRate_(0)
, duration_(-1.0)
, bufferSize_(2048)
, finished_(false)
{
}
Decoder::~Decoder() {
if (vorbis_) {
stb_vorbis_close(static_cast<stb_vorbis *>(vorbis_));
}
}
bool Decoder::initFromMemory(const char *data, size_t size, int bufferSize) {
// Store file data for potential cloning
fileData_.assign(data, data + size);
bufferSize_ = bufferSize;
// Open vorbis decoder
int error = 0;
vorbis_ = stb_vorbis_open_memory(
reinterpret_cast<const unsigned char *>(fileData_.data()),
static_cast<int>(fileData_.size()),
&error, nullptr
);
if (!vorbis_) {
fprintf(stderr, "Failed to open audio file for decoding (error %d)\n", error);
return false;
}
stb_vorbis *v = static_cast<stb_vorbis *>(vorbis_);
stb_vorbis_info info = stb_vorbis_get_info(v);
channels_ = info.channels;
sampleRate_ = static_cast<int>(info.sample_rate);
// Calculate duration
int totalSamples = stb_vorbis_stream_length_in_samples(v);
if (totalSamples > 0) {
duration_ = static_cast<double>(totalSamples) / static_cast<double>(sampleRate_);
} else {
duration_ = -1.0;
}
finished_ = false;
return true;
}
Decoder *Decoder::clone() const {
if (fileData_.empty()) {
return nullptr;
}
Decoder *newDecoder = new Decoder();
if (!newDecoder->initFromMemory(fileData_.data(), fileData_.size(), bufferSize_)) {
delete newDecoder;
return nullptr;
}
return newDecoder;
}
SoundData *Decoder::decode() {
if (!vorbis_ || finished_) {
return nullptr;
}
stb_vorbis *v = static_cast<stb_vorbis *>(vorbis_);
// Allocate buffer for decoded samples
int maxSamples = bufferSize_;
float *buffer = static_cast<float *>(malloc(maxSamples * channels_ * sizeof(float)));
if (!buffer) {
return nullptr;
}
// Decode samples
int samplesDecoded = stb_vorbis_get_samples_float_interleaved(
v, channels_, buffer, maxSamples * channels_
);
if (samplesDecoded == 0) {
free(buffer);
finished_ = true;
return nullptr;
}
// If we got fewer samples than requested, we may be at the end
if (samplesDecoded < maxSamples) {
finished_ = true;
}
// Resize buffer to actual size if needed
if (samplesDecoded < maxSamples) {
float *newBuffer = static_cast<float *>(realloc(buffer, samplesDecoded * channels_ * sizeof(float)));
if (newBuffer) {
buffer = newBuffer;
}
}
return new SoundData(buffer, samplesDecoded, sampleRate_, 16, channels_);
}
SoundData *Decoder::decodeAll() {
if (!vorbis_) {
return nullptr;
}
stb_vorbis *v = static_cast<stb_vorbis *>(vorbis_);
// Get total number of samples
int totalSamples = stb_vorbis_stream_length_in_samples(v);
if (totalSamples <= 0) {
// If duration unknown, decode in chunks and combine
std::vector<float> allSamples;
const int chunkSize = 4096;
float *chunk = static_cast<float *>(malloc(chunkSize * channels_ * sizeof(float)));
while (true) {
int decoded = stb_vorbis_get_samples_float_interleaved(
v, channels_, chunk, chunkSize * channels_
);
if (decoded == 0) break;
allSamples.insert(allSamples.end(), chunk, chunk + decoded * channels_);
}
free(chunk);
finished_ = true;
if (allSamples.empty()) {
return nullptr;
}
int sampleCount = static_cast<int>(allSamples.size()) / channels_;
float *data = static_cast<float *>(malloc(allSamples.size() * sizeof(float)));
memcpy(data, allSamples.data(), allSamples.size() * sizeof(float));
return new SoundData(data, sampleCount, sampleRate_, 16, channels_);
}
// Allocate buffer for all samples
float *buffer = static_cast<float *>(malloc(totalSamples * channels_ * sizeof(float)));
if (!buffer) {
return nullptr;
}
// Reset to beginning and decode all
stb_vorbis_seek_start(v);
int decoded = stb_vorbis_get_samples_float_interleaved(
v, channels_, buffer, totalSamples * channels_
);
finished_ = true;
if (decoded <= 0) {
free(buffer);
return nullptr;
}
return new SoundData(buffer, decoded, sampleRate_, 16, channels_);
}
void Decoder::seek(double offset) {
if (!vorbis_) {
return;
}
stb_vorbis *v = static_cast<stb_vorbis *>(vorbis_);
unsigned int sampleOffset = static_cast<unsigned int>(offset * sampleRate_);
stb_vorbis_seek(v, sampleOffset);
finished_ = false;
}
// Sound module implementation
Sound::Sound(Engine *engine)
: engine_(engine)
{
}
Sound::~Sound() {
}
} // namespace modules
} // namespace joy
|
zyedidia/joy
| 1
|
A framework for building 2D desktop games in JavaScript, with a Love2D-inspired API
|
C++
|
zyedidia
|
Zachary Yedidia
|
Stanford University
|
src/modules/sound/sound.hh
|
C++ Header
|
#pragma once
#include <cstddef>
#include <cstdint>
#include <vector>
#include <string>
namespace js {
class Context;
class Value;
}
namespace joy {
class Engine;
namespace modules {
// SoundData - raw audio samples in memory
// Stores decoded audio data that can be played back, manipulated sample-by-sample,
// or used for procedural audio generation.
class SoundData {
public:
// Create empty SoundData with specified parameters
SoundData(int sampleCount, int sampleRate = 44100, int bitDepth = 16, int channels = 2);
// Create SoundData from raw PCM data (takes ownership)
SoundData(float *data, int sampleCount, int sampleRate, int bitDepth, int channels);
~SoundData();
// Disable copy
SoundData(const SoundData &) = delete;
SoundData &operator=(const SoundData &) = delete;
// Clone this SoundData
SoundData *clone() const;
// Metadata
int getBitDepth() const { return bitDepth_; }
int getChannelCount() const { return channels_; }
int getSampleRate() const { return sampleRate_; }
int getSampleCount() const { return sampleCount_; }
double getDuration() const;
// Sample access (interleaved mode - index across all channels)
// Sample values are normalized to -1.0 to 1.0
float getSample(int index) const;
void setSample(int index, float value);
// Sample access (separate channel mode)
// index is sample position, channel is 0 or 1
float getSample(int index, int channel) const;
void setSample(int index, int channel, float value);
// Raw data access (for audio playback)
const float *getData() const { return data_; }
float *getData() { return data_; }
size_t getDataSize() const { return static_cast<size_t>(sampleCount_ * channels_) * sizeof(float); }
int getTotalSamples() const { return sampleCount_ * channels_; }
private:
float *data_; // PCM data in float format (interleaved)
int sampleCount_; // Number of samples per channel
int sampleRate_; // Samples per second
int bitDepth_; // 8 or 16 (for API compatibility, internally we use float)
int channels_; // 1 = mono, 2 = stereo
};
// Decoder - gradual audio decoding for streaming
// Decodes audio files chunk by chunk to avoid loading entire files into memory
class Decoder {
public:
Decoder();
~Decoder();
// Disable copy
Decoder(const Decoder &) = delete;
Decoder &operator=(const Decoder &) = delete;
// Initialize from file data (memory buffer)
bool initFromMemory(const char *data, size_t size, int bufferSize = 2048);
// Clone this decoder (resets to beginning)
Decoder *clone() const;
// Decode next chunk and return as SoundData
// Returns nullptr when EOF is reached
SoundData *decode();
// Decode entire file and return as SoundData
SoundData *decodeAll();
// Metadata
int getBitDepth() const { return 16; } // We always decode to 16-bit equivalent float
int getChannelCount() const { return channels_; }
int getSampleRate() const { return sampleRate_; }
double getDuration() const { return duration_; }
// Seeking
void seek(double offset);
// Check if at end of stream
bool isFinished() const { return finished_; }
private:
// Vorbis decoder handle (using stb_vorbis)
void *vorbis_;
// File data (kept for cloning)
std::vector<char> fileData_;
// Audio parameters
int channels_;
int sampleRate_;
double duration_;
int bufferSize_; // Size of each decoded chunk in samples
// State
bool finished_;
};
// Sound module - provides functions to create Decoders and SoundData
class Sound {
public:
Sound(Engine *engine);
~Sound();
// JavaScript bindings
static void initJS(js::Context &ctx, js::Value &joy);
private:
Engine *engine_;
};
} // namespace modules
} // namespace joy
|
zyedidia/joy
| 1
|
A framework for building 2D desktop games in JavaScript, with a Love2D-inspired API
|
C++
|
zyedidia
|
Zachary Yedidia
|
Stanford University
|
src/modules/sound/sound_js.cc
|
C++
|
#include "js/js.hh"
#include "sound.hh"
#include "engine.hh"
#include "physfs.h"
#include <cstdlib>
namespace joy {
namespace modules {
// Class IDs for SoundData and Decoder
static js::ClassID sounddata_class_id = 0;
static js::ClassID decoder_class_id = 0;
// Finalizers
static void sounddata_finalizer(void *opaque) {
SoundData *sd = static_cast<SoundData *>(opaque);
delete sd;
}
static void decoder_finalizer(void *opaque) {
Decoder *dec = static_cast<Decoder *>(opaque);
delete dec;
}
// Helper to get SoundData from this value
static SoundData *getSoundData(js::FunctionArgs &args) {
js::Value thisVal = args.thisValue();
return static_cast<SoundData *>(js::ClassBuilder::getOpaque(thisVal, sounddata_class_id));
}
// Helper to get Decoder from this value
static Decoder *getDecoder(js::FunctionArgs &args) {
js::Value thisVal = args.thisValue();
return static_cast<Decoder *>(js::ClassBuilder::getOpaque(thisVal, decoder_class_id));
}
// Helper to create a JS SoundData object
static js::Value wrapSoundData(js::Context &ctx, SoundData *sd) {
js::Value obj = js::ClassBuilder::newInstance(ctx, sounddata_class_id);
js::ClassBuilder::setOpaque(obj, sd);
return obj;
}
// Helper to create a JS Decoder object
static js::Value wrapDecoder(js::Context &ctx, Decoder *dec) {
js::Value obj = js::ClassBuilder::newInstance(ctx, decoder_class_id);
js::ClassBuilder::setOpaque(obj, dec);
return obj;
}
// SoundData methods
static void js_sounddata_getBitDepth(js::FunctionArgs &args) {
SoundData *sd = getSoundData(args);
args.returnValue(js::Value::number(sd ? sd->getBitDepth() : 0));
}
static void js_sounddata_getChannelCount(js::FunctionArgs &args) {
SoundData *sd = getSoundData(args);
args.returnValue(js::Value::number(sd ? sd->getChannelCount() : 0));
}
static void js_sounddata_getDuration(js::FunctionArgs &args) {
SoundData *sd = getSoundData(args);
args.returnValue(js::Value::number(sd ? sd->getDuration() : 0.0));
}
static void js_sounddata_getSampleCount(js::FunctionArgs &args) {
SoundData *sd = getSoundData(args);
args.returnValue(js::Value::number(sd ? sd->getSampleCount() : 0));
}
static void js_sounddata_getSampleRate(js::FunctionArgs &args) {
SoundData *sd = getSoundData(args);
args.returnValue(js::Value::number(sd ? sd->getSampleRate() : 0));
}
static void js_sounddata_getSample(js::FunctionArgs &args) {
SoundData *sd = getSoundData(args);
if (!sd || args.length() < 1) {
args.returnValue(js::Value::number(0.0));
return;
}
int index = args.arg(0).toInt32();
if (args.length() >= 2) {
// Two-argument version: getSample(index, channel)
int channel = args.arg(1).toInt32();
args.returnValue(js::Value::number(sd->getSample(index, channel)));
} else {
// One-argument version: getSample(index) - interleaved
args.returnValue(js::Value::number(sd->getSample(index)));
}
}
static void js_sounddata_setSample(js::FunctionArgs &args) {
SoundData *sd = getSoundData(args);
if (!sd || args.length() < 2) {
args.returnUndefined();
return;
}
int index = args.arg(0).toInt32();
if (args.length() >= 3) {
// Three-argument version: setSample(index, channel, value)
int channel = args.arg(1).toInt32();
float value = static_cast<float>(args.arg(2).toFloat64());
sd->setSample(index, channel, value);
} else {
// Two-argument version: setSample(index, value) - interleaved
float value = static_cast<float>(args.arg(1).toFloat64());
sd->setSample(index, value);
}
args.returnUndefined();
}
static void js_sounddata_clone(js::FunctionArgs &args) {
SoundData *sd = getSoundData(args);
if (!sd) {
args.returnValue(js::Value::null());
return;
}
SoundData *cloned = sd->clone();
if (!cloned) {
args.returnValue(js::Value::null());
return;
}
args.returnValue(wrapSoundData(args.context(), cloned));
}
// Decoder methods
static void js_decoder_getBitDepth(js::FunctionArgs &args) {
Decoder *dec = getDecoder(args);
args.returnValue(js::Value::number(dec ? dec->getBitDepth() : 0));
}
static void js_decoder_getChannelCount(js::FunctionArgs &args) {
Decoder *dec = getDecoder(args);
args.returnValue(js::Value::number(dec ? dec->getChannelCount() : 0));
}
static void js_decoder_getDuration(js::FunctionArgs &args) {
Decoder *dec = getDecoder(args);
args.returnValue(js::Value::number(dec ? dec->getDuration() : -1.0));
}
static void js_decoder_getSampleRate(js::FunctionArgs &args) {
Decoder *dec = getDecoder(args);
args.returnValue(js::Value::number(dec ? dec->getSampleRate() : 0));
}
static void js_decoder_seek(js::FunctionArgs &args) {
Decoder *dec = getDecoder(args);
if (dec && args.length() >= 1) {
double offset = args.arg(0).toFloat64();
dec->seek(offset);
}
args.returnUndefined();
}
static void js_decoder_decode(js::FunctionArgs &args) {
Decoder *dec = getDecoder(args);
if (!dec) {
args.returnValue(js::Value::null());
return;
}
SoundData *sd = dec->decode();
if (!sd) {
args.returnValue(js::Value::null());
return;
}
args.returnValue(wrapSoundData(args.context(), sd));
}
static void js_decoder_clone(js::FunctionArgs &args) {
Decoder *dec = getDecoder(args);
if (!dec) {
args.returnValue(js::Value::null());
return;
}
Decoder *cloned = dec->clone();
if (!cloned) {
args.returnValue(js::Value::null());
return;
}
args.returnValue(wrapDecoder(args.context(), cloned));
}
// Module functions
// Helper to read file via PhysFS
static char *readPhysfsFile(const char *filename, size_t *size) {
PHYSFS_File *file = PHYSFS_openRead(filename);
if (!file) {
return nullptr;
}
PHYSFS_sint64 fileSize = PHYSFS_fileLength(file);
if (fileSize < 0) {
PHYSFS_close(file);
return nullptr;
}
char *data = static_cast<char *>(malloc(fileSize));
if (!data) {
PHYSFS_close(file);
return nullptr;
}
PHYSFS_sint64 bytesRead = PHYSFS_readBytes(file, data, fileSize);
PHYSFS_close(file);
if (bytesRead != fileSize) {
free(data);
return nullptr;
}
*size = static_cast<size_t>(fileSize);
return data;
}
// joy.sound.newDecoder(filename, bufferSize?)
static void js_sound_newDecoder(js::FunctionArgs &args) {
if (args.length() < 1) {
args.returnValue(js::Value::null());
return;
}
std::string filename = args.arg(0).toString(args.context());
int bufferSize = 2048;
if (args.length() >= 2) {
bufferSize = args.arg(1).toInt32();
if (bufferSize <= 0) bufferSize = 2048;
}
// Read file
size_t fileSize;
char *fileData = readPhysfsFile(filename.c_str(), &fileSize);
if (!fileData) {
args.returnValue(js::Value::null());
return;
}
// Create decoder
Decoder *dec = new Decoder();
if (!dec->initFromMemory(fileData, fileSize, bufferSize)) {
free(fileData);
delete dec;
args.returnValue(js::Value::null());
return;
}
free(fileData);
args.returnValue(wrapDecoder(args.context(), dec));
}
// joy.sound.newSoundData(filename) or
// joy.sound.newSoundData(samples, rate?, bits?, channels?) or
// joy.sound.newSoundData(decoder)
static void js_sound_newSoundData(js::FunctionArgs &args) {
if (args.length() < 1) {
args.returnValue(js::Value::null());
return;
}
js::Value arg0 = args.arg(0);
// Check if first argument is a string (filename)
if (arg0.isString()) {
std::string filename = arg0.toString(args.context());
// Read and decode file
size_t fileSize;
char *fileData = readPhysfsFile(filename.c_str(), &fileSize);
if (!fileData) {
args.returnValue(js::Value::null());
return;
}
Decoder dec;
if (!dec.initFromMemory(fileData, fileSize)) {
free(fileData);
args.returnValue(js::Value::null());
return;
}
free(fileData);
SoundData *sd = dec.decodeAll();
if (!sd) {
args.returnValue(js::Value::null());
return;
}
args.returnValue(wrapSoundData(args.context(), sd));
return;
}
// Check if first argument is a number (custom SoundData creation)
if (arg0.isNumber()) {
int samples = arg0.toInt32();
int rate = 44100;
int bits = 16;
int channels = 2;
if (args.length() >= 2) rate = args.arg(1).toInt32();
if (args.length() >= 3) bits = args.arg(2).toInt32();
if (args.length() >= 4) channels = args.arg(3).toInt32();
// Validate parameters
if (samples <= 0) samples = 1;
if (rate <= 0) rate = 44100;
if (bits != 8 && bits != 16) bits = 16;
if (channels != 1 && channels != 2) channels = 2;
SoundData *sd = new SoundData(samples, rate, bits, channels);
args.returnValue(wrapSoundData(args.context(), sd));
return;
}
// Check if first argument is a Decoder object
if (arg0.isObject()) {
Decoder *dec = static_cast<Decoder *>(js::ClassBuilder::getOpaque(arg0, decoder_class_id));
if (dec) {
SoundData *sd = dec->decodeAll();
if (!sd) {
args.returnValue(js::Value::null());
return;
}
args.returnValue(wrapSoundData(args.context(), sd));
return;
}
}
args.returnValue(js::Value::null());
}
void Sound::initJS(js::Context &ctx, js::Value &joy) {
// Register SoundData class
js::ClassDef sounddataDef;
sounddataDef.name = "SoundData";
sounddataDef.finalizer = sounddata_finalizer;
sounddata_class_id = js::ClassBuilder::registerClass(ctx, sounddataDef);
// Create SoundData prototype
js::Value sounddataProto = js::ModuleBuilder(ctx, "__sounddata_proto__")
.function("getBitDepth", js_sounddata_getBitDepth, 0)
.function("getChannelCount", js_sounddata_getChannelCount, 0)
.function("getDuration", js_sounddata_getDuration, 0)
.function("getSampleCount", js_sounddata_getSampleCount, 0)
.function("getSampleRate", js_sounddata_getSampleRate, 0)
.function("getSample", js_sounddata_getSample, 2)
.function("setSample", js_sounddata_setSample, 3)
.function("clone", js_sounddata_clone, 0)
.build();
js::ClassBuilder::setPrototype(ctx, sounddata_class_id, sounddataProto);
// Register Decoder class
js::ClassDef decoderDef;
decoderDef.name = "Decoder";
decoderDef.finalizer = decoder_finalizer;
decoder_class_id = js::ClassBuilder::registerClass(ctx, decoderDef);
// Create Decoder prototype
js::Value decoderProto = js::ModuleBuilder(ctx, "__decoder_proto__")
.function("getBitDepth", js_decoder_getBitDepth, 0)
.function("getChannelCount", js_decoder_getChannelCount, 0)
.function("getDuration", js_decoder_getDuration, 0)
.function("getSampleRate", js_decoder_getSampleRate, 0)
.function("seek", js_decoder_seek, 1)
.function("decode", js_decoder_decode, 0)
.function("clone", js_decoder_clone, 0)
.build();
js::ClassBuilder::setPrototype(ctx, decoder_class_id, decoderProto);
// Create sound namespace
js::ModuleBuilder(ctx, "sound")
.function("newDecoder", js_sound_newDecoder, 2)
.function("newSoundData", js_sound_newSoundData, 4)
.attachTo(joy);
}
// Export class ID getters for use by audio module
js::ClassID getSoundDataClassID() {
return sounddata_class_id;
}
} // namespace modules
} // namespace joy
|
zyedidia/joy
| 1
|
A framework for building 2D desktop games in JavaScript, with a Love2D-inspired API
|
C++
|
zyedidia
|
Zachary Yedidia
|
Stanford University
|
src/modules/system/system.cc
|
C++
|
#include "system.hh"
#include "engine.hh"
#include <SDL3/SDL.h>
namespace joy {
namespace modules {
System::System(Engine *engine)
: engine_(engine)
{
}
System::~System() {
}
const char *System::getOS() {
#if defined(__APPLE__)
#if TARGET_OS_IOS
return "iOS";
#else
return "OS X";
#endif
#elif defined(_WIN32)
return "Windows";
#elif defined(__ANDROID__)
return "Android";
#elif defined(__linux__)
return "Linux";
#elif defined(__EMSCRIPTEN__)
return "Web";
#else
return "Unknown";
#endif
}
int System::getProcessorCount() {
return SDL_GetNumLogicalCPUCores();
}
std::string System::getClipboardText() const {
char *text = SDL_GetClipboardText();
if (text) {
std::string result(text);
SDL_free(text);
return result;
}
return "";
}
void System::setClipboardText(const char *text) const {
SDL_SetClipboardText(text);
}
System::PowerState System::getPowerInfo(int *seconds, int *percent) const {
SDL_PowerState sdlState = SDL_GetPowerInfo(seconds, percent);
switch (sdlState) {
case SDL_POWERSTATE_ON_BATTERY:
return POWER_BATTERY;
case SDL_POWERSTATE_NO_BATTERY:
return POWER_NO_BATTERY;
case SDL_POWERSTATE_CHARGING:
return POWER_CHARGING;
case SDL_POWERSTATE_CHARGED:
return POWER_CHARGED;
default:
return POWER_UNKNOWN;
}
}
const char *System::getPowerStateName(PowerState state) {
switch (state) {
case POWER_BATTERY:
return "battery";
case POWER_NO_BATTERY:
return "nobattery";
case POWER_CHARGING:
return "charging";
case POWER_CHARGED:
return "charged";
default:
return "unknown";
}
}
bool System::openURL(const char *url) const {
return SDL_OpenURL(url);
}
std::vector<std::string> System::getPreferredLocales() const {
std::vector<std::string> result;
int count = 0;
SDL_Locale **locales = SDL_GetPreferredLocales(&count);
if (locales) {
for (int i = 0; i < count; i++) {
SDL_Locale *locale = locales[i];
if (locale->country) {
result.push_back(std::string(locale->language) + "_" + std::string(locale->country));
} else {
result.push_back(locale->language);
}
}
SDL_free(locales);
}
return result;
}
} // namespace modules
} // namespace joy
|
zyedidia/joy
| 1
|
A framework for building 2D desktop games in JavaScript, with a Love2D-inspired API
|
C++
|
zyedidia
|
Zachary Yedidia
|
Stanford University
|
src/modules/system/system.hh
|
C++ Header
|
#pragma once
#include <string>
#include <vector>
namespace js {
class Context;
class Value;
}
namespace joy {
class Engine;
namespace modules {
class System {
public:
enum PowerState {
POWER_UNKNOWN,
POWER_BATTERY,
POWER_NO_BATTERY,
POWER_CHARGING,
POWER_CHARGED
};
System(Engine *engine);
~System();
// Get current operating system
static const char *getOS();
// Get number of logical processor cores
static int getProcessorCount();
// Clipboard
std::string getClipboardText() const;
void setClipboardText(const char *text) const;
// Power info
PowerState getPowerInfo(int *seconds, int *percent) const;
static const char *getPowerStateName(PowerState state);
// Open URL in default browser
bool openURL(const char *url) const;
// Get preferred locales
std::vector<std::string> getPreferredLocales() const;
// Initialize JS bindings
static void initJS(js::Context &ctx, js::Value &joy);
private:
Engine *engine_;
};
} // namespace modules
} // namespace joy
|
zyedidia/joy
| 1
|
A framework for building 2D desktop games in JavaScript, with a Love2D-inspired API
|
C++
|
zyedidia
|
Zachary Yedidia
|
Stanford University
|
src/modules/system/system_js.cc
|
C++
|
#include "system.hh"
#include "js/js.hh"
#include "engine.hh"
namespace joy {
namespace modules {
static System *getSystem(js::FunctionArgs &args) {
Engine *engine = args.getContextOpaque<Engine>();
return engine ? engine->getSystemModule() : nullptr;
}
static void js_system_getOS(js::FunctionArgs &args) {
args.returnValue(js::Value::string(args.context(), System::getOS()));
}
static void js_system_getProcessorCount(js::FunctionArgs &args) {
args.returnValue(js::Value::number(System::getProcessorCount()));
}
static void js_system_getClipboardText(js::FunctionArgs &args) {
System *sys = getSystem(args);
if (!sys) {
args.returnValue(js::Value::string(args.context(), ""));
return;
}
std::string text = sys->getClipboardText();
args.returnValue(js::Value::string(args.context(), text.c_str()));
}
static void js_system_setClipboardText(js::FunctionArgs &args) {
System *sys = getSystem(args);
if (!sys) {
args.returnUndefined();
return;
}
if (args.length() < 1) {
args.returnUndefined();
return;
}
std::string text = args.arg(0).toString(args.context());
sys->setClipboardText(text.c_str());
args.returnUndefined();
}
static void js_system_getPowerInfo(js::FunctionArgs &args) {
System *sys = getSystem(args);
if (!sys) {
// Return unknown state with nil values
js::Context &ctx = args.context();
js::Value state = js::Value::string(ctx, "unknown");
js::Value percent = js::Value::null();
js::Value seconds = js::Value::null();
js::Value result = js::Value::array(ctx);
result.setProperty(ctx, 0u, state);
result.setProperty(ctx, 1u, percent);
result.setProperty(ctx, 2u, seconds);
args.returnValue(std::move(result));
return;
}
int secs = -1;
int pct = -1;
System::PowerState powerState = sys->getPowerInfo(&secs, &pct);
js::Context &ctx = args.context();
js::Value state = js::Value::string(ctx, System::getPowerStateName(powerState));
// Return nil for unknown values (-1)
js::Value percent = (pct >= 0) ? js::Value::number(pct) : js::Value::null();
js::Value seconds = (secs >= 0) ? js::Value::number(secs) : js::Value::null();
// Return as array [state, percent, seconds] to match Love2D's multiple return values
js::Value result = js::Value::array(ctx);
result.setProperty(ctx, 0u, state);
result.setProperty(ctx, 1u, percent);
result.setProperty(ctx, 2u, seconds);
args.returnValue(std::move(result));
}
static void js_system_openURL(js::FunctionArgs &args) {
System *sys = getSystem(args);
if (!sys || args.length() < 1) {
args.returnValue(js::Value::boolean(false));
return;
}
std::string url = args.arg(0).toString(args.context());
bool success = sys->openURL(url.c_str());
args.returnValue(js::Value::boolean(success));
}
static void js_system_getPreferredLocales(js::FunctionArgs &args) {
System *sys = getSystem(args);
js::Context &ctx = args.context();
if (!sys) {
args.returnValue(js::Value::array(ctx));
return;
}
std::vector<std::string> locales = sys->getPreferredLocales();
js::Value result = js::Value::array(ctx);
for (size_t i = 0; i < locales.size(); i++) {
result.setProperty(ctx, static_cast<uint32_t>(i), js::Value::string(ctx, locales[i].c_str()));
}
args.returnValue(std::move(result));
}
void System::initJS(js::Context &ctx, js::Value &joy) {
js::ModuleBuilder(ctx, "system")
.function("getOS", js_system_getOS)
.function("getProcessorCount", js_system_getProcessorCount)
.function("getClipboardText", js_system_getClipboardText)
.function("setClipboardText", js_system_setClipboardText, 1)
.function("getPowerInfo", js_system_getPowerInfo)
.function("openURL", js_system_openURL, 1)
.function("getPreferredLocales", js_system_getPreferredLocales)
.attachTo(joy);
}
} // namespace modules
} // namespace joy
|
zyedidia/joy
| 1
|
A framework for building 2D desktop games in JavaScript, with a Love2D-inspired API
|
C++
|
zyedidia
|
Zachary Yedidia
|
Stanford University
|
src/modules/timer/timer.cc
|
C++
|
#include "timer.hh"
#include "SDL3/SDL.h"
namespace joy {
namespace modules {
// Static helper to get high-precision time
static double getTimeAbsolute() {
static Uint64 freq = SDL_GetPerformanceFrequency();
Uint64 counter = SDL_GetPerformanceCounter();
return (double)counter / (double)freq;
}
Timer::Timer()
: currTime_(0)
, prevTime_(0)
, prevFpsUpdate_(0)
, fps_(0)
, averageDelta_(0)
, fpsUpdateFrequency_(1.0)
, frames_(0)
, dt_(0) {
prevFpsUpdate_ = currTime_ = getTimeAbsolute();
}
Timer::~Timer() {
}
double Timer::step() {
frames_++;
prevTime_ = currTime_;
currTime_ = getTimeAbsolute();
dt_ = currTime_ - prevTime_;
double timeSinceLast = currTime_ - prevFpsUpdate_;
if (timeSinceLast > fpsUpdateFrequency_) {
fps_ = (int)((frames_ / timeSinceLast) + 0.5);
averageDelta_ = timeSinceLast / frames_;
prevFpsUpdate_ = currTime_;
frames_ = 0;
}
return dt_;
}
void Timer::sleep(double seconds) const {
if (seconds >= 0) {
SDL_Delay((Uint32)(seconds * 1000));
}
}
double Timer::getDelta() const {
return dt_;
}
int Timer::getFPS() const {
return fps_;
}
double Timer::getAverageDelta() const {
return averageDelta_;
}
double Timer::getTime() {
static double startTime = getTimeAbsolute();
return getTimeAbsolute() - startTime;
}
} // namespace modules
} // namespace joy
|
zyedidia/joy
| 1
|
A framework for building 2D desktop games in JavaScript, with a Love2D-inspired API
|
C++
|
zyedidia
|
Zachary Yedidia
|
Stanford University
|
src/modules/timer/timer.hh
|
C++ Header
|
#pragma once
namespace js {
class Context;
class Value;
} // namespace js
namespace joy {
namespace modules {
class Timer {
public:
Timer();
~Timer();
// Measures time between frames, updates internal values
double step();
// Sleeps for the specified number of seconds
void sleep(double seconds) const;
// Gets the time between the last two frames
double getDelta() const;
// Gets the average FPS over the last second
int getFPS() const;
// Gets the average delta time over the last second
double getAverageDelta() const;
// Gets time since module initialization
static double getTime();
// Initialize JS bindings
static void initJS(js::Context &ctx, js::Value &joy);
private:
double currTime_;
double prevTime_;
double prevFpsUpdate_;
int fps_;
double averageDelta_;
double fpsUpdateFrequency_;
int frames_;
double dt_;
};
} // namespace modules
} // namespace joy
|
zyedidia/joy
| 1
|
A framework for building 2D desktop games in JavaScript, with a Love2D-inspired API
|
C++
|
zyedidia
|
Zachary Yedidia
|
Stanford University
|
src/modules/timer/timer_js.cc
|
C++
|
#include "timer.hh"
#include "js/js.hh"
#include "engine.hh"
namespace joy {
namespace modules {
static Timer *getTimer(js::FunctionArgs &args) {
Engine *engine = args.getContextOpaque<Engine>();
return engine ? engine->getTimerModule() : nullptr;
}
static void js_timer_step(js::FunctionArgs &args) {
Timer *timer = getTimer(args);
if (!timer) {
args.returnValue(js::Value::number(0));
return;
}
args.returnValue(js::Value::number(timer->step()));
}
static void js_timer_sleep(js::FunctionArgs &args) {
Timer *timer = getTimer(args);
if (!timer || args.length() < 1) {
args.returnUndefined();
return;
}
double seconds = args.arg(0).toFloat64();
timer->sleep(seconds);
args.returnUndefined();
}
static void js_timer_getDelta(js::FunctionArgs &args) {
Timer *timer = getTimer(args);
if (!timer) {
args.returnValue(js::Value::number(0));
return;
}
args.returnValue(js::Value::number(timer->getDelta()));
}
static void js_timer_getFPS(js::FunctionArgs &args) {
Timer *timer = getTimer(args);
if (!timer) {
args.returnValue(js::Value::number(0));
return;
}
args.returnValue(js::Value::number(timer->getFPS()));
}
static void js_timer_getAverageDelta(js::FunctionArgs &args) {
Timer *timer = getTimer(args);
if (!timer) {
args.returnValue(js::Value::number(0));
return;
}
args.returnValue(js::Value::number(timer->getAverageDelta()));
}
static void js_timer_getTime(js::FunctionArgs &args) {
args.returnValue(js::Value::number(Timer::getTime()));
}
void Timer::initJS(js::Context &ctx, js::Value &joy) {
js::ModuleBuilder(ctx, "timer")
.function("step", js_timer_step, 0)
.function("sleep", js_timer_sleep, 1)
.function("getDelta", js_timer_getDelta, 0)
.function("getFPS", js_timer_getFPS, 0)
.function("getAverageDelta", js_timer_getAverageDelta, 0)
.function("getTime", js_timer_getTime, 0)
.attachTo(joy);
}
} // namespace modules
} // namespace joy
|
zyedidia/joy
| 1
|
A framework for building 2D desktop games in JavaScript, with a Love2D-inspired API
|
C++
|
zyedidia
|
Zachary Yedidia
|
Stanford University
|
src/modules/window/window.cc
|
C++
|
#include "window.hh"
#include "engine.hh"
#include <cstdlib>
#include <cstring>
namespace joy {
namespace modules {
Window::Window(Engine *engine)
: engine_(engine)
{
}
Window::~Window() {
}
bool Window::setMode(int width, int height, bool fullscreen, bool resizable, bool borderless, int minwidth, int minheight) {
SDL_Window *window = engine_->getWindow();
if (!window) {
return false;
}
SDL_SetWindowSize(window, width, height);
SDL_SetWindowMinimumSize(window, minwidth, minheight);
SDL_SetWindowResizable(window, resizable);
SDL_SetWindowBordered(window, !borderless);
SDL_SetWindowFullscreen(window, fullscreen);
return true;
}
void Window::getMode(int *width, int *height, bool *fullscreen, bool *resizable, bool *borderless) {
SDL_Window *window = engine_->getWindow();
if (!window) {
*width = 0;
*height = 0;
*fullscreen = false;
*resizable = false;
*borderless = false;
return;
}
SDL_GetWindowSize(window, width, height);
SDL_WindowFlags flags = SDL_GetWindowFlags(window);
*fullscreen = (flags & SDL_WINDOW_FULLSCREEN) != 0;
*resizable = (flags & SDL_WINDOW_RESIZABLE) != 0;
*borderless = (flags & SDL_WINDOW_BORDERLESS) != 0;
}
int Window::getWidth() {
SDL_Window *window = engine_->getWindow();
if (!window) return 0;
int w, h;
SDL_GetWindowSize(window, &w, &h);
return w;
}
int Window::getHeight() {
SDL_Window *window = engine_->getWindow();
if (!window) return 0;
int w, h;
SDL_GetWindowSize(window, &w, &h);
return h;
}
void Window::setTitle(const char *title) {
SDL_Window *window = engine_->getWindow();
if (window) {
SDL_SetWindowTitle(window, title);
}
}
const char *Window::getTitle() {
SDL_Window *window = engine_->getWindow();
if (!window) {
return "";
}
const char *title = SDL_GetWindowTitle(window);
return title ? title : "";
}
void Window::setFullscreen(bool fullscreen) {
SDL_Window *window = engine_->getWindow();
if (window) {
SDL_SetWindowFullscreen(window, fullscreen);
}
}
bool Window::getFullscreen() {
SDL_Window *window = engine_->getWindow();
if (!window) {
return false;
}
SDL_WindowFlags flags = SDL_GetWindowFlags(window);
return (flags & SDL_WINDOW_FULLSCREEN) != 0;
}
bool Window::isOpen() {
return engine_->getWindow() != nullptr;
}
void Window::close() {
engine_->stop();
}
void Window::setPosition(int x, int y) {
SDL_Window *window = engine_->getWindow();
if (window) {
SDL_SetWindowPosition(window, x, y);
}
}
void Window::getPosition(int *x, int *y) {
SDL_Window *window = engine_->getWindow();
if (!window) {
*x = 0;
*y = 0;
return;
}
SDL_GetWindowPosition(window, x, y);
}
float Window::getDPIScale() {
SDL_Window *window = engine_->getWindow();
if (!window) {
return 1.0f;
}
return SDL_GetWindowDisplayScale(window);
}
void Window::minimize() {
SDL_Window *window = engine_->getWindow();
if (window) {
SDL_MinimizeWindow(window);
}
}
void Window::maximize() {
SDL_Window *window = engine_->getWindow();
if (window) {
SDL_MaximizeWindow(window);
}
}
void Window::restore() {
SDL_Window *window = engine_->getWindow();
if (window) {
SDL_RestoreWindow(window);
}
}
bool Window::isMaximized() {
SDL_Window *window = engine_->getWindow();
if (!window) {
return false;
}
SDL_WindowFlags flags = SDL_GetWindowFlags(window);
return (flags & SDL_WINDOW_MAXIMIZED) != 0;
}
bool Window::isMinimized() {
SDL_Window *window = engine_->getWindow();
if (!window) {
return false;
}
SDL_WindowFlags flags = SDL_GetWindowFlags(window);
return (flags & SDL_WINDOW_MINIMIZED) != 0;
}
bool Window::isVisible() {
SDL_Window *window = engine_->getWindow();
if (!window) {
return false;
}
SDL_WindowFlags flags = SDL_GetWindowFlags(window);
return (flags & SDL_WINDOW_HIDDEN) == 0;
}
bool Window::hasFocus() {
SDL_Window *window = engine_->getWindow();
if (!window) {
return false;
}
SDL_WindowFlags flags = SDL_GetWindowFlags(window);
return (flags & SDL_WINDOW_INPUT_FOCUS) != 0;
}
int Window::getDisplayCount() {
int count = 0;
SDL_DisplayID *displays = SDL_GetDisplays(&count);
SDL_free(displays);
return count;
}
void Window::getDesktopDimensions(int displayindex, int *width, int *height) {
int count = 0;
SDL_DisplayID *displays = SDL_GetDisplays(&count);
if (!displays || displayindex >= count) {
*width = 0;
*height = 0;
SDL_free(displays);
return;
}
SDL_DisplayID display = displays[displayindex];
SDL_free(displays);
const SDL_DisplayMode *mode = SDL_GetCurrentDisplayMode(display);
if (mode) {
*width = mode->w;
*height = mode->h;
} else {
*width = 0;
*height = 0;
}
}
const char *Window::getDisplayName(int displayindex) {
int count = 0;
SDL_DisplayID *displays = SDL_GetDisplays(&count);
if (!displays || displayindex >= count) {
SDL_free(displays);
return "";
}
SDL_DisplayID display = displays[displayindex];
SDL_free(displays);
const char *name = SDL_GetDisplayName(display);
return name ? name : "";
}
bool Window::hasMouseFocus() {
SDL_Window *window = engine_->getWindow();
if (!window) {
return false;
}
SDL_WindowFlags flags = SDL_GetWindowFlags(window);
return (flags & SDL_WINDOW_MOUSE_FOCUS) != 0;
}
float Window::fromPixels(float pixelvalue) {
float scale = getDPIScale();
return scale > 0 ? pixelvalue / scale : pixelvalue;
}
void Window::fromPixels(float px, float py, float *x, float *y) {
float scale = getDPIScale();
if (scale > 0) {
*x = px / scale;
*y = py / scale;
} else {
*x = px;
*y = py;
}
}
float Window::toPixels(float value) {
float scale = getDPIScale();
return value * scale;
}
void Window::toPixels(float x, float y, float *px, float *py) {
float scale = getDPIScale();
*px = x * scale;
*py = y * scale;
}
bool Window::isDisplaySleepEnabled() {
return SDL_ScreenSaverEnabled();
}
void Window::setDisplaySleepEnabled(bool enable) {
if (enable) {
SDL_EnableScreenSaver();
} else {
SDL_DisableScreenSaver();
}
}
void Window::requestAttention(bool continuous) {
SDL_Window *window = engine_->getWindow();
if (window) {
SDL_FlashWindow(window, continuous ? SDL_FLASH_UNTIL_FOCUSED : SDL_FLASH_BRIEFLY);
}
}
void Window::getSafeArea(int *x, int *y, int *w, int *h) {
SDL_Window *window = engine_->getWindow();
if (!window) {
*x = 0;
*y = 0;
*w = 0;
*h = 0;
return;
}
SDL_DisplayID display = SDL_GetDisplayForWindow(window);
SDL_Rect rect;
if (SDL_GetDisplayUsableBounds(display, &rect)) {
*x = rect.x;
*y = rect.y;
*w = rect.w;
*h = rect.h;
} else {
// Fallback to window size
int ww, wh;
SDL_GetWindowSize(window, &ww, &wh);
*x = 0;
*y = 0;
*w = ww;
*h = wh;
}
}
const char *Window::getDisplayOrientation(int displayindex) {
int count = 0;
SDL_DisplayID *displays = SDL_GetDisplays(&count);
if (!displays || displayindex >= count) {
SDL_free(displays);
return "unknown";
}
SDL_DisplayID display = displays[displayindex];
SDL_free(displays);
SDL_DisplayOrientation orientation = SDL_GetCurrentDisplayOrientation(display);
switch (orientation) {
case SDL_ORIENTATION_LANDSCAPE:
return "landscape";
case SDL_ORIENTATION_LANDSCAPE_FLIPPED:
return "landscapeflipped";
case SDL_ORIENTATION_PORTRAIT:
return "portrait";
case SDL_ORIENTATION_PORTRAIT_FLIPPED:
return "portraitflipped";
default:
return "unknown";
}
}
void Window::getFullscreenModes(int displayindex, int **widths, int **heights, int *count) {
*widths = nullptr;
*heights = nullptr;
*count = 0;
int displayCount = 0;
SDL_DisplayID *displays = SDL_GetDisplays(&displayCount);
if (!displays || displayindex >= displayCount) {
SDL_free(displays);
return;
}
SDL_DisplayID display = displays[displayindex];
SDL_free(displays);
int modeCount = 0;
SDL_DisplayMode **modes = SDL_GetFullscreenDisplayModes(display, &modeCount);
if (!modes || modeCount == 0) {
return;
}
*widths = (int *)malloc(modeCount * sizeof(int));
*heights = (int *)malloc(modeCount * sizeof(int));
*count = modeCount;
for (int i = 0; i < modeCount; i++) {
(*widths)[i] = modes[i]->w;
(*heights)[i] = modes[i]->h;
}
SDL_free(modes);
}
static SDL_MessageBoxFlags getMessageBoxType(const char *type) {
if (type && strcmp(type, "error") == 0) {
return SDL_MESSAGEBOX_ERROR;
} else if (type && strcmp(type, "warning") == 0) {
return SDL_MESSAGEBOX_WARNING;
}
return SDL_MESSAGEBOX_INFORMATION;
}
bool Window::showMessageBox(const char *title, const char *message, const char *type, bool attachtowindow) {
SDL_MessageBoxFlags flags = getMessageBoxType(type);
// Note: attachtowindow would require passing the SDL_Window, but SDL_ShowSimpleMessageBox
// doesn't support it in the same way. We use nullptr for simplicity.
return SDL_ShowSimpleMessageBox(flags, title, message, nullptr);
}
int Window::showMessageBoxWithButtons(const char *title, const char *message, const char **buttons, int numbuttons, int enterbutton, int escapebutton, const char *type, bool attachtowindow) {
SDL_MessageBoxData data = {};
data.flags = getMessageBoxType(type);
data.title = title;
data.message = message;
data.numbuttons = numbuttons;
SDL_MessageBoxButtonData *buttonData = (SDL_MessageBoxButtonData *)malloc(numbuttons * sizeof(SDL_MessageBoxButtonData));
for (int i = 0; i < numbuttons; i++) {
buttonData[i].flags = 0;
if (i == enterbutton - 1) {
buttonData[i].flags |= SDL_MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT;
}
if (i == escapebutton - 1) {
buttonData[i].flags |= SDL_MESSAGEBOX_BUTTON_ESCAPEKEY_DEFAULT;
}
buttonData[i].buttonID = i + 1; // 1-indexed like Love2D
buttonData[i].text = buttons[i];
}
data.buttons = buttonData;
int buttonid = 0;
SDL_ShowMessageBox(&data, &buttonid);
free(buttonData);
return buttonid;
}
} // namespace modules
} // namespace joy
|
zyedidia/joy
| 1
|
A framework for building 2D desktop games in JavaScript, with a Love2D-inspired API
|
C++
|
zyedidia
|
Zachary Yedidia
|
Stanford University
|
src/modules/window/window.hh
|
C++ Header
|
#pragma once
#include "SDL3/SDL.h"
namespace js {
class Context;
class Value;
}
namespace joy {
// Forward declaration
class Engine;
namespace modules {
class Window {
public:
Window(Engine *engine);
~Window();
// Window mode
bool setMode(int width, int height, bool fullscreen, bool resizable, bool borderless, int minwidth, int minheight);
void getMode(int *width, int *height, bool *fullscreen, bool *resizable, bool *borderless);
// Dimensions
int getWidth();
int getHeight();
// Title
void setTitle(const char *title);
const char *getTitle();
// Fullscreen
void setFullscreen(bool fullscreen);
bool getFullscreen();
// Window state
bool isOpen();
void close();
// Position
void setPosition(int x, int y);
void getPosition(int *x, int *y);
// DPI
float getDPIScale();
// Window actions
void minimize();
void maximize();
void restore();
// Window state queries
bool isMaximized();
bool isMinimized();
bool isVisible();
bool hasFocus();
bool hasMouseFocus();
// DPI conversion
float fromPixels(float pixelvalue);
void fromPixels(float px, float py, float *x, float *y);
float toPixels(float value);
void toPixels(float x, float y, float *px, float *py);
// Display sleep
bool isDisplaySleepEnabled();
void setDisplaySleepEnabled(bool enable);
// Window attention
void requestAttention(bool continuous);
// Safe area
void getSafeArea(int *x, int *y, int *w, int *h);
// Display info
static int getDisplayCount();
static void getDesktopDimensions(int displayindex, int *width, int *height);
static const char *getDisplayName(int displayindex);
static const char *getDisplayOrientation(int displayindex);
static void getFullscreenModes(int displayindex, int **widths, int **heights, int *count);
// Message box
static bool showMessageBox(const char *title, const char *message, const char *type, bool attachtowindow);
static int showMessageBoxWithButtons(const char *title, const char *message, const char **buttons, int numbuttons, int enterbutton, int escapebutton, const char *type, bool attachtowindow);
// Initialize JS bindings
static void initJS(js::Context &ctx, js::Value &joy);
private:
Engine *engine_;
};
} // namespace modules
} // namespace joy
|
zyedidia/joy
| 1
|
A framework for building 2D desktop games in JavaScript, with a Love2D-inspired API
|
C++
|
zyedidia
|
Zachary Yedidia
|
Stanford University
|
src/modules/window/window_js.cc
|
C++
|
#include "js/js.hh"
#include "window.hh"
#include "engine.hh"
#include <cstdlib>
#include <vector>
namespace joy {
namespace modules {
// Helper to get Window from JS context
static Window *getWindow(js::FunctionArgs &args) {
Engine *engine = args.getContextOpaque<Engine>();
return engine ? engine->getWindowModule() : nullptr;
}
// Helper to get boolean from flags object
static bool getFlagBool(js::Context &ctx, js::Value &flags, const char *name, bool def) {
js::Value val = flags.getProperty(ctx, name);
if (val.isUndefined()) {
return def;
}
return val.toBool();
}
// Helper to get int from flags object
static int getFlagInt(js::Context &ctx, js::Value &flags, const char *name, int def) {
js::Value val = flags.getProperty(ctx, name);
if (val.isUndefined()) {
return def;
}
return val.toInt32();
}
static void js_window_setMode(js::FunctionArgs &args) {
Window *window = getWindow(args);
if (!window) {
args.throwError("window.setMode: no window available");
return;
}
if (args.length() < 2) {
args.throwError("window.setMode requires width and height");
return;
}
int width = args.arg(0).toInt32();
int height = args.arg(1).toInt32();
// Parse flags
bool fullscreen = false;
bool resizable = false;
bool borderless = false;
int minwidth = 1;
int minheight = 1;
if (args.length() >= 3) {
js::Value flagsobj = args.arg(2);
if (flagsobj.isObject()) {
fullscreen = getFlagBool(args.context(), flagsobj, "fullscreen", false);
resizable = getFlagBool(args.context(), flagsobj, "resizable", false);
borderless = getFlagBool(args.context(), flagsobj, "borderless", false);
minwidth = getFlagInt(args.context(), flagsobj, "minwidth", 1);
minheight = getFlagInt(args.context(), flagsobj, "minheight", 1);
}
}
window->setMode(width, height, fullscreen, resizable, borderless, minwidth, minheight);
args.returnValue(js::Value::boolean(true));
}
static void js_window_getMode(js::FunctionArgs &args) {
Window *window = getWindow(args);
if (!window) {
args.returnUndefined();
return;
}
int w, h;
bool fullscreen, resizable, borderless;
window->getMode(&w, &h, &fullscreen, &resizable, &borderless);
js::Value flags = js::Value::object(args.context());
flags.setProperty(args.context(), "fullscreen", js::Value::boolean(fullscreen));
flags.setProperty(args.context(), "fullscreentype", js::Value::string(args.context(), "desktop"));
flags.setProperty(args.context(), "vsync", js::Value::number(1));
flags.setProperty(args.context(), "resizable", js::Value::boolean(resizable));
flags.setProperty(args.context(), "borderless", js::Value::boolean(borderless));
js::Value arr = js::Value::array(args.context());
arr.setProperty(args.context(), 0u, js::Value::number(w));
arr.setProperty(args.context(), 1u, js::Value::number(h));
arr.setProperty(args.context(), 2u, std::move(flags));
args.returnValue(std::move(arr));
}
static void js_window_getWidth(js::FunctionArgs &args) {
Window *window = getWindow(args);
args.returnValue(js::Value::number(window ? window->getWidth() : 0));
}
static void js_window_getHeight(js::FunctionArgs &args) {
Window *window = getWindow(args);
args.returnValue(js::Value::number(window ? window->getHeight() : 0));
}
static void js_window_setTitle(js::FunctionArgs &args) {
Window *window = getWindow(args);
if (!window) {
args.returnUndefined();
return;
}
if (args.length() < 1) {
args.throwError("window.setTitle requires a title");
return;
}
std::string title = args.arg(0).toString(args.context());
window->setTitle(title.c_str());
args.returnUndefined();
}
static void js_window_getTitle(js::FunctionArgs &args) {
Window *window = getWindow(args);
if (!window) {
args.returnValue(js::Value::string(args.context(), ""));
return;
}
args.returnValue(js::Value::string(args.context(), window->getTitle()));
}
static void js_window_setFullscreen(js::FunctionArgs &args) {
Window *window = getWindow(args);
if (!window) {
args.returnValue(js::Value::boolean(false));
return;
}
if (args.length() < 1) {
args.throwError("window.setFullscreen requires a boolean");
return;
}
bool fullscreen = args.arg(0).toBool();
window->setFullscreen(fullscreen);
args.returnValue(js::Value::boolean(true));
}
static void js_window_getFullscreen(js::FunctionArgs &args) {
Window *window = getWindow(args);
bool is_fullscreen = window ? window->getFullscreen() : false;
js::Value arr = js::Value::array(args.context());
arr.setProperty(args.context(), 0u, js::Value::boolean(is_fullscreen));
arr.setProperty(args.context(), 1u, js::Value::string(args.context(), "desktop"));
args.returnValue(std::move(arr));
}
static void js_window_isOpen(js::FunctionArgs &args) {
Window *window = getWindow(args);
args.returnValue(js::Value::boolean(window && window->isOpen()));
}
static void js_window_close(js::FunctionArgs &args) {
Window *window = getWindow(args);
if (window) {
window->close();
}
args.returnUndefined();
}
static void js_window_getDesktopDimensions(js::FunctionArgs &args) {
int display_index = 0;
if (args.length() >= 1) {
display_index = args.arg(0).toInt32();
}
int w, h;
Window::getDesktopDimensions(display_index, &w, &h);
js::Value arr = js::Value::array(args.context());
arr.setProperty(args.context(), 0u, js::Value::number(w));
arr.setProperty(args.context(), 1u, js::Value::number(h));
args.returnValue(std::move(arr));
}
static void js_window_setPosition(js::FunctionArgs &args) {
Window *window = getWindow(args);
if (!window) {
args.returnUndefined();
return;
}
if (args.length() < 2) {
args.throwError("window.setPosition requires x and y");
return;
}
int x = args.arg(0).toInt32();
int y = args.arg(1).toInt32();
window->setPosition(x, y);
args.returnUndefined();
}
static void js_window_getPosition(js::FunctionArgs &args) {
Window *window = getWindow(args);
int x = 0, y = 0;
if (window) {
window->getPosition(&x, &y);
}
js::Value arr = js::Value::array(args.context());
arr.setProperty(args.context(), 0u, js::Value::number(x));
arr.setProperty(args.context(), 1u, js::Value::number(y));
args.returnValue(std::move(arr));
}
static void js_window_setVSync(js::FunctionArgs &args) {
// VSync is controlled during initialization
args.returnUndefined();
}
static void js_window_getVSync(js::FunctionArgs &args) {
args.returnValue(js::Value::number(1));
}
static void js_window_getDPIScale(js::FunctionArgs &args) {
Window *window = getWindow(args);
if (!window) {
args.returnValue(js::Value::number(1.0));
return;
}
args.returnValue(js::Value::number(window->getDPIScale()));
}
static void js_window_minimize(js::FunctionArgs &args) {
Window *window = getWindow(args);
if (window) {
window->minimize();
}
args.returnUndefined();
}
static void js_window_maximize(js::FunctionArgs &args) {
Window *window = getWindow(args);
if (window) {
window->maximize();
}
args.returnUndefined();
}
static void js_window_restore(js::FunctionArgs &args) {
Window *window = getWindow(args);
if (window) {
window->restore();
}
args.returnUndefined();
}
static void js_window_isMaximized(js::FunctionArgs &args) {
Window *window = getWindow(args);
args.returnValue(js::Value::boolean(window && window->isMaximized()));
}
static void js_window_isMinimized(js::FunctionArgs &args) {
Window *window = getWindow(args);
args.returnValue(js::Value::boolean(window && window->isMinimized()));
}
static void js_window_isVisible(js::FunctionArgs &args) {
Window *window = getWindow(args);
args.returnValue(js::Value::boolean(window && window->isVisible()));
}
static void js_window_hasFocus(js::FunctionArgs &args) {
Window *window = getWindow(args);
args.returnValue(js::Value::boolean(window && window->hasFocus()));
}
static void js_window_getDisplayCount(js::FunctionArgs &args) {
args.returnValue(js::Value::number(Window::getDisplayCount()));
}
static void js_window_getDisplayName(js::FunctionArgs &args) {
int display_index = 0;
if (args.length() >= 1) {
display_index = args.arg(0).toInt32();
}
args.returnValue(js::Value::string(args.context(), Window::getDisplayName(display_index)));
}
static void js_window_hasMouseFocus(js::FunctionArgs &args) {
Window *window = getWindow(args);
args.returnValue(js::Value::boolean(window && window->hasMouseFocus()));
}
static void js_window_fromPixels(js::FunctionArgs &args) {
Window *window = getWindow(args);
if (!window) {
args.returnUndefined();
return;
}
if (args.length() < 1) {
args.throwError("window.fromPixels requires at least one argument");
return;
}
if (args.length() >= 2) {
// Two-argument version: fromPixels(px, py) -> [x, y]
double px = args.arg(0).toFloat64();
double py = args.arg(1).toFloat64();
float x, y;
window->fromPixels((float)px, (float)py, &x, &y);
js::Value arr = js::Value::array(args.context());
arr.setProperty(args.context(), 0u, js::Value::number((double)x));
arr.setProperty(args.context(), 1u, js::Value::number((double)y));
args.returnValue(std::move(arr));
} else {
// Single argument version: fromPixels(pixelvalue) -> value
double pixelvalue = args.arg(0).toFloat64();
args.returnValue(js::Value::number((double)window->fromPixels((float)pixelvalue)));
}
}
static void js_window_toPixels(js::FunctionArgs &args) {
Window *window = getWindow(args);
if (!window) {
args.returnUndefined();
return;
}
if (args.length() < 1) {
args.throwError("window.toPixels requires at least one argument");
return;
}
if (args.length() >= 2) {
// Two-argument version: toPixels(x, y) -> [px, py]
double x = args.arg(0).toFloat64();
double y = args.arg(1).toFloat64();
float px, py;
window->toPixels((float)x, (float)y, &px, &py);
js::Value arr = js::Value::array(args.context());
arr.setProperty(args.context(), 0u, js::Value::number((double)px));
arr.setProperty(args.context(), 1u, js::Value::number((double)py));
args.returnValue(std::move(arr));
} else {
// Single argument version: toPixels(value) -> pixelvalue
double value = args.arg(0).toFloat64();
args.returnValue(js::Value::number((double)window->toPixels((float)value)));
}
}
static void js_window_isDisplaySleepEnabled(js::FunctionArgs &args) {
Window *window = getWindow(args);
args.returnValue(js::Value::boolean(window && window->isDisplaySleepEnabled()));
}
static void js_window_setDisplaySleepEnabled(js::FunctionArgs &args) {
Window *window = getWindow(args);
if (!window) {
args.returnUndefined();
return;
}
if (args.length() < 1) {
args.throwError("window.setDisplaySleepEnabled requires a boolean");
return;
}
bool enable = args.arg(0).toBool();
window->setDisplaySleepEnabled(enable);
args.returnUndefined();
}
static void js_window_requestAttention(js::FunctionArgs &args) {
Window *window = getWindow(args);
if (!window) {
args.returnUndefined();
return;
}
bool continuous = false;
if (args.length() >= 1) {
continuous = args.arg(0).toBool();
}
window->requestAttention(continuous);
args.returnUndefined();
}
static void js_window_getSafeArea(js::FunctionArgs &args) {
Window *window = getWindow(args);
int x = 0, y = 0, w = 0, h = 0;
if (window) {
window->getSafeArea(&x, &y, &w, &h);
}
js::Value arr = js::Value::array(args.context());
arr.setProperty(args.context(), 0u, js::Value::number(x));
arr.setProperty(args.context(), 1u, js::Value::number(y));
arr.setProperty(args.context(), 2u, js::Value::number(w));
arr.setProperty(args.context(), 3u, js::Value::number(h));
args.returnValue(std::move(arr));
}
static void js_window_getDisplayOrientation(js::FunctionArgs &args) {
int display_index = 0;
if (args.length() >= 1) {
display_index = args.arg(0).toInt32();
}
args.returnValue(js::Value::string(args.context(), Window::getDisplayOrientation(display_index)));
}
static void js_window_getFullscreenModes(js::FunctionArgs &args) {
int display_index = 0;
if (args.length() >= 1) {
display_index = args.arg(0).toInt32();
}
int *widths, *heights, count;
Window::getFullscreenModes(display_index, &widths, &heights, &count);
js::Value arr = js::Value::array(args.context());
for (int i = 0; i < count; i++) {
js::Value mode = js::Value::object(args.context());
mode.setProperty(args.context(), "width", js::Value::number(widths[i]));
mode.setProperty(args.context(), "height", js::Value::number(heights[i]));
arr.setProperty(args.context(), (uint32_t)i, std::move(mode));
}
if (widths) free(widths);
if (heights) free(heights);
args.returnValue(std::move(arr));
}
static void js_window_showMessageBox(js::FunctionArgs &args) {
if (args.length() < 2) {
args.throwError("window.showMessageBox requires title and message");
return;
}
std::string title = args.arg(0).toString(args.context());
std::string message = args.arg(1).toString(args.context());
// Check if third argument is an array (buttonlist) or string (type)
if (args.length() >= 3 && args.arg(2).isArray()) {
// Custom buttons version
js::Value buttonlist = args.arg(2);
js::Value lengthVal = buttonlist.getProperty(args.context(), "length");
int numbuttons = lengthVal.toInt32();
if (numbuttons == 0) {
args.returnValue(js::Value::number(0));
return;
}
const char **buttons = (const char **)malloc(numbuttons * sizeof(const char *));
std::vector<std::string> buttonStrings(numbuttons);
for (int i = 0; i < numbuttons; i++) {
js::Value btn = buttonlist.getProperty(args.context(), (uint32_t)i);
buttonStrings[i] = btn.toString(args.context());
buttons[i] = buttonStrings[i].c_str();
}
// Get enterbutton and escapebutton from buttonlist object
js::Value enterVal = buttonlist.getProperty(args.context(), "enterbutton");
js::Value escapeVal = buttonlist.getProperty(args.context(), "escapebutton");
int enterbutton = enterVal.isUndefined() ? 0 : enterVal.toInt32();
int escapebutton = escapeVal.isUndefined() ? 0 : escapeVal.toInt32();
std::string type = "info";
bool attachtowindow = true;
if (args.length() >= 4) {
type = args.arg(3).toString(args.context());
}
if (args.length() >= 5) {
attachtowindow = args.arg(4).toBool();
}
int result = Window::showMessageBoxWithButtons(title.c_str(), message.c_str(), buttons, numbuttons, enterbutton, escapebutton, type.c_str(), attachtowindow);
free(buttons);
args.returnValue(js::Value::number(result));
} else {
// Simple message box version
std::string type = "info";
bool attachtowindow = true;
if (args.length() >= 3) {
type = args.arg(2).toString(args.context());
}
if (args.length() >= 4) {
attachtowindow = args.arg(3).toBool();
}
bool success = Window::showMessageBox(title.c_str(), message.c_str(), type.c_str(), attachtowindow);
args.returnValue(js::Value::boolean(success));
}
}
static void js_window_updateMode(js::FunctionArgs &args) {
Window *window = getWindow(args);
if (!window) {
args.returnValue(js::Value::boolean(false));
return;
}
if (args.length() < 2) {
args.throwError("window.updateMode requires width and height");
return;
}
int width = args.arg(0).toInt32();
int height = args.arg(1).toInt32();
// Get current mode values as defaults
int curWidth, curHeight;
bool fullscreen, resizable, borderless;
window->getMode(&curWidth, &curHeight, &fullscreen, &resizable, &borderless);
int minwidth = 1, minheight = 1;
// Parse optional settings, using current values as defaults
if (args.length() >= 3) {
js::Value settings = args.arg(2);
if (settings.isObject()) {
fullscreen = getFlagBool(args.context(), settings, "fullscreen", fullscreen);
resizable = getFlagBool(args.context(), settings, "resizable", resizable);
borderless = getFlagBool(args.context(), settings, "borderless", borderless);
minwidth = getFlagInt(args.context(), settings, "minwidth", minwidth);
minheight = getFlagInt(args.context(), settings, "minheight", minheight);
}
}
bool success = window->setMode(width, height, fullscreen, resizable, borderless, minwidth, minheight);
args.returnValue(js::Value::boolean(success));
}
void Window::initJS(js::Context &ctx, js::Value &joy) {
js::ModuleBuilder(ctx, "window")
.function("setMode", js_window_setMode, 3)
.function("getMode", js_window_getMode, 0)
.function("getWidth", js_window_getWidth, 0)
.function("getHeight", js_window_getHeight, 0)
.function("setTitle", js_window_setTitle, 1)
.function("getTitle", js_window_getTitle, 0)
.function("setFullscreen", js_window_setFullscreen, 1)
.function("getFullscreen", js_window_getFullscreen, 0)
.function("isOpen", js_window_isOpen, 0)
.function("close", js_window_close, 0)
.function("getDesktopDimensions", js_window_getDesktopDimensions, 1)
.function("setPosition", js_window_setPosition, 2)
.function("getPosition", js_window_getPosition, 0)
.function("setVSync", js_window_setVSync, 1)
.function("getVSync", js_window_getVSync, 0)
.function("getDPIScale", js_window_getDPIScale, 0)
.function("minimize", js_window_minimize, 0)
.function("maximize", js_window_maximize, 0)
.function("restore", js_window_restore, 0)
.function("isMaximized", js_window_isMaximized, 0)
.function("isMinimized", js_window_isMinimized, 0)
.function("isVisible", js_window_isVisible, 0)
.function("hasFocus", js_window_hasFocus, 0)
.function("hasMouseFocus", js_window_hasMouseFocus, 0)
.function("getDisplayCount", js_window_getDisplayCount, 0)
.function("getDisplayName", js_window_getDisplayName, 1)
.function("getDisplayOrientation", js_window_getDisplayOrientation, 1)
.function("getFullscreenModes", js_window_getFullscreenModes, 1)
.function("getSafeArea", js_window_getSafeArea, 0)
.function("fromPixels", js_window_fromPixels, 2)
.function("toPixels", js_window_toPixels, 2)
.function("isDisplaySleepEnabled", js_window_isDisplaySleepEnabled, 0)
.function("setDisplaySleepEnabled", js_window_setDisplaySleepEnabled, 1)
.function("requestAttention", js_window_requestAttention, 1)
.function("showMessageBox", js_window_showMessageBox, 5)
.function("updateMode", js_window_updateMode, 3)
.attachTo(joy);
}
} // namespace modules
} // namespace joy
|
zyedidia/joy
| 1
|
A framework for building 2D desktop games in JavaScript, with a Love2D-inspired API
|
C++
|
zyedidia
|
Zachary Yedidia
|
Stanford University
|
src/nuklear_config.h
|
C/C++ Header
|
#pragma once
#define NK_INCLUDE_FIXED_TYPES
#define NK_INCLUDE_STANDARD_IO
#define NK_INCLUDE_DEFAULT_ALLOCATOR
#define NK_INCLUDE_VERTEX_BUFFER_OUTPUT
#define NK_INCLUDE_FONT_BAKING
#define NK_INCLUDE_DEFAULT_FONT
#include "nuklear.h"
|
zyedidia/joy
| 1
|
A framework for building 2D desktop games in JavaScript, with a Love2D-inspired API
|
C++
|
zyedidia
|
Zachary Yedidia
|
Stanford University
|
src/render.hh
|
C++ Header
|
#pragma once
#include "SDL3/SDL.h"
namespace joy {
// Forward declarations
namespace modules {
class Graphics;
class Gui;
}
namespace render {
class Render {
public:
Render();
virtual ~Render();
// Initialize renderer with SDL window
bool init(SDL_Window *window);
// Begin/end frame rendering
void beginFrame();
void endFrame();
// Clear screen
void clear(float r, float g, float b, float a);
// Check if renderer is initialized
bool isActive() const { return active_; }
// Set graphics module for text rendering
void setGraphicsModule(modules::Graphics *graphics) { graphics_ = graphics; }
// Set GUI module for GUI rendering
void setGuiModule(modules::Gui *gui) { gui_ = gui; }
private:
bool active_;
SDL_Window *window_;
modules::Graphics *graphics_;
modules::Gui *gui_;
// Platform-specific context
#ifdef RENDER_METAL
void *metal_view_; // SDL_MetalView
void *metal_layer_; // CAMetalLayer*
void *current_drawable_; // id<CAMetalDrawable>
bool frame_valid_;
#else
void *gl_context_; // SDL_GLContext
#endif
};
} // namespace render
} // namespace joy
|
zyedidia/joy
| 1
|
A framework for building 2D desktop games in JavaScript, with a Love2D-inspired API
|
C++
|
zyedidia
|
Zachary Yedidia
|
Stanford University
|
src/render_metal.mm
|
Objective-C++
|
#include "render.hh"
#include "modules/graphics/graphics.hh"
#include "modules/gui/gui.hh"
#include "SDL3/SDL.h"
#include "SDL3/SDL_metal.h"
#import "Metal/Metal.h"
#import "QuartzCore/CAMetalLayer.h"
#include "sokol_gfx.h"
#include "sokol_log.h"
#include <cstdio>
namespace joy {
namespace render {
Render::Render()
: active_(false)
, window_(nullptr)
, graphics_(nullptr)
, gui_(nullptr)
, metal_view_(nullptr)
, metal_layer_(nullptr)
, current_drawable_(nullptr)
, frame_valid_(false)
{
}
Render::~Render() {
if (active_) {
sg_shutdown();
if (metal_view_) {
SDL_Metal_DestroyView((SDL_MetalView)metal_view_);
metal_view_ = nullptr;
}
}
}
bool Render::init(SDL_Window *window) {
if (!window) {
return false;
}
window_ = window;
// Create Metal view
metal_view_ = SDL_Metal_CreateView(window_);
if (!metal_view_) {
fprintf(stderr, "Failed to create Metal view: %s\n", SDL_GetError());
return false;
}
// Get the Metal layer
CAMetalLayer *layer = (__bridge CAMetalLayer *)SDL_Metal_GetLayer((SDL_MetalView)metal_view_);
metal_layer_ = (__bridge void *)layer;
// Create Metal device if not already assigned
id<MTLDevice> device = layer.device;
if (!device) {
device = MTLCreateSystemDefaultDevice();
layer.device = device;
}
layer.pixelFormat = MTLPixelFormatBGRA8Unorm;
layer.displaySyncEnabled = YES;
if (!device) {
fprintf(stderr, "Failed to create Metal device\n");
SDL_Metal_DestroyView((SDL_MetalView)metal_view_);
metal_view_ = nullptr;
return false;
}
// Initialize sokol_gfx with Metal backend
sg_desc desc = {};
desc.environment.defaults.color_format = SG_PIXELFORMAT_BGRA8;
desc.environment.defaults.depth_format = SG_PIXELFORMAT_DEPTH_STENCIL;
desc.environment.defaults.sample_count = 1;
desc.environment.metal.device = (__bridge const void *)device;
desc.logger.func = slog_func;
sg_setup(&desc);
if (!sg_isvalid()) {
fprintf(stderr, "Failed to initialize sokol_gfx\n");
SDL_Metal_DestroyView((SDL_MetalView)metal_view_);
metal_view_ = nullptr;
return false;
}
active_ = true;
return true;
}
void Render::beginFrame() {
if (!active_) return;
int pw, ph;
SDL_GetWindowSizeInPixels(window_, &pw, &ph);
CAMetalLayer *layer = (__bridge CAMetalLayer *)metal_layer_;
id<CAMetalDrawable> drawable = [layer nextDrawable];
if (!drawable) {
frame_valid_ = false;
return;
}
[drawable retain];
current_drawable_ = (__bridge void *)drawable;
frame_valid_ = true;
sg_pass pass = {};
pass.swapchain.width = pw;
pass.swapchain.height = ph;
pass.swapchain.sample_count = 1;
pass.swapchain.color_format = SG_PIXELFORMAT_BGRA8;
pass.swapchain.depth_format = SG_PIXELFORMAT_DEPTH_STENCIL;
pass.swapchain.metal.current_drawable = current_drawable_;
pass.swapchain.metal.depth_stencil_texture = nullptr;
pass.swapchain.metal.msaa_color_texture = nullptr;
sg_begin_pass(&pass);
// Begin batch rendering frame
// w, h = logical pixels, pw, ph = physical pixels
int w, h;
SDL_GetWindowSize(window_, &w, &h);
if (graphics_) {
graphics_->beginFrame(w, h, pw, ph);
}
}
void Render::endFrame() {
if (!active_) return;
if (!frame_valid_) {
SDL_Delay(16); // ~60fps fallback when drawable unavailable
return;
}
// End batch rendering frame
if (graphics_) {
graphics_->endFrame();
}
// Render GUI using logical dimensions for proper hiDPI support
if (gui_) {
int win_w, win_h;
SDL_GetWindowSize(window_, &win_w, &win_h);
gui_->render(win_w, win_h);
}
sg_end_pass();
sg_commit();
// Release the drawable that was retained in beginFrame
if (current_drawable_) {
id<CAMetalDrawable> drawable = (__bridge id<CAMetalDrawable>)current_drawable_;
[drawable release];
current_drawable_ = nullptr;
}
}
void Render::clear(float r, float g, float b, float a) {
if (!active_) return;
if (graphics_) {
graphics_->clear(r, g, b, a, true);
}
}
} // namespace render
} // namespace joy
|
zyedidia/joy
| 1
|
A framework for building 2D desktop games in JavaScript, with a Love2D-inspired API
|
C++
|
zyedidia
|
Zachary Yedidia
|
Stanford University
|
src/render_opengl.cc
|
C++
|
#include "render.hh"
#include "modules/graphics/graphics.hh"
#include "modules/gui/gui.hh"
#include "SDL3/SDL.h"
#include "sokol_gfx.h"
#include "sokol_log.h"
#include <cstdio>
#include <cstring>
namespace joy {
namespace render {
// Custom logger that filters out uniform-not-found warnings
// These happen when shaders declare uniforms that get optimized out
static void joy_sokol_logger(
const char* tag,
uint32_t log_level,
uint32_t log_item,
const char* message,
uint32_t line_nr,
const char* filename,
void* user_data
) {
// Filter out GL_UNIFORMBLOCK_NAME_NOT_FOUND_IN_SHADER warnings
// These appear when uniforms are optimized out by GLSL compiler
if (log_item == SG_LOGITEM_GL_UNIFORMBLOCK_NAME_NOT_FOUND_IN_SHADER) {
return;
}
// Call the default sokol logger for everything else
slog_func(tag, log_level, log_item, message, line_nr, filename, user_data);
}
Render::Render()
: active_(false)
, window_(nullptr)
, graphics_(nullptr)
, gui_(nullptr)
, gl_context_(nullptr)
{
}
Render::~Render() {
if (active_) {
sg_shutdown();
if (gl_context_) {
SDL_GL_DestroyContext((SDL_GLContext)gl_context_);
gl_context_ = nullptr;
}
}
}
bool Render::init(SDL_Window *window) {
if (!window) {
return false;
}
window_ = window;
// Set OpenGL attributes
#ifdef __EMSCRIPTEN__
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES);
#else
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
#endif
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
// Create OpenGL context
gl_context_ = SDL_GL_CreateContext(window_);
if (!gl_context_) {
fprintf(stderr, "Failed to create GL context: %s\n", SDL_GetError());
return false;
}
SDL_GL_MakeCurrent(window_, (SDL_GLContext)gl_context_);
#ifndef __EMSCRIPTEN__
SDL_GL_SetSwapInterval(1); // VSync
#endif
// Initialize sokol_gfx
sg_desc desc = {};
desc.environment.defaults.color_format = SG_PIXELFORMAT_RGBA8;
desc.environment.defaults.depth_format = SG_PIXELFORMAT_DEPTH_STENCIL;
desc.environment.defaults.sample_count = 1;
desc.logger.func = joy_sokol_logger;
sg_setup(&desc);
if (!sg_isvalid()) {
fprintf(stderr, "Failed to initialize sokol_gfx\n");
SDL_GL_DestroyContext((SDL_GLContext)gl_context_);
gl_context_ = nullptr;
return false;
}
active_ = true;
return true;
}
void Render::beginFrame() {
if (!active_) return;
int w, h;
SDL_GetWindowSize(window_, &w, &h);
int pw, ph;
SDL_GetWindowSizeInPixels(window_, &pw, &ph);
// Start render pass early so mid-frame flushes work
sg_pass pass = {};
pass.swapchain.width = pw;
pass.swapchain.height = ph;
pass.swapchain.sample_count = 1;
pass.swapchain.color_format = SG_PIXELFORMAT_RGBA8;
pass.swapchain.depth_format = SG_PIXELFORMAT_DEPTH_STENCIL;
pass.swapchain.gl.framebuffer = 0;
sg_begin_pass(&pass);
// Begin batch rendering frame
// w, h = logical pixels, pw, ph = physical pixels
if (graphics_) {
graphics_->beginFrame(w, h, pw, ph);
}
}
void Render::endFrame() {
if (!active_) return;
// End batch rendering frame
if (graphics_) {
graphics_->endFrame();
}
// Render GUI using logical dimensions for proper hiDPI support
if (gui_) {
int win_w, win_h;
SDL_GetWindowSize(window_, &win_w, &win_h);
gui_->render(win_w, win_h);
}
sg_end_pass();
sg_commit();
SDL_GL_SwapWindow(window_);
}
void Render::clear(float r, float g, float b, float a) {
if (!active_) return;
if (graphics_) {
graphics_->clear(r, g, b, a, true);
}
}
} // namespace render
} // namespace joy
|
zyedidia/joy
| 1
|
A framework for building 2D desktop games in JavaScript, with a Love2D-inspired API
|
C++
|
zyedidia
|
Zachary Yedidia
|
Stanford University
|
src/web-api/curl-websocket-utils.c
|
C
|
/* clang-format off */
/*
* Copyright (C) 2016 Gustavo Sverzut Barbieri
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
#include <string.h>
#include <ctype.h>
/* Platform-specific random includes */
#if defined(_WIN32)
#include <windows.h>
#include <bcrypt.h>
#elif defined(__linux__)
#include <sys/random.h>
#include <errno.h>
#endif
/*
* Embedded SHA-1 implementation (public domain, based on RFC 3174)
*/
static inline uint32_t _sha1_rol(uint32_t value, unsigned int bits)
{
return (value << bits) | (value >> (32 - bits));
}
static void _sha1_transform(uint32_t state[5], const uint8_t buffer[64])
{
uint32_t a, b, c, d, e, f, k, temp;
uint32_t w[80];
int i;
for (i = 0; i < 16; i++) {
w[i] = ((uint32_t)buffer[i * 4] << 24) |
((uint32_t)buffer[i * 4 + 1] << 16) |
((uint32_t)buffer[i * 4 + 2] << 8) |
((uint32_t)buffer[i * 4 + 3]);
}
for (i = 16; i < 80; i++) {
w[i] = _sha1_rol(w[i-3] ^ w[i-8] ^ w[i-14] ^ w[i-16], 1);
}
a = state[0]; b = state[1]; c = state[2]; d = state[3]; e = state[4];
for (i = 0; i < 80; i++) {
if (i < 20) {
f = (b & c) | ((~b) & d);
k = 0x5A827999;
} else if (i < 40) {
f = b ^ c ^ d;
k = 0x6ED9EBA1;
} else if (i < 60) {
f = (b & c) | (b & d) | (c & d);
k = 0x8F1BBCDC;
} else {
f = b ^ c ^ d;
k = 0xCA62C1D6;
}
temp = _sha1_rol(a, 5) + f + e + k + w[i];
e = d; d = c; c = _sha1_rol(b, 30); b = a; a = temp;
}
state[0] += a; state[1] += b; state[2] += c; state[3] += d; state[4] += e;
}
static void
_cws_sha1(const void *input, const size_t input_len, void *output)
{
uint32_t state[5] = {0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0};
uint8_t buffer[64];
size_t i, buffer_idx = 0;
uint64_t total_bits = input_len * 8;
const uint8_t *data = (const uint8_t *)input;
uint8_t *out = (uint8_t *)output;
/* Process complete 64-byte blocks */
for (i = 0; i < input_len; i++) {
buffer[buffer_idx++] = data[i];
if (buffer_idx == 64) {
_sha1_transform(state, buffer);
buffer_idx = 0;
}
}
/* Pad message */
buffer[buffer_idx++] = 0x80;
if (buffer_idx > 56) {
while (buffer_idx < 64) buffer[buffer_idx++] = 0;
_sha1_transform(state, buffer);
buffer_idx = 0;
}
while (buffer_idx < 56) buffer[buffer_idx++] = 0;
/* Append length in bits (big-endian) */
for (i = 0; i < 8; i++) {
buffer[56 + i] = (uint8_t)(total_bits >> (56 - i * 8));
}
_sha1_transform(state, buffer);
/* Output hash (big-endian) */
for (i = 0; i < 5; i++) {
out[i * 4] = (uint8_t)(state[i] >> 24);
out[i * 4 + 1] = (uint8_t)(state[i] >> 16);
out[i * 4 + 2] = (uint8_t)(state[i] >> 8);
out[i * 4 + 3] = (uint8_t)(state[i]);
}
}
static inline void
_cws_debug(const char *prefix, const void *buffer, size_t len)
{
const uint8_t *bytes = buffer;
size_t i;
if (prefix)
fprintf(stderr, "%s:", prefix);
for (i = 0; i < len; i++) {
uint8_t b = bytes[i];
if (isprint(b))
fprintf(stderr, " %#04x(%c)", b, b);
else
fprintf(stderr, " %#04x", b);
}
if (prefix)
fprintf(stderr, "\n");
}
static void
_cws_encode_base64(const uint8_t *input, const size_t input_len, char *output)
{
static const char base64_map[65] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
size_t i, o;
uint8_t c;
for (i = 0, o = 0; i + 3 <= input_len; i += 3) {
c = (input[i] & (((1 << 6) - 1) << 2)) >> 2;
output[o++] = base64_map[c];
c = (input[i] & ((1 << 2) - 1)) << 4;
c |= (input[i + 1] & (((1 << 4) - 1) << 4)) >> 4;
output[o++] = base64_map[c];
c = (input[i + 1] & ((1 << 4) - 1)) << 2;
c |= (input[i + 2] & (((1 << 2) - 1) << 6)) >> 6;
output[o++] = base64_map[c];
c = input[i + 2] & ((1 << 6) - 1);
output[o++] = base64_map[c];
}
if (i + 1 == input_len) {
c = (input[i] & (((1 << 6) - 1) << 2)) >> 2;
output[o++] = base64_map[c];
c = (input[i] & ((1 << 2) - 1)) << 4;
output[o++] = base64_map[c];
output[o++] = base64_map[64];
output[o++] = base64_map[64];
} else if (i + 2 == input_len) {
c = (input[i] & (((1 << 6) - 1) << 2)) >> 2;
output[o++] = base64_map[c];
c = (input[i] & ((1 << 2) - 1)) << 4;
c |= (input[i + 1] & (((1 << 4) - 1) << 4)) >> 4;
output[o++] = base64_map[c];
c = (input[i + 1] & ((1 << 4) - 1)) << 2;
output[o++] = base64_map[c];
output[o++] = base64_map[64];
}
}
static void
_cws_get_random(void *buffer, size_t len)
{
#if defined(_WIN32)
BCryptGenRandom(NULL, (PUCHAR)buffer, (ULONG)len, BCRYPT_USE_SYSTEM_PREFERRED_RNG);
#elif defined(__APPLE__)
arc4random_buf(buffer, len);
#else
uint8_t *buf = (uint8_t *)buffer;
size_t remaining = len;
while (remaining > 0) {
ssize_t ret = getrandom(buf, remaining, 0);
if (ret < 0) {
if (errno == EINTR) continue;
abort();
}
buf += ret;
remaining -= (size_t)ret;
}
#endif
}
static inline void
_cws_trim(const char **p_buffer, size_t *p_len)
{
const char *buffer = *p_buffer;
size_t len = *p_len;
while (len > 0 && isspace(buffer[0])) {
buffer++;
len--;
}
while (len > 0 && isspace(buffer[len - 1]))
len--;
*p_buffer = buffer;
*p_len = len;
}
static inline bool
_cws_header_has_prefix(const char *buffer, const size_t buflen, const char *prefix)
{
const size_t prefixlen = strlen(prefix);
if (buflen < prefixlen)
return false;
return strncasecmp(buffer, prefix, prefixlen) == 0;
}
static inline void
_cws_hton(void *mem, uint8_t len)
{
#if __BYTE_ORDER__ != __BIG_ENDIAN
uint8_t *bytes;
uint8_t i, mid;
if (len % 2) return;
mid = len / 2;
bytes = mem;
for (i = 0; i < mid; i++) {
uint8_t tmp = bytes[i];
bytes[i] = bytes[len - i - 1];
bytes[len - i - 1] = tmp;
}
#endif
}
static inline void
_cws_ntoh(void *mem, uint8_t len)
{
#if __BYTE_ORDER__ != __BIG_ENDIAN
uint8_t *bytes;
uint8_t i, mid;
if (len % 2) return;
mid = len / 2;
bytes = mem;
for (i = 0; i < mid; i++) {
uint8_t tmp = bytes[i];
bytes[i] = bytes[len - i - 1];
bytes[len - i - 1] = tmp;
}
#endif
}
|
zyedidia/joy
| 1
|
A framework for building 2D desktop games in JavaScript, with a Love2D-inspired API
|
C++
|
zyedidia
|
Zachary Yedidia
|
Stanford University
|
src/web-api/curl-websocket.c
|
C
|
/* clang-format off */
/*
* Copyright (C) 2016 Gustavo Sverzut Barbieri
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/* c-mode: linux-4 */
#include "curl-websocket.h"
#include <stdio.h>
#ifdef _MSC_VER
#define strncasecmp _strnicmp
#endif
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
#include <ctype.h>
#include <inttypes.h>
#include <errno.h>
#include <time.h>
#include "curl-websocket-utils.c"
#define STR_OR_EMPTY(p) (p != NULL ? p : "")
/* Temporary buffer size to use during WebSocket masking.
* stack-allocated
*/
#define CWS_MASK_TMPBUF_SIZE 4096
enum cws_opcode {
CWS_OPCODE_CONTINUATION = 0x0,
CWS_OPCODE_TEXT = 0x1,
CWS_OPCODE_BINARY = 0x2,
CWS_OPCODE_CLOSE = 0x8,
CWS_OPCODE_PING = 0x9,
CWS_OPCODE_PONG = 0xa,
};
static bool
cws_opcode_is_control(enum cws_opcode opcode)
{
switch (opcode) {
case CWS_OPCODE_CONTINUATION:
case CWS_OPCODE_TEXT:
case CWS_OPCODE_BINARY:
return false;
case CWS_OPCODE_CLOSE:
case CWS_OPCODE_PING:
case CWS_OPCODE_PONG:
return true;
}
return true;
}
static bool
cws_close_reason_is_valid(enum cws_close_reason r)
{
switch (r) {
case CWS_CLOSE_REASON_NORMAL:
case CWS_CLOSE_REASON_GOING_AWAY:
case CWS_CLOSE_REASON_PROTOCOL_ERROR:
case CWS_CLOSE_REASON_UNEXPECTED_DATA:
case CWS_CLOSE_REASON_INCONSISTENT_DATA:
case CWS_CLOSE_REASON_POLICY_VIOLATION:
case CWS_CLOSE_REASON_TOO_BIG:
case CWS_CLOSE_REASON_MISSING_EXTENSION:
case CWS_CLOSE_REASON_SERVER_ERROR:
case CWS_CLOSE_REASON_IANA_REGISTRY_START:
case CWS_CLOSE_REASON_IANA_REGISTRY_END:
case CWS_CLOSE_REASON_PRIVATE_START:
case CWS_CLOSE_REASON_PRIVATE_END:
return true;
case CWS_CLOSE_REASON_NO_REASON:
case CWS_CLOSE_REASON_ABRUPTLY:
return false;
}
if (r >= CWS_CLOSE_REASON_IANA_REGISTRY_START && r <= CWS_CLOSE_REASON_IANA_REGISTRY_END)
return true;
if (r >= CWS_CLOSE_REASON_PRIVATE_START && r <= CWS_CLOSE_REASON_PRIVATE_END)
return true;
return false;
}
/*
* WebSocket is a framed protocol in the format:
*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-------+-+-------------+-------------------------------+
* |F|R|R|R| opcode|M| Payload len | Extended payload length |
* |I|S|S|S| (4) |A| (7) | (16/64) |
* |N|V|V|V| |S| | (if payload len==126/127) |
* | |1|2|3| |K| | |
* +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
* | Extended payload length continued, if payload len == 127 |
* + - - - - - - - - - - - - - - - +-------------------------------+
* | |Masking-key, if MASK set to 1 |
* +-------------------------------+-------------------------------+
* | Masking-key (continued) | Payload Data |
* +-------------------------------- - - - - - - - - - - - - - - - +
* : Payload Data continued ... :
* + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +
* | Payload Data continued ... |
* +---------------------------------------------------------------+
*
* See https://tools.ietf.org/html/rfc6455#section-5.2
*/
struct cws_frame_header {
/* first byte: fin + opcode */
uint8_t opcode : 4;
uint8_t _reserved : 3;
uint8_t fin : 1;
/* second byte: mask + payload length */
uint8_t payload_len : 7; /* if 126, uses extra 2 bytes (uint16_t)
* if 127, uses extra 8 bytes (uint64_t)
* if <=125 is self-contained
*/
uint8_t mask : 1; /* if 1, uses 4 extra bytes */
};
struct cws_data {
CURL *easy;
struct cws_callbacks cbs;
struct {
char *requested;
char *received;
} websocket_protocols;
struct curl_slist *headers;
char accept_key[29];
struct {
struct {
uint8_t *payload;
uint64_t used;
uint64_t total;
enum cws_opcode opcode;
bool fin;
} current;
struct {
uint8_t *payload;
uint64_t used;
uint64_t total;
enum cws_opcode opcode;
} fragmented;
uint8_t tmpbuf[sizeof(struct cws_frame_header) + sizeof(uint64_t)];
uint8_t done; /* of tmpbuf, for header */
uint8_t needed; /* of tmpbuf, for header */
} recv;
struct {
uint8_t *buffer;
size_t len;
} send;
uint8_t dispatching;
uint8_t pause_flags;
bool accepted;
bool upgraded;
bool connection_websocket;
bool closed;
bool deleted;
time_t start;
};
static bool
_cws_write(struct cws_data *priv, const void *buffer, size_t len)
{
/* optimization note: we could grow by some rounded amount (ie:
* next power-of-2, 4096/pagesize...) and if using
* priv->send.position, do the memmove() here to free up some
* extra space without realloc() (see _cws_send_data()).
*/
//_cws_debug("WRITE", buffer, len);
uint8_t *tmp = realloc(priv->send.buffer, priv->send.len + len);
if (!tmp)
return false;
memcpy(tmp + priv->send.len, buffer, len);
priv->send.buffer = tmp;
priv->send.len += len;
if (priv->pause_flags & CURLPAUSE_SEND) {
priv->pause_flags &= ~CURLPAUSE_SEND;
curl_easy_pause(priv->easy, priv->pause_flags);
}
return true;
}
/*
* Mask is:
*
* for i in len:
* output[i] = input[i] ^ mask[i % 4]
*
* Here a temporary buffer is used to reduce number of "write" calls
* and pointer arithmetic to avoid counters.
*/
static bool
_cws_write_masked(struct cws_data *priv, const uint8_t mask[4], const void *buffer, size_t len)
{
const uint8_t *itr_begin = buffer;
const uint8_t *itr = itr_begin;
const uint8_t *itr_end = itr + len;
uint8_t tmpbuf[CWS_MASK_TMPBUF_SIZE];
while (itr < itr_end) {
uint8_t *o = tmpbuf, *o_end = tmpbuf + sizeof(tmpbuf);
for (; o < o_end && itr < itr_end; o++, itr++) {
*o = *itr ^ mask[(itr - itr_begin) & 0x3];
}
if (!_cws_write(priv, tmpbuf, o - tmpbuf))
return false;
}
return true;
}
static bool
_cws_send(struct cws_data *priv, enum cws_opcode opcode, const void *msg, size_t msglen)
{
struct cws_frame_header fh = {
.fin = 1, /* TODO review if should fragment over some boundary */
.opcode = opcode,
.mask = 1,
.payload_len = ((msglen > UINT16_MAX) ? 127 :
(msglen > 125) ? 126 : msglen),
};
uint8_t mask[4];
if (priv->closed) {
fprintf(stderr,"cannot send data to closed WebSocket connection %p", priv->easy);
return false;
}
_cws_get_random(mask, sizeof(mask));
if (!_cws_write(priv, &fh, sizeof(fh)))
return false;
if (fh.payload_len == 127) {
uint64_t payload_len = msglen;
_cws_hton(&payload_len, sizeof(payload_len));
if (!_cws_write(priv, &payload_len, sizeof(payload_len)))
return false;
} else if (fh.payload_len == 126) {
uint16_t payload_len = msglen;
_cws_hton(&payload_len, sizeof(payload_len));
if (!_cws_write(priv, &payload_len, sizeof(payload_len)))
return false;
}
if (!_cws_write(priv, mask, sizeof(mask)))
return false;
return _cws_write_masked(priv, mask, msg, msglen);
}
bool
cws_send(CURL *easy, bool text, const void *msg, size_t msglen)
{
struct cws_data *priv;
char *p = NULL;
curl_easy_getinfo(easy, CURLINFO_PRIVATE, &p); /* checks for char* */
if (!p) {
fprintf(stderr,"not CWS (no CURLINFO_PRIVATE): %p", easy);
return false;
}
priv = (struct cws_data *)p;
return _cws_send(priv, text ? CWS_OPCODE_TEXT : CWS_OPCODE_BINARY,
msg, msglen);
}
bool
cws_ping(CURL *easy, const char *reason, size_t len)
{
struct cws_data *priv;
char *p = NULL;
curl_easy_getinfo(easy, CURLINFO_PRIVATE, &p); /* checks for char* */
if (!p) {
fprintf(stderr,"not CWS (no CURLINFO_PRIVATE): %p", easy);
return false;
}
priv = (struct cws_data *)p;
if (len == SIZE_MAX) {
if (reason)
len = strlen(reason);
else
len = 0;
}
return _cws_send(priv, CWS_OPCODE_PING, reason, len);
}
bool
cws_pong(CURL *easy, const char *reason, size_t len)
{
struct cws_data *priv;
char *p = NULL;
curl_easy_getinfo(easy, CURLINFO_PRIVATE, &p); /* checks for char* */
if (!p) {
fprintf(stderr,"not CWS (no CURLINFO_PRIVATE): %p", easy);
return false;
}
priv = (struct cws_data *)p;
if (len == SIZE_MAX) {
if (reason)
len = strlen(reason);
else
len = 0;
}
return _cws_send(priv, CWS_OPCODE_PONG, reason, len);
}
static void
_cws_cleanup(struct cws_data *priv)
{
CURL *easy;
if (priv->dispatching > 0)
return;
if (!priv->deleted)
return;
easy = priv->easy;
curl_slist_free_all(priv->headers);
free(priv->websocket_protocols.requested);
free(priv->websocket_protocols.received);
free(priv->send.buffer);
free(priv->recv.current.payload);
free(priv->recv.fragmented.payload);
free(priv);
curl_easy_cleanup(easy);
}
bool
cws_close(CURL *easy, enum cws_close_reason reason, const char *reason_text, size_t reason_text_len)
{
struct cws_data *priv;
size_t len;
uint16_t r;
bool ret;
char *p = NULL;
curl_easy_getinfo(easy, CURLINFO_PRIVATE, &p); /* checks for char* */
if (!p) {
fprintf(stderr,"not CWS (no CURLINFO_PRIVATE): %p", easy);
return false;
}
priv = (struct cws_data *)p;
/* give 15 seconds to terminate connection @todo configurable */
long runtime_sec = (long)(time(NULL) - priv->start);
curl_easy_setopt(easy, CURLOPT_TIMEOUT, (long)(runtime_sec + 15L));
if (reason == 0) {
ret = _cws_send(priv, CWS_OPCODE_CLOSE, NULL, 0);
priv->closed = true;
return ret;
}
r = reason;
if (!reason_text)
reason_text = "";
if (reason_text_len == SIZE_MAX)
reason_text_len = strlen(reason_text);
len = sizeof(uint16_t) + reason_text_len;
p = malloc(len);
memcpy(p, &r, sizeof(uint16_t));
_cws_hton(p, sizeof(uint16_t));
if (reason_text_len)
memcpy(p + sizeof(uint16_t), reason_text, reason_text_len);
ret = _cws_send(priv, CWS_OPCODE_CLOSE, p, len);
free(p);
priv->closed = true;
return ret;
}
static void
_cws_check_accept(struct cws_data *priv, const char *buffer, size_t len)
{
priv->accepted = false;
if (len != sizeof(priv->accept_key) - 1) {
fprintf(stderr,"expected %zd bytes, got %zd '%.*s'",
sizeof(priv->accept_key) - 1, len, (int)len, buffer);
return;
}
if (memcmp(priv->accept_key, buffer, len) != 0) {
fprintf(stderr,"invalid accept key '%.*s', expected '%.*s'",
(int)len, buffer, (int)len, priv->accept_key);
return;
}
priv->accepted = true;
}
static void
_cws_check_protocol(struct cws_data *priv, const char *buffer, size_t len)
{
if (priv->websocket_protocols.received)
free(priv->websocket_protocols.received);
priv->websocket_protocols.received = malloc(len + 1);
memcpy(priv->websocket_protocols.received, buffer, len);
priv->websocket_protocols.received[len] = '\0';
}
static void
_cws_check_upgrade(struct cws_data *priv, const char *buffer, size_t len)
{
priv->connection_websocket = false;
if (len == strlen("websocket") &&
strncasecmp(buffer, "websocket", len) != 0) {
fprintf(stderr,"unexpected 'Upgrade: %.*s'. Expected 'Upgrade: websocket'",
(int)len, buffer);
return;
}
priv->connection_websocket = true;
}
static void
_cws_check_connection(struct cws_data *priv, const char *buffer, size_t len)
{
priv->upgraded = false;
if (len == strlen("upgrade") &&
strncasecmp(buffer, "upgrade", len) != 0) {
fprintf(stderr,"unexpected 'Connection: %.*s'. Expected 'Connection: upgrade'",
(int)len, buffer);
return;
}
priv->upgraded = true;
}
static size_t
_cws_receive_header(const char *buffer, size_t count, size_t nitems, void *data)
{
struct cws_data *priv = data;
size_t len = count * nitems;
const struct header_checker {
const char *prefix;
void (*check)(struct cws_data *priv, const char *suffix, size_t suffixlen);
} *itr, header_checkers[] = {
{"Sec-WebSocket-Accept:", _cws_check_accept},
{"Sec-WebSocket-Protocol:", _cws_check_protocol},
{"Connection:", _cws_check_connection},
{"Upgrade:", _cws_check_upgrade},
{NULL, NULL}
};
if (len == 2 && memcmp(buffer, "\r\n", 2) == 0) {
long status;
curl_easy_getinfo(priv->easy, CURLINFO_HTTP_CONNECTCODE, &status);
if (!priv->accepted) {
if (priv->cbs.on_close) {
priv->dispatching++;
priv->cbs.on_close((void *)priv->cbs.data,
priv->easy,
CWS_CLOSE_REASON_SERVER_ERROR,
"server didn't accept the websocket upgrade",
strlen("server didn't accept the websocket upgrade"));
priv->dispatching--;
_cws_cleanup(priv);
}
return 0;
} else {
priv->start = time(NULL);
if (priv->cbs.on_connect) {
priv->dispatching++;
priv->cbs.on_connect((void *)priv->cbs.data,
priv->easy,
STR_OR_EMPTY(priv->websocket_protocols.received));
priv->dispatching--;
_cws_cleanup(priv);
}
return len;
}
}
if (_cws_header_has_prefix(buffer, len, "HTTP/")) {
priv->accepted = false;
priv->upgraded = false;
priv->connection_websocket = false;
if (priv->websocket_protocols.received) {
free(priv->websocket_protocols.received);
priv->websocket_protocols.received = NULL;
}
return len;
}
for (itr = header_checkers; itr->prefix != NULL; itr++) {
if (_cws_header_has_prefix(buffer, len, itr->prefix)) {
size_t prefixlen = strlen(itr->prefix);
size_t valuelen = len - prefixlen;
const char *value = buffer + prefixlen;
_cws_trim(&value, &valuelen);
itr->check(priv, value, valuelen);
}
}
return len;
}
static bool
_cws_dispatch_validate(struct cws_data *priv)
{
if (priv->closed && priv->recv.current.opcode != CWS_OPCODE_CLOSE)
return false;
if (!priv->recv.current.fin && cws_opcode_is_control(priv->recv.current.opcode))
fprintf(stderr,"server sent forbidden fragmented control frame opcode=%#x.",
priv->recv.current.opcode);
else if (priv->recv.current.opcode == CWS_OPCODE_CONTINUATION && priv->recv.fragmented.opcode == 0)
fprintf(stderr,"%s", "server sent continuation frame after non-fragmentable frame");
else
return true;
cws_close(priv->easy, CWS_CLOSE_REASON_PROTOCOL_ERROR, NULL, 0);
return false;
}
static void
_cws_dispatch(struct cws_data *priv)
{
if (!_cws_dispatch_validate(priv))
return;
switch (priv->recv.current.opcode) {
case CWS_OPCODE_CONTINUATION:
if (priv->recv.current.fin) {
if (priv->recv.fragmented.opcode == CWS_OPCODE_TEXT) {
const char *str = (const char *)priv->recv.current.payload;
if (priv->recv.current.used == 0)
str = "";
if (priv->cbs.on_text)
priv->cbs.on_text((void *)priv->cbs.data, priv->easy, str, priv->recv.current.used);
} else if (priv->recv.fragmented.opcode == CWS_OPCODE_BINARY) {
if (priv->cbs.on_binary)
priv->cbs.on_binary((void *)priv->cbs.data, priv->easy, priv->recv.current.payload, priv->recv.current.used);
}
memset(&priv->recv.fragmented, 0, sizeof(priv->recv.fragmented));
} else {
priv->recv.fragmented.payload = priv->recv.current.payload;
priv->recv.fragmented.used = priv->recv.current.used;
priv->recv.fragmented.total = priv->recv.current.total;
priv->recv.current.payload = NULL;
priv->recv.current.used = 0;
priv->recv.current.total = 0;
}
break;
case CWS_OPCODE_TEXT:
if (priv->recv.current.fin) {
const char *str = (const char *)priv->recv.current.payload;
if (priv->recv.current.used == 0)
str = "";
if (priv->cbs.on_text)
priv->cbs.on_text((void *)priv->cbs.data, priv->easy, str, priv->recv.current.used);
} else {
priv->recv.fragmented.payload = priv->recv.current.payload;
priv->recv.fragmented.used = priv->recv.current.used;
priv->recv.fragmented.total = priv->recv.current.total;
priv->recv.fragmented.opcode = priv->recv.current.opcode;
priv->recv.current.payload = NULL;
priv->recv.current.used = 0;
priv->recv.current.total = 0;
priv->recv.current.opcode = 0;
priv->recv.current.fin = 0;
}
break;
case CWS_OPCODE_BINARY:
if (priv->recv.current.fin) {
if (priv->cbs.on_binary)
priv->cbs.on_binary((void *)priv->cbs.data, priv->easy, priv->recv.current.payload, priv->recv.current.used);
} else {
priv->recv.fragmented.payload = priv->recv.current.payload;
priv->recv.fragmented.used = priv->recv.current.used;
priv->recv.fragmented.total = priv->recv.current.total;
priv->recv.fragmented.opcode = priv->recv.current.opcode;
priv->recv.current.payload = NULL;
priv->recv.current.used = 0;
priv->recv.current.total = 0;
priv->recv.current.opcode = 0;
priv->recv.current.fin = 0;
}
break;
case CWS_OPCODE_CLOSE: {
enum cws_close_reason reason = CWS_CLOSE_REASON_NO_REASON;
const char *str = "";
size_t len = priv->recv.current.used;
if (priv->recv.current.used >= sizeof(uint16_t)) {
uint16_t r;
memcpy(&r, priv->recv.current.payload, sizeof(uint16_t));
_cws_ntoh(&r, sizeof(r));
if (!cws_close_reason_is_valid(r)) {
cws_close(priv->easy, CWS_CLOSE_REASON_PROTOCOL_ERROR, "invalid close reason", SIZE_MAX);
r = CWS_CLOSE_REASON_PROTOCOL_ERROR;
}
reason = r;
str = (const char *)priv->recv.current.payload + sizeof(uint16_t);
len = priv->recv.current.used - 2;
} else if (priv->recv.current.used > 0 && priv->recv.current.used < sizeof(uint16_t)) {
cws_close(priv->easy, CWS_CLOSE_REASON_PROTOCOL_ERROR, "invalid close payload length", SIZE_MAX);
}
if (priv->cbs.on_close)
priv->cbs.on_close((void *)priv->cbs.data, priv->easy, reason, str, len);
if (!priv->closed) {
if (reason == CWS_CLOSE_REASON_NO_REASON)
reason = 0;
cws_close(priv->easy, reason, str, len);
}
break;
}
case CWS_OPCODE_PING: {
const char *str = (const char *)priv->recv.current.payload;
if (priv->recv.current.used == 0)
str = "";
if (priv->cbs.on_ping)
priv->cbs.on_ping((void *)priv->cbs.data, priv->easy, str, priv->recv.current.used);
else
cws_pong(priv->easy, str, priv->recv.current.used);
break;
}
case CWS_OPCODE_PONG: {
const char *str = (const char *)priv->recv.current.payload;
if (priv->recv.current.used == 0)
str = "";
if (priv->cbs.on_pong)
priv->cbs.on_pong((void *)priv->cbs.data, priv->easy, str, priv->recv.current.used);
break;
}
default:
fprintf(stderr,"unexpected WebSocket opcode: %#x.", priv->recv.current.opcode);
cws_close(priv->easy, CWS_CLOSE_REASON_PROTOCOL_ERROR, "unexpected opcode", SIZE_MAX);
}
}
static size_t
_cws_process_frame(struct cws_data *priv, const char *buffer, size_t len)
{
size_t used = 0;
while (len > 0 && priv->recv.done < priv->recv.needed) {
uint64_t frame_len;
if (priv->recv.done < priv->recv.needed) {
size_t todo = priv->recv.needed - priv->recv.done;
if (todo > len)
todo = len;
memcpy(priv->recv.tmpbuf + priv->recv.done, buffer, todo);
priv->recv.done += todo;
used += todo;
buffer += todo;
len -= todo;
}
if (priv->recv.needed != priv->recv.done)
continue;
if (priv->recv.needed == sizeof(struct cws_frame_header)) {
struct cws_frame_header fh;
memcpy(&fh, priv->recv.tmpbuf, sizeof(struct cws_frame_header));
priv->recv.current.opcode = fh.opcode;
priv->recv.current.fin = fh.fin;
if (fh._reserved || fh.mask)
cws_close(priv->easy, CWS_CLOSE_REASON_PROTOCOL_ERROR, NULL, 0);
if (fh.payload_len == 126) {
if (cws_opcode_is_control(fh.opcode))
cws_close(priv->easy, CWS_CLOSE_REASON_PROTOCOL_ERROR, NULL, 0);
priv->recv.needed += sizeof(uint16_t);
continue;
} else if (fh.payload_len == 127) {
if (cws_opcode_is_control(fh.opcode))
cws_close(priv->easy, CWS_CLOSE_REASON_PROTOCOL_ERROR, NULL, 0);
priv->recv.needed += sizeof(uint64_t);
continue;
} else
frame_len = fh.payload_len;
} else if (priv->recv.needed == sizeof(struct cws_frame_header) + sizeof(uint16_t)) {
uint16_t plen;
memcpy(&plen,
priv->recv.tmpbuf + sizeof(struct cws_frame_header),
sizeof(plen));
_cws_ntoh(&plen, sizeof(plen));
frame_len = plen;
} else if (priv->recv.needed == sizeof(struct cws_frame_header) + sizeof(uint64_t)) {
uint64_t plen;
memcpy(&plen, priv->recv.tmpbuf + sizeof(struct cws_frame_header),
sizeof(plen));
_cws_ntoh(&plen, sizeof(plen));
frame_len = plen;
} else {
fprintf(stderr,"needed=%u, done=%u", priv->recv.needed, priv->recv.done);
abort();
}
if (priv->recv.current.opcode == CWS_OPCODE_CONTINUATION) {
if (priv->recv.fragmented.opcode == 0)
cws_close(priv->easy, CWS_CLOSE_REASON_PROTOCOL_ERROR, "nothing to continue", SIZE_MAX);
if (priv->recv.current.payload)
free(priv->recv.current.payload);
priv->recv.current.payload = priv->recv.fragmented.payload;
priv->recv.current.used = priv->recv.fragmented.used;
priv->recv.current.total = priv->recv.fragmented.total;
priv->recv.fragmented.payload = NULL;
priv->recv.fragmented.used = 0;
priv->recv.fragmented.total = 0;
} else if (!cws_opcode_is_control(priv->recv.current.opcode) && priv->recv.fragmented.opcode != 0) {
cws_close(priv->easy, CWS_CLOSE_REASON_PROTOCOL_ERROR, "expected continuation or control frames", SIZE_MAX);
}
if (frame_len > 0) {
void *tmp;
tmp = realloc(priv->recv.current.payload,
priv->recv.current.total + frame_len + 1);
if (!tmp) {
cws_close(priv->easy, CWS_CLOSE_REASON_TOO_BIG, NULL, 0);
fprintf(stderr,"%s", "could not allocate memory");
return CURL_READFUNC_ABORT;
}
priv->recv.current.payload = tmp;
priv->recv.current.total += frame_len;
}
}
if (len == 0 && priv->recv.done < priv->recv.needed)
return used;
/* fill payload */
while (len > 0 && priv->recv.current.used < priv->recv.current.total) {
size_t todo = priv->recv.current.total - priv->recv.current.used;
if (todo > len)
todo = len;
memcpy(priv->recv.current.payload + priv->recv.current.used, buffer, todo);
priv->recv.current.used += todo;
used += todo;
buffer += todo;
len -= todo;
}
if (priv->recv.current.payload)
priv->recv.current.payload[priv->recv.current.used] = '\0';
if (len == 0 && priv->recv.current.used < priv->recv.current.total)
return used;
priv->dispatching++;
_cws_dispatch(priv);
priv->recv.done = 0;
priv->recv.needed = sizeof(struct cws_frame_header);
priv->recv.current.used = 0;
priv->recv.current.total = 0;
priv->dispatching--;
_cws_cleanup(priv);
return used;
}
static size_t
_cws_receive_data(const char *buffer, size_t count, size_t nitems, void *data)
{
struct cws_data *priv = data;
size_t len = count * nitems;
while (len > 0) {
size_t used = _cws_process_frame(priv, buffer, len);
len -= used;
buffer += used;
}
return count * nitems;
}
static size_t
_cws_send_data(char *buffer, size_t count, size_t nitems, void *data)
{
struct cws_data *priv = data;
size_t len = count * nitems;
size_t todo = priv->send.len;
if (todo == 0) {
priv->pause_flags |= CURLPAUSE_SEND;
return CURL_READFUNC_PAUSE;
}
if (todo > len)
todo = len;
memcpy(buffer, priv->send.buffer, todo);
if (todo < priv->send.len) {
/* optimization note: we could avoid memmove() by keeping a
* priv->send.position, then we just increment that offset.
*
* on next _cws_write(), check if priv->send.position > 0 and
* memmove() to make some space without realloc().
*/
memmove(priv->send.buffer,
priv->send.buffer + todo,
priv->send.len - todo);
} else {
free(priv->send.buffer);
priv->send.buffer = NULL;
}
priv->send.len -= todo;
return todo;
}
static const char*
_cws_fill_websocket_key(struct cws_data *priv, char key_header[44])
{
uint8_t key[16];
/* 24 bytes of base24 encoded key
* + GUID 258EAFA5-E914-47DA-95CA-C5AB0DC85B11
*/
char buf[60] = "01234567890123456789....258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
uint8_t sha1hash[20];
_cws_get_random(key, sizeof(key));
_cws_encode_base64(key, sizeof(key), buf);
memcpy(key_header + strlen("Sec-WebSocket-Key: "), buf, 24);
_cws_sha1(buf, sizeof(buf), sha1hash);
_cws_encode_base64(sha1hash, sizeof(sha1hash), priv->accept_key);
priv->accept_key[sizeof(priv->accept_key) - 1] = '\0';
return key_header;
}
CURL*
cws_new(const char *url, const char *websocket_protocols, const struct cws_callbacks *callbacks)
{
CURL *easy;
struct cws_data *priv;
char key_header[] = "Sec-WebSocket-Key: 01234567890123456789....";
char *tmp = NULL;
const curl_version_info_data *cver = curl_version_info(CURLVERSION_NOW);
if (cver->version_num < 0x073202)
fprintf(stderr,"CURL version '%s'. At least '7.50.2' is required for WebSocket to work reliably", cver->version);
if (!url)
return NULL;
easy = curl_easy_init();
if (!easy)
return NULL;
priv = calloc(1, sizeof(struct cws_data));
priv->easy = easy;
curl_easy_setopt(easy, CURLOPT_PRIVATE, priv);
curl_easy_setopt(easy, CURLOPT_HEADERFUNCTION, _cws_receive_header);
curl_easy_setopt(easy, CURLOPT_HEADERDATA, priv);
curl_easy_setopt(easy, CURLOPT_WRITEFUNCTION, _cws_receive_data);
curl_easy_setopt(easy, CURLOPT_WRITEDATA, priv);
curl_easy_setopt(easy, CURLOPT_READFUNCTION, _cws_send_data);
curl_easy_setopt(easy, CURLOPT_READDATA, priv);
if (callbacks)
priv->cbs = *callbacks;
priv->recv.needed = sizeof(struct cws_frame_header);
priv->recv.done = 0;
/* curl doesn't support ws:// or wss:// scheme, rewrite to http/https */
if (strncmp(url, "ws://", strlen("ws://")) == 0) {
tmp = malloc(strlen(url) - strlen("ws://") + strlen("http://") + 1);
memcpy(tmp, "http://", strlen("http://"));
memcpy(tmp + strlen("http://"),
url + strlen("ws://"),
strlen(url) - strlen("ws://") + 1);
url = tmp;
} else if (strncmp(url, "wss://", strlen("wss://")) == 0) {
tmp = malloc(strlen(url) - strlen("wss://") + strlen("https://") + 1);
memcpy(tmp, "https://", strlen("https://"));
memcpy(tmp + strlen("https://"),
url + strlen("wss://"),
strlen(url) - strlen("wss://") + 1);
url = tmp;
}
curl_easy_setopt(easy, CURLOPT_URL, url);
free(tmp);
/*
* BEGIN: work around CURL to get WebSocket:
*
* WebSocket must be HTTP/1.1 GET request where we must keep the
* "send" part alive without any content-length and no chunked
* encoding and the server answer is 101-upgrade.
*/
curl_easy_setopt(easy, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
/* Use CURLOPT_UPLOAD=1 to force "send" even with a GET request,
* however it will set HTTP request to PUT
*/
curl_easy_setopt(easy, CURLOPT_UPLOAD, 1L);
/*
* Then we manually override the string sent to be "GET".
*/
curl_easy_setopt(easy, CURLOPT_CUSTOMREQUEST, "GET");
#if 0
/*
* CURLOPT_UPLOAD=1 with HTTP/1.1 implies:
* Expect: 100-continue
* but we don't want that, rather 101. Then force: 101.
*/
priv->headers = curl_slist_append(priv->headers, "Expect: 101");
#else
/*
* This disables a automatic CURL behaviour where we receive a
* error if the server can't be bothered to send just a header
* with a 100 response code (https://stackoverflow.com/questions/9120760/curl-simple-file-upload-417-expectation-failed/19250636")
*/
priv->headers = curl_slist_append(priv->headers, "Expect:");
#endif
/*
* CURLOPT_UPLOAD=1 without a size implies in:
* Transfer-Encoding: chunked
* but we don't want that, rather unmodified (raw) bites as we're
* doing the websockets framing ourselves. Force nothing.
*/
priv->headers = curl_slist_append(priv->headers, "Transfer-Encoding:");
/* END: work around CURL to get WebSocket. */
/* regular mandatory WebSockets headers */
priv->headers = curl_slist_append(priv->headers, "Connection: Upgrade");
priv->headers = curl_slist_append(priv->headers, "Upgrade: websocket");
priv->headers = curl_slist_append(priv->headers, "Sec-WebSocket-Version: 13");
/* Sec-WebSocket-Key: <24-bytes-base64-of-random-key> */
priv->headers = curl_slist_append(priv->headers, _cws_fill_websocket_key(priv, key_header));
if (websocket_protocols) {
char *tmp = malloc(strlen("Sec-WebSocket-Protocol: ") +
strlen(websocket_protocols) + 1);
memcpy(tmp,
"Sec-WebSocket-Protocol: ",
strlen("Sec-WebSocket-Protocol: "));
memcpy(tmp + strlen("Sec-WebSocket-Protocol: "),
websocket_protocols,
strlen(websocket_protocols) + 1);
priv->headers = curl_slist_append(priv->headers, tmp);
free(tmp);
priv->websocket_protocols.requested = strdup(websocket_protocols);
}
curl_easy_setopt(easy, CURLOPT_HTTPHEADER, priv->headers);
return easy;
}
void
cws_free(CURL *easy)
{
struct cws_data *priv;
char *p = NULL;
curl_easy_getinfo(easy, CURLINFO_PRIVATE, &p); /* checks for char* */
if (!p)
return;
priv = (struct cws_data *)p;
priv->deleted = true;
_cws_cleanup(priv);
}
void
cws_add_header(CURL *easy, const char field[], const char value[])
{
struct cws_data *priv;
char *p = NULL;
char buf[4096];
size_t bufret;
size_t field_len;
curl_easy_getinfo(easy, CURLINFO_PRIVATE, &p); /* checks for char* */
if (!p)
return;
priv = (struct cws_data *)p;
bufret = snprintf(buf, sizeof(buf), "%s: %s", field, value);
if (bufret >= sizeof(buf)) {
fprintf(stderr, "Out of bounds write attempt\n");
abort();
}
/* check for match in existing fields */
field_len = strlen(field);
struct curl_slist *node = priv->headers;
while (NULL != node) {
if (!(p = strchr(node->data, ':'))) {
fprintf(stderr, "Missing ':' in header:\n\t%s\n", node->data);
abort();
}
if (field_len == p - node->data
&& 0 == strncasecmp(node->data, field, field_len))
{
if (strlen(node->data) < bufret) {
free(node->data);
node->data = strdup(buf);
}
else {
memcpy(node->data, buf, bufret+1);
}
return; /* EARLY RETURN */
}
node = node->next;
}
curl_slist_append(priv->headers, buf);
}
|
zyedidia/joy
| 1
|
A framework for building 2D desktop games in JavaScript, with a Love2D-inspired API
|
C++
|
zyedidia
|
Zachary Yedidia
|
Stanford University
|
src/web-api/curl-websocket.h
|
C/C++ Header
|
/* clang-format off */
/*
* Copyright (C) 2016 Gustavo Sverzut Barbieri
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/* c-mode: linux-4 */
#ifndef _CURL_WEBSOCKET_H_
#define _CURL_WEBSOCKET_H_ 1
#include <curl/curl.h>
#include <string.h>
#include <stdbool.h>
#ifdef __cplusplus
extern "C" {
#endif
/* see https://tools.ietf.org/html/rfc6455#section-7.4.1 */
enum cws_close_reason {
CWS_CLOSE_REASON_NORMAL = 1000,
CWS_CLOSE_REASON_GOING_AWAY = 1001,
CWS_CLOSE_REASON_PROTOCOL_ERROR = 1002,
CWS_CLOSE_REASON_UNEXPECTED_DATA = 1003,
CWS_CLOSE_REASON_NO_REASON = 1005,
CWS_CLOSE_REASON_ABRUPTLY = 1006,
CWS_CLOSE_REASON_INCONSISTENT_DATA = 1007,
CWS_CLOSE_REASON_POLICY_VIOLATION = 1008,
CWS_CLOSE_REASON_TOO_BIG = 1009,
CWS_CLOSE_REASON_MISSING_EXTENSION = 1010,
CWS_CLOSE_REASON_SERVER_ERROR = 1011,
CWS_CLOSE_REASON_IANA_REGISTRY_START = 3000,
CWS_CLOSE_REASON_IANA_REGISTRY_END = 3999,
CWS_CLOSE_REASON_PRIVATE_START = 4000,
CWS_CLOSE_REASON_PRIVATE_END = 4999
};
struct cws_callbacks {
/**
* called upon connection, websocket_protocols contains what
* server reported as 'Sec-WebSocket-Protocol:'.
*
* @note It is not validated if matches the proposed protocols.
*/
void (*on_connect)(void *data, CURL *easy, const char *websocket_protocols);
/**
* reports UTF-8 text messages.
*
* @note it's guaranteed to be NULL (\0) terminated, but the UTF-8 is
* not validated. If it's invalid, consider closing the connection
* with #CWS_CLOSE_REASON_INCONSISTENT_DATA.
*/
void (*on_text)(void *data, CURL *easy, const char *text, size_t len);
/**
* reports binary data.
*/
void (*on_binary)(void *data, CURL *easy, const void *mem, size_t len);
/**
* reports PING.
*
* @note if provided you should reply with cws_pong(). If not
* provided, pong is sent with the same message payload.
*/
void (*on_ping)(void *data, CURL *easy, const char *reason, size_t len);
/**
* reports PONG.
*/
void (*on_pong)(void *data, CURL *easy, const char *reason, size_t len);
/**
* reports server closed the connection with the given reason.
*
* Clients should not transmit any more data after the server is
* closed, just call cws_free().
*/
void (*on_close)(void *data, CURL *easy, enum cws_close_reason reason, const char *reason_text, size_t reason_text_len);
const void *data;
};
/**
* Create a new CURL-based WebSocket handle.
*
* This is a regular CURL easy handle properly setup to do
* WebSocket. You can add more headers and cookies, but do @b not mess
* with the following headers:
* @li Content-Length
* @li Content-Type
* @li Transfer-Encoding
* @li Connection
* @li Upgrade
* @li Expect
* @li Sec-WebSocket-Version
* @li Sec-WebSocket-Key
*
* And do not change the HTTP method or version, callbacks (read,
* write or header) or private data.
*
* @param url the URL to connect, such as ws://echo.websockets.org
* @param websocket_protocols #NULL or something like "chat", "superchat"...
* @param callbacks set of functions to call back when server report events.
*
* @return newly created CURL easy handle, free with cws_free()
*/
CURL *cws_new(const char *url, const char *websocket_protocols, const struct cws_callbacks *callbacks);
/**
* Free a handle created with cws_new()
*/
void cws_free(CURL *easy);
/**
* Send a text or binary message of given size.
*
* Text messages do not need to include the null terminator (\0), they
* will be read up to @a msglen.
*
* @param easy the CURL easy handle created with cws_new()
* @param text if #true, opcode will be 0x1 (text-frame), otherwise
* opcode will be 0x2 (binary-frame).
* @param msg the pointer to memory (linear) to send.
* @param msglen the length in bytes of @a msg.
*
* @return #true if sent, #false on errors.
*
* @see cws_send_binary()
* @see cws_send_text()
*/
bool cws_send(CURL *easy, bool text, const void *msg, size_t msglen);
/**
* Helper over cws_send() to send binary messages.
*/
static inline bool cws_send_binary(CURL *easy, const void *msg, size_t msglen) {
return cws_send(easy, false, msg, msglen);
}
/**
* Helper over cws_send() to send text (UTF-8) messages, will use
* strlen() on string.
*/
static inline bool cws_send_text(CURL *easy, const char *string) {
return cws_send(easy, true, string, strlen(string));
}
/**
* Send a PING (opcode 0x9) frame with @a reason as payload.
*
* @param easy the CURL easy handle created with cws_new()
* @param reason #NULL or some UTF-8 string null ('\0') terminated.
* @param len the length of @a reason in bytes. If #SIZE_MAX, uses
* strlen() on @a reason if it's not #NULL.
* @return #true if sent, #false on errors.
*/
bool cws_ping(CURL *easy, const char *reason, size_t len);
/**
* Send a PONG (opcode 0xA) frame with @a reason as payload.
*
* Note that pong is sent automatically if no "on_ping" callback is
* defined. If one is defined you must send pong manually.
*
* @param easy the CURL easy handle created with cws_new()
* @param reason #NULL or some UTF-8 string null ('\0') terminated.
* @param len the length of @a reason in bytes. If #SIZE_MAX, uses
* strlen() on @a reason if it's not #NULL.
* @return #true if sent, #false on errors.
*/
bool cws_pong(CURL *easy, const char *reason, size_t len);
/**
* Send a CLOSE (opcode 0x8) frame with @a reason as payload.
*
* @param easy the CURL easy handle created with cws_new()
* @param reason the reason why it was closed, see the well-known numbers.
* @param reason_text #NULL or some UTF-8 string null ('\0') terminated.
* @param reason_text_len the length of @a reason_text in bytes. If
* #SIZE_MAX, uses strlen() on @a reason_text if it's not
* #NULL.
* @return #true if sent, #false on errors.
*/
bool cws_close(CURL *easy, enum cws_close_reason reason, const char *reason_text, size_t reason_text_len);
/**
* Add a header field/value pair
*
* @param easy the CURL easy handle created with cws_new()
* @param field the header field
* @param value the header value
*/
void cws_add_header(CURL *easy, const char field[], const char value[]);
#ifdef __cplusplus
}
#endif
#endif
|
zyedidia/joy
| 1
|
A framework for building 2D desktop games in JavaScript, with a Love2D-inspired API
|
C++
|
zyedidia
|
Zachary Yedidia
|
Stanford University
|
src/web-api/message_queue.hh
|
C++ Header
|
#pragma once
#include <mutex>
#include <queue>
#include <vector>
#include <string>
#include <cstdint>
namespace joy::webapi {
// Serialized message for cross-thread transfer
// Data is serialized using JS_WriteObject2/JS_ReadObject2
struct SerializedMessage {
std::vector<uint8_t> data;
bool is_error = false;
std::string error_msg;
SerializedMessage() = default;
SerializedMessage(std::vector<uint8_t> d) : data(std::move(d)) {}
SerializedMessage(const std::string &err) : is_error(true), error_msg(err) {}
};
// Thread-safe queue for inter-thread message passing
class MessageQueue {
public:
MessageQueue() = default;
~MessageQueue() = default;
// Non-copyable
MessageQueue(const MessageQueue &) = delete;
MessageQueue &operator=(const MessageQueue &) = delete;
// Push a message to the queue (thread-safe)
void push(SerializedMessage msg) {
std::lock_guard<std::mutex> lock(mutex_);
queue_.push(std::move(msg));
}
// Try to pop a message from the queue (thread-safe)
// Returns true if a message was popped, false if queue was empty
bool tryPop(SerializedMessage &out) {
std::lock_guard<std::mutex> lock(mutex_);
if (queue_.empty()) {
return false;
}
out = std::move(queue_.front());
queue_.pop();
return true;
}
// Check if queue is empty (thread-safe, but may be stale)
bool empty() const {
std::lock_guard<std::mutex> lock(mutex_);
return queue_.empty();
}
private:
mutable std::mutex mutex_;
std::queue<SerializedMessage> queue_;
};
} // namespace joy::webapi
|
zyedidia/joy
| 1
|
A framework for building 2D desktop games in JavaScript, with a Love2D-inspired API
|
C++
|
zyedidia
|
Zachary Yedidia
|
Stanford University
|
src/web-api/websocket.cc
|
C++
|
#include "websocket.hh"
#include "engine.hh"
#include "curl-websocket.h"
#include <cstring>
#include <cstdlib>
namespace joy::webapi {
// WebSocket ready states (matches browser API)
enum {
WS_STATE_CONNECTING = 0,
WS_STATE_OPEN = 1,
WS_STATE_CLOSING = 2,
WS_STATE_CLOSED = 3
};
// Event indices
enum {
WS_EVENT_OPEN = 0,
WS_EVENT_MESSAGE = 1,
WS_EVENT_CLOSE = 2,
WS_EVENT_ERROR = 3,
WS_EVENT_MAX = 4
};
// WebSocket instance data
struct WebSocketData {
js::PersistentValue this_ref; // Self-reference (prevents GC while active)
js::PersistentValue events[WS_EVENT_MAX]; // onopen, onmessage, onclose, onerror
js::PersistentValue url_val; // Original URL string
js::PersistentValue protocol_val; // Negotiated protocol
void *raw_ctx; // Raw context pointer for curl callbacks
CURL *curl_h;
CURLM *curlm_h;
WebSocket *module; // Pointer to module for handle tracking
unsigned short ready_state;
struct cws_callbacks ws_callbacks;
WebSocketData() : raw_ctx(nullptr), curl_h(nullptr), curlm_h(nullptr),
module(nullptr), ready_state(WS_STATE_CONNECTING) {
memset(&ws_callbacks, 0, sizeof(ws_callbacks));
}
~WebSocketData() {
if (curl_h) {
if (module) {
module->unregisterHandle(curl_h);
}
if (curlm_h) {
curl_multi_remove_handle(curlm_h, curl_h);
}
cws_free(curl_h);
}
}
};
// Get WebSocketData from this value
static WebSocketData *getWebSocketData(js::FunctionArgs &args) {
js::Value thisVal = args.thisValue();
return static_cast<WebSocketData *>(thisVal.getInternalField(0));
}
// Emit event to JS callback (called from curl callbacks)
static void emit_event(WebSocketData *ws, int event_idx, js::Value event) {
if (ws->events[event_idx].isEmpty()) {
return;
}
// Create wrapper context for the call
js::Context ctx = js::Context::wrapRaw(nullptr, ws->raw_ctx);
js::Value callback = ws->events[event_idx].get(ctx);
if (!callback.isFunction()) {
return;
}
js::Value thisVal = ws->this_ref.get(ctx);
js::Value result = ctx.call(callback, thisVal, &event, 1);
if (result.isException()) {
js::Value exception = ctx.getException();
std::string err = exception.toString(ctx);
fprintf(stderr, "WebSocket callback error: %s\n", err.c_str());
}
}
// curl-websocket callback: connection established
static void cws_on_connect(void *data, CURL *easy, const char *websocket_protocols) {
WebSocketData *ws = static_cast<WebSocketData *>(data);
ws->ready_state = WS_STATE_OPEN;
js::Context ctx = js::Context::wrapRaw(nullptr, ws->raw_ctx);
// Store negotiated protocol
ws->protocol_val.reset(ctx, js::Value::string(ctx, websocket_protocols ? websocket_protocols : ""));
// Create event object
js::Value event = js::Value::object(ctx);
event.setProperty(ctx, "type", js::Value::string(ctx, "open"));
emit_event(ws, WS_EVENT_OPEN, std::move(event));
}
// curl-websocket callback: text message received
static void cws_on_text(void *data, CURL *easy, const char *text, size_t len) {
WebSocketData *ws = static_cast<WebSocketData *>(data);
js::Context ctx = js::Context::wrapRaw(nullptr, ws->raw_ctx);
// Create MessageEvent-like object
js::Value event = js::Value::object(ctx);
event.setProperty(ctx, "type", js::Value::string(ctx, "message"));
event.setProperty(ctx, "data", js::Value::string(ctx, text, len));
emit_event(ws, WS_EVENT_MESSAGE, std::move(event));
}
// curl-websocket callback: binary message received
static void cws_on_binary(void *data, CURL *easy, const void *mem, size_t len) {
WebSocketData *ws = static_cast<WebSocketData *>(data);
js::Context ctx = js::Context::wrapRaw(nullptr, ws->raw_ctx);
// Create MessageEvent-like object with ArrayBuffer
js::Value event = js::Value::object(ctx);
event.setProperty(ctx, "type", js::Value::string(ctx, "message"));
event.setProperty(ctx, "data", js::Value::arrayBuffer(ctx, mem, len));
emit_event(ws, WS_EVENT_MESSAGE, std::move(event));
}
// curl-websocket callback: connection closed
static void cws_on_close(void *data, CURL *easy, enum cws_close_reason reason,
const char *reason_text, size_t reason_text_len) {
WebSocketData *ws = static_cast<WebSocketData *>(data);
ws->ready_state = WS_STATE_CLOSED;
js::Context ctx = js::Context::wrapRaw(nullptr, ws->raw_ctx);
// Create CloseEvent-like object
js::Value event = js::Value::object(ctx);
event.setProperty(ctx, "type", js::Value::string(ctx, "close"));
event.setProperty(ctx, "code", js::Value::number(static_cast<int32_t>(reason)));
event.setProperty(ctx, "reason", js::Value::string(ctx, reason_text, reason_text_len));
event.setProperty(ctx, "wasClean", js::Value::boolean(reason == CWS_CLOSE_REASON_NORMAL));
emit_event(ws, WS_EVENT_CLOSE, std::move(event));
}
// Destructor for WebSocket instances
static void websocket_destructor(void *opaque) {
WebSocketData *ws = static_cast<WebSocketData *>(opaque);
delete ws;
}
// WebSocket constructor
static void js_websocket_constructor(js::ConstructorArgs &args) {
if (args.length() < 1) {
args.throwSyntaxError("WebSocket constructor requires a URL");
return;
}
// Get URL
std::string url = args.arg(0).toString(args.context());
// Validate URL scheme
if (url.substr(0, 5) != "ws://" && url.substr(0, 6) != "wss://") {
args.throwSyntaxError("WebSocket URL must start with ws:// or wss://");
return;
}
// Get protocols (optional)
std::string protocols;
if (args.length() >= 2) {
js::Value protocolArg = args.arg(1);
if (!protocolArg.isUndefined() && !protocolArg.isNull()) {
if (!protocolArg.isArray()) {
protocols = protocolArg.toString(args.context());
}
// TODO: Handle array of protocols by joining with comma
}
}
// Get engine
Engine *engine = args.getContextOpaque<Engine>();
if (!engine || !engine->getWebSocketModule()) {
args.throwError("WebSocket module not initialized");
return;
}
// Create instance
js::Value instance = args.createInstance();
// Allocate WebSocket data
WebSocketData *ws = new WebSocketData();
ws->raw_ctx = args.context().raw();
ws->module = engine->getWebSocketModule();
ws->curlm_h = ws->module->getCurlMulti();
// Store references
ws->this_ref = js::PersistentValue(args.context(), instance);
ws->url_val = js::PersistentValue(args.context(), js::Value::string(args.context(), url.c_str()));
ws->protocol_val = js::PersistentValue(args.context(), js::Value::string(args.context(), ""));
// Setup curl-websocket callbacks
ws->ws_callbacks.on_connect = cws_on_connect;
ws->ws_callbacks.on_text = cws_on_text;
ws->ws_callbacks.on_binary = cws_on_binary;
ws->ws_callbacks.on_close = cws_on_close;
ws->ws_callbacks.on_ping = nullptr; // Auto-pong
ws->ws_callbacks.on_pong = nullptr;
ws->ws_callbacks.data = ws;
// Create curl-websocket connection
ws->curl_h = cws_new(url.c_str(), protocols.empty() ? nullptr : protocols.c_str(), &ws->ws_callbacks);
if (!ws->curl_h) {
delete ws;
args.throwError("Failed to create WebSocket connection");
return;
}
// Register for connection error handling
ws->module->registerHandle(ws->curl_h, ws);
// Add to multi handle
curl_multi_add_handle(ws->curlm_h, ws->curl_h);
instance.setInternalField(0, ws);
args.returnValue(std::move(instance));
}
// send(data) - send text or binary data
static void js_websocket_send(js::FunctionArgs &args) {
WebSocketData *ws = getWebSocketData(args);
if (!ws) {
args.throwError("Invalid WebSocket");
return;
}
if (ws->ready_state != WS_STATE_OPEN) {
args.throwError("WebSocket is not open");
return;
}
if (args.length() < 1) {
args.returnUndefined();
return;
}
js::Value data = args.arg(0);
if (data.isString()) {
std::string text = data.toString(args.context());
cws_send_text(ws->curl_h, text.c_str());
} else if (data.isArrayBuffer()) {
void *buf = data.arrayBufferData();
size_t size = data.arrayBufferLength();
if (buf) {
cws_send_binary(ws->curl_h, buf, size);
}
} else if (data.isTypedArray()) {
js::Value buffer = data.typedArrayBuffer(args.context());
void *buf = buffer.arrayBufferData();
size_t offset = data.typedArrayByteOffset();
size_t length = data.typedArrayByteLength();
if (buf) {
cws_send_binary(ws->curl_h, static_cast<uint8_t *>(buf) + offset, length);
}
}
args.returnUndefined();
}
// close(code, reason) - close the connection
static void js_websocket_close(js::FunctionArgs &args) {
WebSocketData *ws = getWebSocketData(args);
if (!ws) {
args.throwError("Invalid WebSocket");
return;
}
if (ws->ready_state >= WS_STATE_CLOSING) {
args.returnUndefined(); // Already closing/closed
return;
}
int code = 1000; // Normal closure
std::string reason;
if (args.length() >= 1) {
js::Value codeArg = args.arg(0);
if (!codeArg.isUndefined()) {
code = codeArg.toInt32();
// Validate code (must be 1000 or 3000-4999)
if (code != 1000 && (code < 3000 || code > 4999)) {
args.throwRangeError("Invalid close code: must be 1000 or 3000-4999");
return;
}
}
}
if (args.length() >= 2) {
js::Value reasonArg = args.arg(1);
if (!reasonArg.isUndefined()) {
reason = reasonArg.toString(args.context());
// Validate reason length (max 123 bytes per spec)
if (reason.length() > 123) {
args.throwSyntaxError("Close reason too long (max 123 bytes)");
return;
}
}
}
ws->ready_state = WS_STATE_CLOSING;
cws_close(ws->curl_h, static_cast<cws_close_reason>(code), reason.c_str(), reason.length());
args.returnUndefined();
}
// Getter for readyState
static void js_websocket_get_readyState(js::FunctionArgs &args) {
WebSocketData *ws = getWebSocketData(args);
if (!ws) {
args.throwError("Invalid WebSocket");
return;
}
args.returnValue(js::Value::number(static_cast<int32_t>(ws->ready_state)));
}
// Getter for url
static void js_websocket_get_url(js::FunctionArgs &args) {
WebSocketData *ws = getWebSocketData(args);
if (!ws) {
args.throwError("Invalid WebSocket");
return;
}
args.returnValue(ws->url_val.get(args.context()));
}
// Getter for protocol
static void js_websocket_get_protocol(js::FunctionArgs &args) {
WebSocketData *ws = getWebSocketData(args);
if (!ws) {
args.throwError("Invalid WebSocket");
return;
}
args.returnValue(ws->protocol_val.get(args.context()));
}
// Event handler getters/setters
static void js_websocket_get_onopen(js::FunctionArgs &args) {
WebSocketData *ws = getWebSocketData(args);
if (!ws) { args.returnUndefined(); return; }
args.returnValue(ws->events[WS_EVENT_OPEN].get(args.context()));
}
static void js_websocket_set_onopen(js::FunctionArgs &args) {
WebSocketData *ws = getWebSocketData(args);
if (!ws || args.length() < 1) { args.returnUndefined(); return; }
js::Value val = args.arg(0);
if (val.isFunction() || val.isUndefined() || val.isNull()) {
ws->events[WS_EVENT_OPEN].reset(args.context(), val);
}
args.returnUndefined();
}
static void js_websocket_get_onmessage(js::FunctionArgs &args) {
WebSocketData *ws = getWebSocketData(args);
if (!ws) { args.returnUndefined(); return; }
args.returnValue(ws->events[WS_EVENT_MESSAGE].get(args.context()));
}
static void js_websocket_set_onmessage(js::FunctionArgs &args) {
WebSocketData *ws = getWebSocketData(args);
if (!ws || args.length() < 1) { args.returnUndefined(); return; }
js::Value val = args.arg(0);
if (val.isFunction() || val.isUndefined() || val.isNull()) {
ws->events[WS_EVENT_MESSAGE].reset(args.context(), val);
}
args.returnUndefined();
}
static void js_websocket_get_onclose(js::FunctionArgs &args) {
WebSocketData *ws = getWebSocketData(args);
if (!ws) { args.returnUndefined(); return; }
args.returnValue(ws->events[WS_EVENT_CLOSE].get(args.context()));
}
static void js_websocket_set_onclose(js::FunctionArgs &args) {
WebSocketData *ws = getWebSocketData(args);
if (!ws || args.length() < 1) { args.returnUndefined(); return; }
js::Value val = args.arg(0);
if (val.isFunction() || val.isUndefined() || val.isNull()) {
ws->events[WS_EVENT_CLOSE].reset(args.context(), val);
}
args.returnUndefined();
}
static void js_websocket_get_onerror(js::FunctionArgs &args) {
WebSocketData *ws = getWebSocketData(args);
if (!ws) { args.returnUndefined(); return; }
args.returnValue(ws->events[WS_EVENT_ERROR].get(args.context()));
}
static void js_websocket_set_onerror(js::FunctionArgs &args) {
WebSocketData *ws = getWebSocketData(args);
if (!ws || args.length() < 1) { args.returnUndefined(); return; }
js::Value val = args.arg(0);
if (val.isFunction() || val.isUndefined() || val.isNull()) {
ws->events[WS_EVENT_ERROR].reset(args.context(), val);
}
args.returnUndefined();
}
// Module initialization
WebSocket::WebSocket(Engine *engine) : engine_(engine), curlm_(nullptr) {
// Initialize curl globally if not already done
static bool curl_initialized = false;
if (!curl_initialized) {
curl_global_init(CURL_GLOBAL_DEFAULT);
curl_initialized = true;
}
// Create curl multi handle
curlm_ = curl_multi_init();
}
WebSocket::~WebSocket() {
if (curlm_) {
curl_multi_cleanup(curlm_);
}
}
void WebSocket::registerHandle(CURL *handle, WebSocketData *ws) {
handle_map_[handle] = ws;
}
void WebSocket::unregisterHandle(CURL *handle) {
handle_map_.erase(handle);
}
void WebSocket::update() {
if (!curlm_) return;
int running_handles;
curl_multi_perform(curlm_, &running_handles);
// Process any completed transfers
CURLMsg *msg;
int msgs_left;
while ((msg = curl_multi_info_read(curlm_, &msgs_left))) {
if (msg->msg == CURLMSG_DONE) {
CURL *easy = msg->easy_handle;
CURLcode result = msg->data.result;
// Find the WebSocketData for this handle
auto it = handle_map_.find(easy);
if (it != handle_map_.end()) {
WebSocketData *ws = it->second;
// Only emit events if not already closed
if (ws->ready_state != WS_STATE_CLOSED) {
ws->ready_state = WS_STATE_CLOSED;
js::Context ctx = js::Context::wrapRaw(nullptr, ws->raw_ctx);
// Emit error event if there was a curl error
if (result != CURLE_OK) {
js::Value error_event = js::Value::object(ctx);
error_event.setProperty(ctx, "type", js::Value::string(ctx, "error"));
emit_event(ws, WS_EVENT_ERROR, std::move(error_event));
}
// Emit close event
js::Value close_event = js::Value::object(ctx);
close_event.setProperty(ctx, "type", js::Value::string(ctx, "close"));
close_event.setProperty(ctx, "code", js::Value::number(result == CURLE_OK ? 1000 : 1006));
close_event.setProperty(ctx, "reason", js::Value::string(ctx, result == CURLE_OK ? "" : curl_easy_strerror(result)));
close_event.setProperty(ctx, "wasClean", js::Value::boolean(result == CURLE_OK));
emit_event(ws, WS_EVENT_CLOSE, std::move(close_event));
}
}
}
}
}
void WebSocket::initJS(js::Context &ctx, js::Value &global) {
js::ConstructorBuilder(ctx, "WebSocket")
.constructor(js_websocket_constructor, 2)
.finalizer(websocket_destructor)
.internalFieldCount(1)
.prototypeMethod("send", js_websocket_send, 1)
.prototypeMethod("close", js_websocket_close, 2)
.prototypeGetter("readyState", js_websocket_get_readyState)
.prototypeGetter("url", js_websocket_get_url)
.prototypeGetter("protocol", js_websocket_get_protocol)
.prototypeAccessor("onopen", js_websocket_get_onopen, js_websocket_set_onopen)
.prototypeAccessor("onmessage", js_websocket_get_onmessage, js_websocket_set_onmessage)
.prototypeAccessor("onclose", js_websocket_get_onclose, js_websocket_set_onclose)
.prototypeAccessor("onerror", js_websocket_get_onerror, js_websocket_set_onerror)
.staticConstant("CONNECTING", WS_STATE_CONNECTING)
.staticConstant("OPEN", WS_STATE_OPEN)
.staticConstant("CLOSING", WS_STATE_CLOSING)
.staticConstant("CLOSED", WS_STATE_CLOSED)
.attachTo(global);
}
} // namespace joy::webapi
|
zyedidia/joy
| 1
|
A framework for building 2D desktop games in JavaScript, with a Love2D-inspired API
|
C++
|
zyedidia
|
Zachary Yedidia
|
Stanford University
|
src/web-api/websocket.hh
|
C++ Header
|
#pragma once
#include "js/js.hh"
#ifndef __EMSCRIPTEN__
#include <curl/curl.h>
#include <unordered_map>
#endif
namespace joy {
class Engine;
namespace webapi {
// Forward declaration
struct WebSocketData;
class WebSocket {
public:
WebSocket(Engine *engine);
~WebSocket();
// Called each frame to pump curl_multi (desktop only)
void update();
// Register WebSocket constructor on global object
static void initJS(js::Context &ctx, js::Value &global);
#ifndef __EMSCRIPTEN__
CURLM *getCurlMulti() { return curlm_; }
// Track CURL handles for connection error handling
void registerHandle(CURL *handle, WebSocketData *ws);
void unregisterHandle(CURL *handle);
#endif
private:
Engine *engine_;
#ifndef __EMSCRIPTEN__
CURLM *curlm_; // Shared curl multi handle
std::unordered_map<CURL*, WebSocketData*> handle_map_;
#endif
};
} // namespace webapi
} // namespace joy
|
zyedidia/joy
| 1
|
A framework for building 2D desktop games in JavaScript, with a Love2D-inspired API
|
C++
|
zyedidia
|
Zachary Yedidia
|
Stanford University
|
src/web-api/websocket_emscripten.cc
|
C++
|
#include "websocket.hh"
#include "engine.hh"
#include <emscripten/websocket.h>
#include <cstring>
#include <cstdlib>
namespace joy::webapi {
// WebSocket ready states (matches browser API)
enum {
WS_STATE_CONNECTING = 0,
WS_STATE_OPEN = 1,
WS_STATE_CLOSING = 2,
WS_STATE_CLOSED = 3
};
// Event indices
enum {
WS_EVENT_OPEN = 0,
WS_EVENT_MESSAGE = 1,
WS_EVENT_CLOSE = 2,
WS_EVENT_ERROR = 3,
WS_EVENT_MAX = 4
};
// WebSocket instance data
struct WebSocketData {
js::PersistentValue this_ref; // Self-reference (prevents GC while active)
js::PersistentValue events[WS_EVENT_MAX]; // onopen, onmessage, onclose, onerror
js::PersistentValue url_val; // Original URL string
js::PersistentValue protocol_val; // Negotiated protocol
void *raw_ctx; // Raw context pointer for emscripten callbacks
EMSCRIPTEN_WEBSOCKET_T socket; // Emscripten WebSocket handle
unsigned short ready_state;
WebSocketData() : raw_ctx(nullptr), socket(0), ready_state(WS_STATE_CONNECTING) {}
~WebSocketData() {
if (socket) {
emscripten_websocket_close(socket, 1000, "");
emscripten_websocket_delete(socket);
}
}
};
// Get WebSocketData from this value
static WebSocketData *getWebSocketData(js::FunctionArgs &args) {
js::Value thisVal = args.thisValue();
return static_cast<WebSocketData *>(thisVal.getInternalField(0));
}
// Emit event to JS callback
static void emit_event(WebSocketData *ws, int event_idx, js::Value event) {
if (ws->events[event_idx].isEmpty()) {
return;
}
js::Context ctx = js::Context::wrapRaw(nullptr, ws->raw_ctx);
js::Value callback = ws->events[event_idx].get(ctx);
if (!callback.isFunction()) {
return;
}
js::Value thisVal = ws->this_ref.get(ctx);
js::Value result = ctx.call(callback, thisVal, &event, 1);
if (result.isException()) {
js::Value exception = ctx.getException();
std::string err = exception.toString(ctx);
fprintf(stderr, "WebSocket callback error: %s\n", err.c_str());
}
}
// Emscripten callback: connection opened
static EM_BOOL on_open(int eventType, const EmscriptenWebSocketOpenEvent *e, void *userData) {
WebSocketData *ws = static_cast<WebSocketData *>(userData);
ws->ready_state = WS_STATE_OPEN;
js::Context ctx = js::Context::wrapRaw(nullptr, ws->raw_ctx);
// Create event object
js::Value event = js::Value::object(ctx);
event.setProperty(ctx, "type", js::Value::string(ctx, "open"));
emit_event(ws, WS_EVENT_OPEN, std::move(event));
return EM_TRUE;
}
// Emscripten callback: message received
static EM_BOOL on_message(int eventType, const EmscriptenWebSocketMessageEvent *e, void *userData) {
WebSocketData *ws = static_cast<WebSocketData *>(userData);
js::Context ctx = js::Context::wrapRaw(nullptr, ws->raw_ctx);
// Create MessageEvent-like object
js::Value event = js::Value::object(ctx);
event.setProperty(ctx, "type", js::Value::string(ctx, "message"));
if (e->isText) {
// Text message
event.setProperty(ctx, "data", js::Value::string(ctx, (const char *)e->data, e->numBytes));
} else {
// Binary message - create ArrayBuffer
event.setProperty(ctx, "data", js::Value::arrayBuffer(ctx, e->data, e->numBytes));
}
emit_event(ws, WS_EVENT_MESSAGE, std::move(event));
return EM_TRUE;
}
// Emscripten callback: connection closed
static EM_BOOL on_close(int eventType, const EmscriptenWebSocketCloseEvent *e, void *userData) {
WebSocketData *ws = static_cast<WebSocketData *>(userData);
ws->ready_state = WS_STATE_CLOSED;
js::Context ctx = js::Context::wrapRaw(nullptr, ws->raw_ctx);
// Create CloseEvent-like object
js::Value event = js::Value::object(ctx);
event.setProperty(ctx, "type", js::Value::string(ctx, "close"));
event.setProperty(ctx, "code", js::Value::number(static_cast<int32_t>(e->code)));
event.setProperty(ctx, "reason", js::Value::string(ctx, e->reason));
event.setProperty(ctx, "wasClean", js::Value::boolean(e->wasClean));
emit_event(ws, WS_EVENT_CLOSE, std::move(event));
return EM_TRUE;
}
// Emscripten callback: error occurred
static EM_BOOL on_error(int eventType, const EmscriptenWebSocketErrorEvent *e, void *userData) {
WebSocketData *ws = static_cast<WebSocketData *>(userData);
js::Context ctx = js::Context::wrapRaw(nullptr, ws->raw_ctx);
// Create error event
js::Value event = js::Value::object(ctx);
event.setProperty(ctx, "type", js::Value::string(ctx, "error"));
emit_event(ws, WS_EVENT_ERROR, std::move(event));
return EM_TRUE;
}
// Destructor for WebSocket instances
static void websocket_destructor(void *opaque) {
WebSocketData *ws = static_cast<WebSocketData *>(opaque);
delete ws;
}
// WebSocket constructor: new WebSocket(url, protocols)
static void js_websocket_constructor(js::ConstructorArgs &args) {
if (args.length() < 1) {
args.throwSyntaxError("WebSocket constructor requires a URL");
return;
}
// Get URL
std::string url = args.arg(0).toString(args.context());
// Validate URL scheme
if (url.substr(0, 5) != "ws://" && url.substr(0, 6) != "wss://") {
args.throwSyntaxError("WebSocket URL must start with ws:// or wss://");
return;
}
// Get protocols (optional)
std::string protocols;
if (args.length() >= 2) {
js::Value protocolArg = args.arg(1);
if (!protocolArg.isUndefined() && !protocolArg.isNull()) {
if (!protocolArg.isArray()) {
protocols = protocolArg.toString(args.context());
}
// TODO: Handle array of protocols by joining with comma
}
}
// Create instance
js::Value instance = args.createInstance();
// Allocate WebSocket data
WebSocketData *ws = new WebSocketData();
ws->raw_ctx = args.context().raw();
// Store references
ws->this_ref = js::PersistentValue(args.context(), instance);
ws->url_val = js::PersistentValue(args.context(), js::Value::string(args.context(), url.c_str()));
ws->protocol_val = js::PersistentValue(args.context(), js::Value::string(args.context(), ""));
// Create Emscripten WebSocket
EmscriptenWebSocketCreateAttributes attrs = {
url.c_str(),
protocols.empty() ? nullptr : protocols.c_str(),
EM_TRUE // createOnMainThread
};
ws->socket = emscripten_websocket_new(&attrs);
if (ws->socket <= 0) {
delete ws;
args.throwError("Failed to create WebSocket connection");
return;
}
// Set up callbacks
emscripten_websocket_set_onopen_callback(ws->socket, ws, on_open);
emscripten_websocket_set_onmessage_callback(ws->socket, ws, on_message);
emscripten_websocket_set_onclose_callback(ws->socket, ws, on_close);
emscripten_websocket_set_onerror_callback(ws->socket, ws, on_error);
instance.setInternalField(0, ws);
args.returnValue(std::move(instance));
}
// send(data) - send text or binary data
static void js_websocket_send(js::FunctionArgs &args) {
WebSocketData *ws = getWebSocketData(args);
if (!ws) {
args.throwError("Invalid WebSocket");
return;
}
if (ws->ready_state != WS_STATE_OPEN) {
args.throwError("WebSocket is not open");
return;
}
if (args.length() < 1) {
args.returnUndefined();
return;
}
js::Value data = args.arg(0);
if (data.isString()) {
std::string text = data.toString(args.context());
emscripten_websocket_send_utf8_text(ws->socket, text.c_str());
} else if (data.isArrayBuffer()) {
void *buf = data.arrayBufferData();
size_t size = data.arrayBufferLength();
if (buf) {
emscripten_websocket_send_binary(ws->socket, buf, size);
}
} else if (data.isTypedArray()) {
js::Value buffer = data.typedArrayBuffer(args.context());
void *buf = buffer.arrayBufferData();
size_t offset = data.typedArrayByteOffset();
size_t length = data.typedArrayByteLength();
if (buf) {
emscripten_websocket_send_binary(ws->socket, static_cast<uint8_t *>(buf) + offset, length);
}
}
args.returnUndefined();
}
// close(code, reason) - close the connection
static void js_websocket_close(js::FunctionArgs &args) {
WebSocketData *ws = getWebSocketData(args);
if (!ws) {
args.throwError("Invalid WebSocket");
return;
}
if (ws->ready_state >= WS_STATE_CLOSING) {
args.returnUndefined(); // Already closing/closed
return;
}
int code = 1000; // Normal closure
std::string reason;
if (args.length() >= 1) {
js::Value codeArg = args.arg(0);
if (!codeArg.isUndefined()) {
code = codeArg.toInt32();
// Validate code (must be 1000 or 3000-4999)
if (code != 1000 && (code < 3000 || code > 4999)) {
args.throwRangeError("Invalid close code: must be 1000 or 3000-4999");
return;
}
}
}
if (args.length() >= 2) {
js::Value reasonArg = args.arg(1);
if (!reasonArg.isUndefined()) {
reason = reasonArg.toString(args.context());
// Validate reason length (max 123 bytes per spec)
if (reason.length() > 123) {
args.throwSyntaxError("Close reason too long (max 123 bytes)");
return;
}
}
}
ws->ready_state = WS_STATE_CLOSING;
emscripten_websocket_close(ws->socket, code, reason.c_str());
args.returnUndefined();
}
// Getter for readyState
static void js_websocket_get_readyState(js::FunctionArgs &args) {
WebSocketData *ws = getWebSocketData(args);
if (!ws) {
args.throwError("Invalid WebSocket");
return;
}
args.returnValue(js::Value::number(static_cast<int32_t>(ws->ready_state)));
}
// Getter for url
static void js_websocket_get_url(js::FunctionArgs &args) {
WebSocketData *ws = getWebSocketData(args);
if (!ws) {
args.throwError("Invalid WebSocket");
return;
}
args.returnValue(ws->url_val.get(args.context()));
}
// Getter for protocol
static void js_websocket_get_protocol(js::FunctionArgs &args) {
WebSocketData *ws = getWebSocketData(args);
if (!ws) {
args.throwError("Invalid WebSocket");
return;
}
args.returnValue(ws->protocol_val.get(args.context()));
}
// Event handler getters/setters
static void js_websocket_get_onopen(js::FunctionArgs &args) {
WebSocketData *ws = getWebSocketData(args);
if (!ws) { args.returnUndefined(); return; }
args.returnValue(ws->events[WS_EVENT_OPEN].get(args.context()));
}
static void js_websocket_set_onopen(js::FunctionArgs &args) {
WebSocketData *ws = getWebSocketData(args);
if (!ws || args.length() < 1) { args.returnUndefined(); return; }
js::Value val = args.arg(0);
if (val.isFunction() || val.isUndefined() || val.isNull()) {
ws->events[WS_EVENT_OPEN].reset(args.context(), val);
}
args.returnUndefined();
}
static void js_websocket_get_onmessage(js::FunctionArgs &args) {
WebSocketData *ws = getWebSocketData(args);
if (!ws) { args.returnUndefined(); return; }
args.returnValue(ws->events[WS_EVENT_MESSAGE].get(args.context()));
}
static void js_websocket_set_onmessage(js::FunctionArgs &args) {
WebSocketData *ws = getWebSocketData(args);
if (!ws || args.length() < 1) { args.returnUndefined(); return; }
js::Value val = args.arg(0);
if (val.isFunction() || val.isUndefined() || val.isNull()) {
ws->events[WS_EVENT_MESSAGE].reset(args.context(), val);
}
args.returnUndefined();
}
static void js_websocket_get_onclose(js::FunctionArgs &args) {
WebSocketData *ws = getWebSocketData(args);
if (!ws) { args.returnUndefined(); return; }
args.returnValue(ws->events[WS_EVENT_CLOSE].get(args.context()));
}
static void js_websocket_set_onclose(js::FunctionArgs &args) {
WebSocketData *ws = getWebSocketData(args);
if (!ws || args.length() < 1) { args.returnUndefined(); return; }
js::Value val = args.arg(0);
if (val.isFunction() || val.isUndefined() || val.isNull()) {
ws->events[WS_EVENT_CLOSE].reset(args.context(), val);
}
args.returnUndefined();
}
static void js_websocket_get_onerror(js::FunctionArgs &args) {
WebSocketData *ws = getWebSocketData(args);
if (!ws) { args.returnUndefined(); return; }
args.returnValue(ws->events[WS_EVENT_ERROR].get(args.context()));
}
static void js_websocket_set_onerror(js::FunctionArgs &args) {
WebSocketData *ws = getWebSocketData(args);
if (!ws || args.length() < 1) { args.returnUndefined(); return; }
js::Value val = args.arg(0);
if (val.isFunction() || val.isUndefined() || val.isNull()) {
ws->events[WS_EVENT_ERROR].reset(args.context(), val);
}
args.returnUndefined();
}
// Module initialization
WebSocket::WebSocket(Engine *engine) : engine_(engine) {
// Nothing to initialize for Emscripten - browser handles WebSocket
}
WebSocket::~WebSocket() {
// Nothing to cleanup for Emscripten
}
void WebSocket::update() {
// Nothing to do for Emscripten - browser handles async events
}
void WebSocket::initJS(js::Context &ctx, js::Value &global) {
js::ConstructorBuilder(ctx, "WebSocket")
.constructor(js_websocket_constructor, 2)
.finalizer(websocket_destructor)
.internalFieldCount(1)
.prototypeMethod("send", js_websocket_send, 1)
.prototypeMethod("close", js_websocket_close, 2)
.prototypeGetter("readyState", js_websocket_get_readyState)
.prototypeGetter("url", js_websocket_get_url)
.prototypeGetter("protocol", js_websocket_get_protocol)
.prototypeAccessor("onopen", js_websocket_get_onopen, js_websocket_set_onopen)
.prototypeAccessor("onmessage", js_websocket_get_onmessage, js_websocket_set_onmessage)
.prototypeAccessor("onclose", js_websocket_get_onclose, js_websocket_set_onclose)
.prototypeAccessor("onerror", js_websocket_get_onerror, js_websocket_set_onerror)
.staticConstant("CONNECTING", WS_STATE_CONNECTING)
.staticConstant("OPEN", WS_STATE_OPEN)
.staticConstant("CLOSING", WS_STATE_CLOSING)
.staticConstant("CLOSED", WS_STATE_CLOSED)
.attachTo(global);
}
} // namespace joy::webapi
|
zyedidia/joy
| 1
|
A framework for building 2D desktop games in JavaScript, with a Love2D-inspired API
|
C++
|
zyedidia
|
Zachary Yedidia
|
Stanford University
|
src/web-api/worker.cc
|
C++
|
#include "worker.hh"
#include "message_queue.hh"
#include "engine.hh"
#include <thread>
#include <atomic>
#include <memory>
#include <algorithm>
namespace joy::webapi {
// Forward declaration of worker thread entry point (in worker_thread.cc)
void workerThreadEntry(std::shared_ptr<MessageQueue> incoming,
std::shared_ptr<MessageQueue> outgoing,
std::atomic<bool> *terminated,
std::string script_path);
// Event indices for callbacks
enum {
WORKER_EVENT_MESSAGE = 0,
WORKER_EVENT_ERROR = 1,
WORKER_EVENT_MAX = 2
};
// Instance data for each Worker object
struct WorkerData {
js::PersistentValue this_ref; // Self-reference for GC protection
js::PersistentValue events[WORKER_EVENT_MAX]; // onmessage, onerror
void *raw_ctx; // Raw context pointer for callbacks
Worker *module; // Pointer to Worker module
// Threading
std::thread thread;
std::atomic<bool> terminated;
std::shared_ptr<MessageQueue> main_to_worker; // Main -> Worker messages
std::shared_ptr<MessageQueue> worker_to_main; // Worker -> Main messages
// Script info
std::string script_path;
WorkerData()
: raw_ctx(nullptr)
, module(nullptr)
, terminated(false)
, main_to_worker(std::make_shared<MessageQueue>())
, worker_to_main(std::make_shared<MessageQueue>()) {}
~WorkerData() {
// Ensure thread is terminated and joined
terminated = true;
if (thread.joinable()) {
thread.join();
}
}
};
// Get WorkerData from this value
static WorkerData *getWorkerData(js::FunctionArgs &args) {
js::Value thisVal = args.thisValue();
return static_cast<WorkerData *>(thisVal.getInternalField(0));
}
// Emit event to JS callback
static void emit_event(WorkerData *wd, js::Context &ctx, int event_idx, js::Value event) {
if (wd->events[event_idx].isEmpty()) {
return;
}
js::Value callback = wd->events[event_idx].get(ctx);
if (!callback.isFunction()) {
return;
}
js::Value thisVal = wd->this_ref.get(ctx);
js::Value result = ctx.call(callback, thisVal, &event, 1);
if (result.isException()) {
js::Value exception = ctx.getException();
std::string err = exception.toString(ctx);
fprintf(stderr, "Worker callback error: %s\n", err.c_str());
}
}
// Destructor for Worker instances
static void worker_destructor(void *opaque) {
WorkerData *wd = static_cast<WorkerData *>(opaque);
if (wd->module) {
wd->module->unregisterWorker(wd);
}
delete wd;
}
// Worker constructor: new Worker(scriptPath)
static void js_worker_constructor(js::ConstructorArgs &args) {
if (args.length() < 1) {
args.throwSyntaxError("Worker constructor requires a script path");
return;
}
// Get script path
std::string script_path = args.arg(0).toString(args.context());
// Get engine
Engine *engine = args.getContextOpaque<Engine>();
if (!engine || !engine->getWorkerModule()) {
args.throwError("Worker module not initialized");
return;
}
// Create instance
js::Value instance = args.createInstance();
// Allocate WorkerData
WorkerData *wd = new WorkerData();
wd->raw_ctx = args.context().raw();
wd->module = engine->getWorkerModule();
wd->script_path = script_path;
// Store self-reference
wd->this_ref = js::PersistentValue(args.context(), instance);
// Register with module for update tracking
wd->module->registerWorker(wd);
// Spawn worker thread
wd->thread = std::thread(workerThreadEntry,
wd->main_to_worker,
wd->worker_to_main,
&wd->terminated,
script_path);
instance.setInternalField(0, wd);
args.returnValue(std::move(instance));
}
// Worker.postMessage(data) - serialize and queue for worker
static void js_worker_postMessage(js::FunctionArgs &args) {
WorkerData *wd = getWorkerData(args);
if (!wd) {
args.throwError("Invalid Worker");
return;
}
if (wd->terminated) {
args.returnUndefined();
return;
}
if (args.length() < 1) {
args.returnUndefined();
return;
}
// Serialize argument using js:: abstraction
js::Value arg = args.arg(0);
std::vector<uint8_t> data = arg.serialize(args.context());
if (data.empty()) {
args.throwError("Failed to serialize message");
return;
}
SerializedMessage msg(std::move(data));
wd->main_to_worker->push(std::move(msg));
args.returnUndefined();
}
// Worker.terminate() - signal worker to stop
static void js_worker_terminate(js::FunctionArgs &args) {
WorkerData *wd = getWorkerData(args);
if (!wd) {
args.throwError("Invalid Worker");
return;
}
wd->terminated = true;
// Post empty message to wake worker if blocked
wd->main_to_worker->push(SerializedMessage{});
// Wait for thread to finish
if (wd->thread.joinable()) {
wd->thread.join();
}
args.returnUndefined();
}
// Event handler getters/setters
static void js_worker_get_onmessage(js::FunctionArgs &args) {
WorkerData *wd = getWorkerData(args);
if (!wd) { args.returnUndefined(); return; }
if (wd->events[WORKER_EVENT_MESSAGE].isEmpty()) {
args.returnValue(js::Value::null());
} else {
args.returnValue(wd->events[WORKER_EVENT_MESSAGE].get(args.context()));
}
}
static void js_worker_set_onmessage(js::FunctionArgs &args) {
WorkerData *wd = getWorkerData(args);
if (!wd || args.length() < 1) { args.returnUndefined(); return; }
js::Value val = args.arg(0);
if (val.isFunction() || val.isUndefined() || val.isNull()) {
wd->events[WORKER_EVENT_MESSAGE].reset(args.context(), val);
}
args.returnUndefined();
}
static void js_worker_get_onerror(js::FunctionArgs &args) {
WorkerData *wd = getWorkerData(args);
if (!wd) { args.returnUndefined(); return; }
if (wd->events[WORKER_EVENT_ERROR].isEmpty()) {
args.returnValue(js::Value::null());
} else {
args.returnValue(wd->events[WORKER_EVENT_ERROR].get(args.context()));
}
}
static void js_worker_set_onerror(js::FunctionArgs &args) {
WorkerData *wd = getWorkerData(args);
if (!wd || args.length() < 1) { args.returnUndefined(); return; }
js::Value val = args.arg(0);
if (val.isFunction() || val.isUndefined() || val.isNull()) {
wd->events[WORKER_EVENT_ERROR].reset(args.context(), val);
}
args.returnUndefined();
}
// Worker module implementation
Worker::Worker(Engine *engine) : engine_(engine) {
}
Worker::~Worker() {
// Terminate all active workers
for (WorkerData *wd : active_workers_) {
wd->terminated = true;
wd->main_to_worker->push(SerializedMessage{});
if (wd->thread.joinable()) {
wd->thread.join();
}
}
}
void Worker::registerWorker(WorkerData *wd) {
active_workers_.push_back(wd);
}
void Worker::unregisterWorker(WorkerData *wd) {
auto it = std::find(active_workers_.begin(), active_workers_.end(), wd);
if (it != active_workers_.end()) {
active_workers_.erase(it);
}
}
void Worker::update() {
js::Context *ctx = engine_->getJSContext();
if (!ctx) return;
for (WorkerData *wd : active_workers_) {
SerializedMessage msg;
while (wd->worker_to_main->tryPop(msg)) {
if (msg.is_error) {
// Create error event
js::Value event = js::Value::object(*ctx);
event.setProperty(*ctx, "type", js::Value::string(*ctx, "error"));
event.setProperty(*ctx, "message", js::Value::string(*ctx, msg.error_msg.c_str()));
emit_event(wd, *ctx, WORKER_EVENT_ERROR, std::move(event));
} else if (!msg.data.empty()) {
// Deserialize message using js:: abstraction
js::Value val = js::Value::deserialize(*ctx, msg.data);
if (val.isException()) {
// Handle deserialization error
js::Value exc = ctx->getException();
std::string err = exc.toString(*ctx);
fprintf(stderr, "Worker message deserialization error: %s\n", err.c_str());
continue;
}
// Create MessageEvent-like object
js::Value event = js::Value::object(*ctx);
event.setProperty(*ctx, "type", js::Value::string(*ctx, "message"));
event.setProperty(*ctx, "data", std::move(val));
emit_event(wd, *ctx, WORKER_EVENT_MESSAGE, std::move(event));
}
}
}
}
void Worker::initJS(js::Context &ctx, js::Value &global) {
js::ConstructorBuilder(ctx, "Worker")
.constructor(js_worker_constructor, 1)
.finalizer(worker_destructor)
.internalFieldCount(1)
.prototypeMethod("postMessage", js_worker_postMessage, 1)
.prototypeMethod("terminate", js_worker_terminate, 0)
.prototypeAccessor("onmessage", js_worker_get_onmessage, js_worker_set_onmessage)
.prototypeAccessor("onerror", js_worker_get_onerror, js_worker_set_onerror)
.attachTo(global);
}
} // namespace joy::webapi
|
zyedidia/joy
| 1
|
A framework for building 2D desktop games in JavaScript, with a Love2D-inspired API
|
C++
|
zyedidia
|
Zachary Yedidia
|
Stanford University
|
src/web-api/worker.hh
|
C++ Header
|
#pragma once
#include "js/js.hh"
#include <vector>
#include <memory>
namespace joy {
class Engine;
namespace webapi {
// Forward declaration
struct WorkerData;
class Worker {
public:
Worker(Engine *engine);
~Worker();
// Called each frame to process worker->main messages
void update();
// Register Worker constructor on global object
static void initJS(js::Context &ctx, js::Value &global);
// Track active workers for update loop
void registerWorker(WorkerData *wd);
void unregisterWorker(WorkerData *wd);
Engine *getEngine() { return engine_; }
private:
Engine *engine_;
std::vector<WorkerData*> active_workers_;
};
} // namespace webapi
} // namespace joy
|
zyedidia/joy
| 1
|
A framework for building 2D desktop games in JavaScript, with a Love2D-inspired API
|
C++
|
zyedidia
|
Zachary Yedidia
|
Stanford University
|
src/web-api/worker_thread.cc
|
C++
|
#include "worker.hh"
#include "message_queue.hh"
#include "js/js.hh"
#include "modules/filesystem/filesystem.hh"
#include "modules/timer/timer.hh"
#include "modules/math/math.hh"
#include <thread>
#include <atomic>
#include <chrono>
#include <memory>
#include <cstdio>
namespace joy::webapi {
// Worker-side context data (stored as context opaque)
struct WorkerContext {
std::shared_ptr<MessageQueue> incoming; // main_to_worker
std::shared_ptr<MessageQueue> outgoing; // worker_to_main
std::atomic<bool> *terminated;
// Worker-local module instances
std::unique_ptr<modules::Math> math;
WorkerContext() : terminated(nullptr) {}
};
// Get WorkerContext from context opaque
static WorkerContext *getWorkerContext(js::FunctionArgs &args) {
return args.getContextOpaque<WorkerContext>();
}
// ============================================================================
// Worker-local module: self.postMessage
// ============================================================================
static void js_self_postMessage(js::FunctionArgs &args) {
WorkerContext *wctx = getWorkerContext(args);
if (!wctx) {
args.throwError("Worker context not found");
return;
}
if (args.length() < 1) {
args.returnUndefined();
return;
}
// Serialize argument using js:: abstraction
js::Value arg = args.arg(0);
std::vector<uint8_t> data = arg.serialize(args.context());
if (data.empty()) {
args.throwError("Failed to serialize message");
return;
}
SerializedMessage msg(std::move(data));
wctx->outgoing->push(std::move(msg));
args.returnUndefined();
}
// ============================================================================
// Worker-local module: joy.timer (static methods only)
// ============================================================================
static void js_worker_timer_getTime(js::FunctionArgs &args) {
args.returnValue(js::Value::number(modules::Timer::getTime()));
}
static void js_worker_timer_sleep(js::FunctionArgs &args) {
WorkerContext *wctx = getWorkerContext(args);
if (args.length() >= 1) {
double seconds = args.arg(0).toFloat64();
if (seconds >= 0) {
// Sleep in small chunks to allow interruption by termination
int total_ms = static_cast<int>(seconds * 1000);
const int chunk_ms = 50; // Check every 50ms
while (total_ms > 0 && wctx && !(*wctx->terminated)) {
int sleep_ms = (total_ms < chunk_ms) ? total_ms : chunk_ms;
std::this_thread::sleep_for(std::chrono::milliseconds(sleep_ms));
total_ms -= sleep_ms;
}
}
}
args.returnUndefined();
}
// ============================================================================
// Worker-local module: joy.math
// ============================================================================
static void js_worker_math_random(js::FunctionArgs &args) {
WorkerContext *wctx = getWorkerContext(args);
if (!wctx || !wctx->math) {
args.returnValue(js::Value::number(0));
return;
}
double result;
if (args.length() == 0) {
result = wctx->math->random();
} else if (args.length() == 1) {
double max = args.arg(0).toFloat64();
result = wctx->math->random(max);
} else {
double min = args.arg(0).toFloat64();
double max = args.arg(1).toFloat64();
result = wctx->math->random(min, max);
}
args.returnValue(js::Value::number(result));
}
static void js_worker_math_randomNormal(js::FunctionArgs &args) {
WorkerContext *wctx = getWorkerContext(args);
if (!wctx || !wctx->math) {
args.returnValue(js::Value::number(0));
return;
}
double stddev = args.length() >= 1 ? args.arg(0).toFloat64() : 1.0;
double mean = args.length() >= 2 ? args.arg(1).toFloat64() : 0.0;
args.returnValue(js::Value::number(wctx->math->randomNormal(stddev, mean)));
}
static void js_worker_math_setRandomSeed(js::FunctionArgs &args) {
WorkerContext *wctx = getWorkerContext(args);
if (!wctx || !wctx->math || args.length() < 1) {
args.returnUndefined();
return;
}
if (args.length() == 1) {
uint64_t seed = static_cast<uint64_t>(args.arg(0).toFloat64());
wctx->math->setRandomSeed(seed);
} else {
uint32_t low = static_cast<uint32_t>(args.arg(0).toFloat64());
uint32_t high = static_cast<uint32_t>(args.arg(1).toFloat64());
wctx->math->setRandomSeed(low, high);
}
args.returnUndefined();
}
static void js_worker_math_getRandomSeed(js::FunctionArgs &args) {
WorkerContext *wctx = getWorkerContext(args);
if (!wctx || !wctx->math) {
args.returnValue(js::Value::number(0));
return;
}
uint32_t low, high;
wctx->math->getRandomSeed(low, high);
js::Value result = js::Value::array(args.context());
result.setProperty(args.context(), 0u, js::Value::number(static_cast<double>(low)));
result.setProperty(args.context(), 1u, js::Value::number(static_cast<double>(high)));
args.returnValue(std::move(result));
}
static void js_worker_math_noise(js::FunctionArgs &args) {
double result = 0;
int argc = args.length();
if (argc == 1) {
result = modules::Math::noise(args.arg(0).toFloat64());
} else if (argc == 2) {
result = modules::Math::noise(args.arg(0).toFloat64(), args.arg(1).toFloat64());
} else if (argc == 3) {
result = modules::Math::noise(args.arg(0).toFloat64(), args.arg(1).toFloat64(),
args.arg(2).toFloat64());
} else if (argc >= 4) {
result = modules::Math::noise(args.arg(0).toFloat64(), args.arg(1).toFloat64(),
args.arg(2).toFloat64(), args.arg(3).toFloat64());
}
args.returnValue(js::Value::number(result));
}
static void js_worker_math_gammaToLinear(js::FunctionArgs &args) {
if (args.length() < 1) {
args.returnValue(js::Value::number(0));
return;
}
float c = static_cast<float>(args.arg(0).toFloat64());
args.returnValue(js::Value::number(modules::Math::gammaToLinear(c)));
}
static void js_worker_math_linearToGamma(js::FunctionArgs &args) {
if (args.length() < 1) {
args.returnValue(js::Value::number(0));
return;
}
float c = static_cast<float>(args.arg(0).toFloat64());
args.returnValue(js::Value::number(modules::Math::linearToGamma(c)));
}
// ============================================================================
// Worker-local module: joy.filesystem (read-only operations)
// ============================================================================
static void js_worker_filesystem_read(js::FunctionArgs &args) {
if (args.length() < 1) {
args.throwError("filesystem.read requires filename");
return;
}
std::string filename = args.arg(0).toString(args.context());
std::vector<char> data;
if (!modules::Filesystem::read(filename.c_str(), data)) {
args.returnValue(js::Value::null());
return;
}
args.returnValue(js::Value::string(args.context(), data.data(), data.size()));
}
static void js_worker_filesystem_getInfo(js::FunctionArgs &args) {
if (args.length() < 1) {
args.returnValue(js::Value::null());
return;
}
std::string filename = args.arg(0).toString(args.context());
modules::FileInfo info;
if (!modules::Filesystem::getInfo(filename.c_str(), &info)) {
args.returnValue(js::Value::null());
return;
}
js::Value result = js::Value::object(args.context());
result.setProperty(args.context(), "type",
js::Value::string(args.context(),
info.type == modules::FileType::File ? "file" :
info.type == modules::FileType::Directory ? "directory" :
info.type == modules::FileType::Symlink ? "symlink" : "other"));
result.setProperty(args.context(), "size", js::Value::number(static_cast<double>(info.size)));
result.setProperty(args.context(), "modtime", js::Value::number(static_cast<double>(info.modtime)));
args.returnValue(std::move(result));
}
static void js_worker_filesystem_getDirectoryItems(js::FunctionArgs &args) {
if (args.length() < 1) {
args.returnValue(js::Value::array(args.context()));
return;
}
std::string dir = args.arg(0).toString(args.context());
std::vector<std::string> items = modules::Filesystem::getDirectoryItems(dir.c_str());
js::Value result = js::Value::array(args.context());
for (size_t i = 0; i < items.size(); i++) {
result.setProperty(args.context(), static_cast<uint32_t>(i),
js::Value::string(args.context(), items[i].c_str()));
}
args.returnValue(std::move(result));
}
// ============================================================================
// Worker-local module: console
// ============================================================================
static void js_worker_console_log(js::FunctionArgs &args) {
for (int i = 0; i < args.length(); i++) {
if (i > 0) fprintf(stdout, " ");
std::string str = args.arg(i).toString(args.context());
fprintf(stdout, "%s", str.c_str());
}
fprintf(stdout, "\n");
fflush(stdout);
args.returnUndefined();
}
static void js_worker_console_warn(js::FunctionArgs &args) {
fprintf(stderr, "[WARN] ");
for (int i = 0; i < args.length(); i++) {
if (i > 0) fprintf(stderr, " ");
std::string str = args.arg(i).toString(args.context());
fprintf(stderr, "%s", str.c_str());
}
fprintf(stderr, "\n");
fflush(stderr);
args.returnUndefined();
}
static void js_worker_console_error(js::FunctionArgs &args) {
fprintf(stderr, "[ERROR] ");
for (int i = 0; i < args.length(); i++) {
if (i > 0) fprintf(stderr, " ");
std::string str = args.arg(i).toString(args.context());
fprintf(stderr, "%s", str.c_str());
}
fprintf(stderr, "\n");
fflush(stderr);
args.returnUndefined();
}
// ============================================================================
// Worker-local module: joy.worker
// ============================================================================
static void js_worker_isTerminated(js::FunctionArgs &args) {
WorkerContext *wctx = getWorkerContext(args);
if (wctx && wctx->terminated) {
args.returnValue(js::Value::boolean(*wctx->terminated));
} else {
args.returnValue(js::Value::boolean(false));
}
}
// ============================================================================
// Initialize worker modules
// ============================================================================
static void initWorkerModules(js::Context &ctx, js::Value &global, WorkerContext *wctx) {
// Create joy namespace
js::Value joy = js::Value::object(ctx);
// joy.timer (static methods)
js::ModuleBuilder(ctx, "timer")
.function("getTime", js_worker_timer_getTime, 0)
.function("sleep", js_worker_timer_sleep, 1)
.attachTo(joy);
// joy.math (uses worker-local Math instance)
js::ModuleBuilder(ctx, "math")
.function("random", js_worker_math_random, 2)
.function("randomNormal", js_worker_math_randomNormal, 2)
.function("setRandomSeed", js_worker_math_setRandomSeed, 2)
.function("getRandomSeed", js_worker_math_getRandomSeed, 0)
.function("noise", js_worker_math_noise, 4)
.function("gammaToLinear", js_worker_math_gammaToLinear, 1)
.function("linearToGamma", js_worker_math_linearToGamma, 1)
.attachTo(joy);
// joy.filesystem (read-only)
js::ModuleBuilder(ctx, "filesystem")
.function("read", js_worker_filesystem_read, 1)
.function("getInfo", js_worker_filesystem_getInfo, 1)
.function("getDirectoryItems", js_worker_filesystem_getDirectoryItems, 1)
.attachTo(joy);
// joy.worker (worker-specific functions)
js::ModuleBuilder(ctx, "worker")
.function("isTerminated", js_worker_isTerminated, 0)
.attachTo(joy);
global.setProperty(ctx, "joy", std::move(joy));
// console
js::ModuleBuilder(ctx, "console")
.function("log", js_worker_console_log, 1)
.function("warn", js_worker_console_warn, 1)
.function("error", js_worker_console_error, 1)
.attachTo(global);
// Build a temp object to get postMessage function
js::Value workerFuncs = js::ModuleBuilder(ctx, "__temp__")
.function("postMessage", js_self_postMessage, 1)
.build();
// Set postMessage directly on global object
js::Value postMessageFunc = workerFuncs.getProperty(ctx, "postMessage");
global.setProperty(ctx, "postMessage", postMessageFunc);
// Alias self to globalThis
global.setProperty(ctx, "self", global);
}
// ============================================================================
// Process incoming messages from main thread
// ============================================================================
static void processIncomingMessages(WorkerContext *wctx, js::Context &ctx,
js::Value &global, js::PersistentValue &onmessage) {
SerializedMessage msg;
while (wctx->incoming->tryPop(msg)) {
// Empty message is termination signal
if (msg.data.empty()) {
continue;
}
// Deserialize message using js:: abstraction
js::Value val = js::Value::deserialize(ctx, msg.data);
if (val.isException()) {
js::Value exc = ctx.getException();
std::string err = exc.toString(ctx);
fprintf(stderr, "Worker: Failed to deserialize message: %s\n", err.c_str());
continue;
}
// Check for onmessage callback
if (onmessage.isEmpty()) {
// Try to get it from global again (might have been set later)
js::Value cb = global.getProperty(ctx, "onmessage");
if (cb.isFunction()) {
onmessage.reset(ctx, cb);
}
}
if (!onmessage.isEmpty()) {
js::Value callback = onmessage.get(ctx);
if (callback.isFunction()) {
// Create MessageEvent-like object
js::Value event = js::Value::object(ctx);
event.setProperty(ctx, "type", js::Value::string(ctx, "message"));
event.setProperty(ctx, "data", std::move(val));
js::Value result = ctx.call(callback, global, &event, 1);
if (result.isException()) {
js::Value exception = ctx.getException();
std::string err = exception.toString(ctx);
fprintf(stderr, "Worker onmessage error: %s\n", err.c_str());
}
}
}
}
}
// ============================================================================
// Worker thread entry point
// ============================================================================
void workerThreadEntry(std::shared_ptr<MessageQueue> incoming,
std::shared_ptr<MessageQueue> outgoing,
std::atomic<bool> *terminated,
std::string script_path) {
// Create thread-local JS runtime and context
js::Runtime runtime;
js::Context ctx(runtime);
// Create worker context
WorkerContext wctx;
wctx.incoming = incoming;
wctx.outgoing = outgoing;
wctx.terminated = terminated;
wctx.math = std::make_unique<modules::Math>();
// Set context opaque for module access
ctx.setOpaque(&wctx);
// Get global object
js::Value global = ctx.globalObject();
// Initialize worker modules
initWorkerModules(ctx, global, &wctx);
// Load worker script from filesystem
std::vector<char> script_data;
if (!modules::Filesystem::read(script_path.c_str(), script_data)) {
SerializedMessage err(std::string("Failed to load worker script: ") + script_path);
outgoing->push(std::move(err));
return;
}
// Execute the script
js::Value result = ctx.eval(script_data.data(), script_data.size(), script_path.c_str());
if (result.isException()) {
js::Value exception = ctx.getException();
std::string err_msg = exception.toString(ctx);
ctx.printException(exception);
SerializedMessage err(err_msg);
outgoing->push(std::move(err));
return;
}
// Get onmessage callback (if set during script execution)
js::PersistentValue onmessage;
js::Value cb = global.getProperty(ctx, "onmessage");
if (cb.isFunction()) {
onmessage = js::PersistentValue(ctx, cb);
}
// Event loop - process messages until terminated
while (!*terminated) {
processIncomingMessages(&wctx, ctx, global, onmessage);
// Sleep briefly to avoid busy-waiting
// In a more sophisticated implementation, we could use condition variables
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
}
} // namespace joy::webapi
|
zyedidia/joy
| 1
|
A framework for building 2D desktop games in JavaScript, with a Love2D-inspired API
|
C++
|
zyedidia
|
Zachary Yedidia
|
Stanford University
|
web/shell.html
|
HTML
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>Joy2D</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
background: #1a1a2e;
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}
.container {
text-align: center;
}
#canvas {
background: #000;
display: block;
margin: 0 auto;
border-radius: 4px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.5);
}
.loading {
color: #fff;
font-size: 18px;
margin-top: 20px;
}
.progress {
width: 300px;
height: 8px;
background: #333;
border-radius: 4px;
margin: 10px auto;
overflow: hidden;
}
.progress-bar {
height: 100%;
background: linear-gradient(90deg, #667eea, #764ba2);
width: 0%;
transition: width 0.3s;
}
.hidden {
display: none;
}
.error {
color: #ff6b6b;
}
</style>
</head>
<body>
<div class="container">
<canvas id="canvas" oncontextmenu="event.preventDefault()" tabindex="-1"></canvas>
<div id="loading" class="loading">
<div id="loading-text">Loading...</div>
<div class="progress">
<div id="progress-bar" class="progress-bar"></div>
</div>
<div id="status"></div>
</div>
</div>
<script>
// Get game URL from query parameter: ?game=mygame.joy
var params = new URLSearchParams(window.location.search);
var gameUrl = params.get('game') || 'game.joy';
var Module = {
canvas: (function() {
var canvas = document.getElementById('canvas');
canvas.addEventListener('webglcontextlost', function(e) {
alert('WebGL context lost. Please reload the page.');
e.preventDefault();
}, false);
return canvas;
})(),
setStatus: function(text) {
var status = document.getElementById('status');
var loading = document.getElementById('loading');
var progressBar = document.getElementById('progress-bar');
if (text === '') {
loading.classList.add('hidden');
} else {
status.textContent = text;
var match = text.match(/\((\d+)%\)/);
if (match) {
progressBar.style.width = match[1] + '%';
}
}
},
totalDependencies: 0,
monitorRunDependencies: function(left) {
this.totalDependencies = Math.max(this.totalDependencies, left);
var progress = ((this.totalDependencies - left) / this.totalDependencies) * 100;
document.getElementById('progress-bar').style.width = progress + '%';
if (left === 0) {
document.getElementById('loading').classList.add('hidden');
}
},
preRun: [function() {
// Add a dependency so the engine waits for the game to load
Module.addRunDependency('game-bundle');
document.getElementById('loading-text').textContent = 'Loading game...';
fetch(gameUrl)
.then(function(response) {
if (!response.ok) {
throw new Error('Failed to load ' + gameUrl + ': ' + response.status);
}
var contentLength = response.headers.get('Content-Length');
var total = contentLength ? parseInt(contentLength, 10) : 0;
var loaded = 0;
var reader = response.body.getReader();
var chunks = [];
function read() {
return reader.read().then(function(result) {
if (result.done) {
return new Blob(chunks);
}
chunks.push(result.value);
loaded += result.value.length;
if (total > 0) {
var pct = Math.round((loaded / total) * 100);
document.getElementById('progress-bar').style.width = pct + '%';
document.getElementById('status').textContent = 'Downloading... (' + pct + '%)';
}
return read();
});
}
return read();
})
.then(function(blob) {
return blob.arrayBuffer();
})
.then(function(buffer) {
document.getElementById('status').textContent = 'Starting...';
// Write the .joy file to Emscripten's virtual filesystem
var data = new Uint8Array(buffer);
FS.writeFile('/game.joy', data);
Module.removeRunDependency('game-bundle');
})
.catch(function(err) {
document.getElementById('loading-text').classList.add('error');
document.getElementById('loading-text').textContent = 'Error: ' + err.message;
document.getElementById('status').textContent = 'Make sure to serve a .joy file (e.g., ?game=pong.joy)';
document.getElementById('progress-bar').style.display = 'none';
});
}],
arguments: ['/game.joy']
};
</script>
{{{ SCRIPT }}}
</body>
</html>
|
zyedidia/joy
| 1
|
A framework for building 2D desktop games in JavaScript, with a Love2D-inspired API
|
C++
|
zyedidia
|
Zachary Yedidia
|
Stanford University
|
disarm-sys/build.rs
|
Rust
|
use std::env;
use std::path::PathBuf;
use std::process::Command;
fn main() {
let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap());
let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());
let disarm_dir = manifest_dir.join("disarm");
// Generate the include files using parse.py
let pub_inc = out_dir.join("disarm64-public.inc");
let priv_inc = out_dir.join("disarm64-private.inc");
let status = Command::new("python3")
.arg(disarm_dir.join("parse.py"))
.arg(&pub_inc)
.arg(&priv_inc)
.arg(disarm_dir.join("desc.txt"))
.arg("--features")
.arg("all")
.arg("--feature-desc")
.arg(disarm_dir.join("feat.txt"))
.arg("--encode-in-header")
.status()
.expect("Failed to run parse.py");
if !status.success() {
panic!("parse.py failed with status: {}", status);
}
// Compile the C library
cc::Build::new()
.file(disarm_dir.join("classify.c"))
.file(disarm_dir.join("decode.c"))
.file(disarm_dir.join("encode.c"))
.file(disarm_dir.join("format.c"))
.include(&disarm_dir)
.include(&out_dir)
.compile("disarm64");
// Generate bindings
let bindings = bindgen::Builder::default()
.header(disarm_dir.join("disarm64.h").to_str().unwrap())
.clang_arg(format!("-I{}", disarm_dir.display()))
.clang_arg(format!("-I{}", out_dir.display()))
.parse_callbacks(Box::new(bindgen::CargoCallbacks::new()))
.generate()
.expect("Unable to generate bindings");
bindings
.write_to_file(out_dir.join("bindings.rs"))
.expect("Couldn't write bindings!");
println!("cargo::rerun-if-changed=disarm/disarm64.h");
println!("cargo::rerun-if-changed=disarm/desc.txt");
println!("cargo::rerun-if-changed=disarm/feat.txt");
println!("cargo::rerun-if-changed=disarm/parse.py");
println!("cargo::rerun-if-changed=disarm/classify.c");
println!("cargo::rerun-if-changed=disarm/decode.c");
println!("cargo::rerun-if-changed=disarm/encode.c");
println!("cargo::rerun-if-changed=disarm/format.c");
}
|
zyedidia/rdisarm
| 0
|
Rust
|
zyedidia
|
Zachary Yedidia
|
Stanford University
|
|
disarm-sys/src/lib.rs
|
Rust
|
#![allow(non_upper_case_globals)]
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
#![allow(unsafe_op_in_unsafe_fn)]
include!(concat!(env!("OUT_DIR"), "/bindings.rs"));
|
zyedidia/rdisarm
| 0
|
Rust
|
zyedidia
|
Zachary Yedidia
|
Stanford University
|
|
src/lib.rs
|
Rust
|
//! Safe Rust bindings for the disarm64 AArch64 disassembler library.
//!
//! This crate provides a Rust-friendly API for decoding and formatting
//! AArch64 (ARM64) instructions.
//!
//! # Example
//!
//! ```
//! use rdisarm::Instruction;
//!
//! // Decode a NOP instruction (0xD503201F)
//! let inst = Instruction::decode(0xD503201F);
//! println!("{}", inst);
//!
//! // Access operands
//! for op in inst.operands() {
//! println!(" {:?}", op);
//! }
//! ```
use std::fmt;
use std::mem::MaybeUninit;
/// Condition codes for conditional instructions.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u8)]
pub enum Condition {
/// Equal (Z=1)
Eq = 0x0,
/// Not equal (Z=0)
Ne = 0x1,
/// Carry set / Higher or same (C=1)
Cs = 0x2,
/// Carry clear / Lower (C=0)
Cc = 0x3,
/// Minus / Negative (N=1)
Mi = 0x4,
/// Plus / Positive or zero (N=0)
Pl = 0x5,
/// Overflow set (V=1)
Vs = 0x6,
/// Overflow clear (V=0)
Vc = 0x7,
/// Higher (C=1 & Z=0)
Hi = 0x8,
/// Lower or same (C=0 | Z=1)
Ls = 0x9,
/// Greater than or equal (N=V)
Ge = 0xa,
/// Less than (N!=V)
Lt = 0xb,
/// Greater than (Z=0 & N=V)
Gt = 0xc,
/// Less than or equal (Z=1 | N!=V)
Le = 0xd,
/// Always
Al = 0xe,
/// Always (never encoding)
Nv = 0xf,
}
impl Condition {
fn from_raw(val: u8) -> Self {
match val & 0xf {
0x0 => Self::Eq,
0x1 => Self::Ne,
0x2 => Self::Cs,
0x3 => Self::Cc,
0x4 => Self::Mi,
0x5 => Self::Pl,
0x6 => Self::Vs,
0x7 => Self::Vc,
0x8 => Self::Hi,
0x9 => Self::Ls,
0xa => Self::Ge,
0xb => Self::Lt,
0xc => Self::Gt,
0xd => Self::Le,
0xe => Self::Al,
_ => Self::Nv,
}
}
}
/// Register extend/shift operations.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u8)]
pub enum Extend {
/// Unsigned extend byte
Uxtb = 0,
/// Unsigned extend halfword
Uxth = 1,
/// Unsigned extend word
Uxtw = 2,
/// Unsigned extend doubleword
Uxtx = 3,
/// Signed extend byte
Sxtb = 4,
/// Signed extend halfword
Sxth = 5,
/// Signed extend word
Sxtw = 6,
/// Signed extend doubleword
Sxtx = 7,
/// Logical shift left
Lsl = 8,
/// Logical shift right
Lsr = 9,
/// Arithmetic shift right
Asr = 10,
/// Rotate right
Ror = 11,
}
impl Extend {
fn from_raw(val: u8) -> Self {
match val {
0 => Self::Uxtb,
1 => Self::Uxth,
2 => Self::Uxtw,
3 => Self::Uxtx,
4 => Self::Sxtb,
5 => Self::Sxth,
6 => Self::Sxtw,
7 => Self::Sxtx,
8 => Self::Lsl,
9 => Self::Lsr,
10 => Self::Asr,
_ => Self::Ror,
}
}
}
/// Vector arrangement specifier.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u8)]
pub enum VectorArrangement {
/// 8 bytes
B8 = 0,
/// 16 bytes
B16 = 1,
/// 4 halfwords
H4 = 2,
/// 8 halfwords
H8 = 3,
/// 2 single-words
S2 = 4,
/// 4 single-words
S4 = 5,
/// 1 double-word
D1 = 6,
/// 2 double-words
D2 = 7,
/// 2 halfwords (special)
H2 = 8,
/// 1 quadword (special)
Q1 = 9,
}
impl VectorArrangement {
fn from_raw(val: u8) -> Self {
match val {
0 => Self::B8,
1 => Self::B16,
2 => Self::H4,
3 => Self::H8,
4 => Self::S2,
5 => Self::S4,
6 => Self::D1,
7 => Self::D2,
8 => Self::H2,
_ => Self::Q1,
}
}
}
/// Prefetch operation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u8)]
pub enum PrefetchOp {
PldL1Keep = 0,
PldL1Strm = 1,
PldL2Keep = 2,
PldL2Strm = 3,
PldL3Keep = 4,
PldL3Strm = 5,
PliL1Keep = 8,
PliL1Strm = 9,
PliL2Keep = 10,
PliL2Strm = 11,
PliL3Keep = 12,
PliL3Strm = 13,
PstL1Keep = 16,
PstL1Strm = 17,
PstL2Keep = 18,
PstL2Strm = 19,
PstL3Keep = 20,
PstL3Strm = 21,
/// Unknown/other prefetch operation
Other(u8),
}
impl PrefetchOp {
fn from_raw(val: u8) -> Self {
match val {
0 => Self::PldL1Keep,
1 => Self::PldL1Strm,
2 => Self::PldL2Keep,
3 => Self::PldL2Strm,
4 => Self::PldL3Keep,
5 => Self::PldL3Strm,
8 => Self::PliL1Keep,
9 => Self::PliL1Strm,
10 => Self::PliL2Keep,
11 => Self::PliL2Strm,
12 => Self::PliL3Keep,
13 => Self::PliL3Strm,
16 => Self::PstL1Keep,
17 => Self::PstL1Strm,
18 => Self::PstL2Keep,
19 => Self::PstL2Strm,
20 => Self::PstL3Keep,
21 => Self::PstL3Strm,
v => Self::Other(v),
}
}
}
/// Shift type for immediate shifts.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ShiftType {
/// Logical shift left
Lsl,
/// Masked shift left
Msl,
}
/// General-purpose register operand.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct GpReg {
/// Register number (0-30, or 31 for ZR/SP depending on context)
pub reg: u8,
/// True if 64-bit (X register), false if 32-bit (W register)
pub is_64bit: bool,
}
/// Extended general-purpose register operand.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct GpRegExt {
/// Register number
pub reg: u8,
/// True if 64-bit
pub is_64bit: bool,
/// Extension/shift type
pub extend: Extend,
/// Shift amount
pub shift: u8,
}
/// Floating-point/SIMD scalar register.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct FpReg {
/// Register number (0-31)
pub reg: u8,
/// Size: 0=B, 1=H, 2=S, 3=D, 4=Q
pub size: u8,
}
/// Vector register with arrangement.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct VecReg {
/// Register number (0-31)
pub reg: u8,
/// Vector arrangement
pub arrangement: VectorArrangement,
}
/// Vector register element.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct VecRegElement {
/// Register number (0-31)
pub reg: u8,
/// Element size: 0=b, 1=h, 2=s, 3=d, 4=q, 5=2b, 6=4b, 7=2h
pub elem_size: u8,
/// Element index
pub elem_index: u8,
}
/// Vector register table (for LD/ST multiple).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct VecRegTable {
/// First register number (0-31)
pub reg: u8,
/// Vector arrangement
pub arrangement: VectorArrangement,
/// Number of registers in the table
pub count: u8,
}
/// Vector register table element.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct VecRegTableElement {
/// First register number (0-31)
pub reg: u8,
/// Element size
pub elem_size: u8,
/// Element index
pub elem_index: u8,
/// Number of registers
pub count: u8,
}
/// Memory operand with unsigned offset.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct MemUnsignedOffset {
/// Base register (0-31, 31 = SP)
pub base: u8,
/// Unsigned offset
pub offset: u16,
}
/// Memory operand with signed offset.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct MemSignedOffset {
/// Base register (0-31, 31 = SP)
pub base: u8,
/// Signed offset
pub offset: i16,
}
/// Memory operand with register offset.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct MemRegOffset {
/// Base register (0-31, 31 = SP)
pub base: u8,
/// Offset register
pub offset_reg: u8,
/// Extension type
pub extend: Extend,
/// Shift amount
pub shift: u8,
/// Whether the shift/extend is explicitly shown
pub has_extend: bool,
}
/// Immediate with shift.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ShiftedImm {
/// Immediate value
pub value: u16,
/// Shift amount
pub shift: u8,
/// Shift type
pub shift_type: ShiftType,
}
/// Decoded operand.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Operand {
/// No operand (empty slot)
None,
/// General-purpose register (Xn/Wn, with 31=ZR)
GpReg(GpReg),
/// General-purpose register with post-increment
GpRegInc(GpReg),
/// Extended general-purpose register
GpRegExt(GpRegExt),
/// Stack pointer register
Sp(GpReg),
/// Floating-point/SIMD scalar register
FpReg(FpReg),
/// Vector register with arrangement
VecReg(VecReg),
/// Vector register table
VecRegTable(VecRegTable),
/// Vector register element
VecRegElement(VecRegElement),
/// Vector register table element
VecRegTableElement(VecRegTableElement),
/// Memory with unsigned offset
MemUnsignedOffset(MemUnsignedOffset),
/// Memory with signed offset
MemSignedOffset(MemSignedOffset),
/// Memory with signed pre-indexed offset
MemPreIndex(MemSignedOffset),
/// Memory with signed post-indexed offset
MemPostIndex(MemSignedOffset),
/// Memory with register offset
MemRegOffset(MemRegOffset),
/// Memory with post-incremented register
MemRegPost(MemRegOffset),
/// Memory with increment
MemInc { base: u8 },
/// Condition code
Condition(Condition),
/// Prefetch operation
Prefetch(PrefetchOp),
/// System register (encoded as op1:CRn:CRm:op2)
SysReg(u16),
/// Small unsigned immediate (decimal)
ImmSmall(u16),
/// Signed immediate
ImmSigned(i16),
/// Unsigned immediate
ImmUnsigned(u16),
/// Shifted immediate
ImmShifted(ShiftedImm),
/// Large immediate (64-bit)
ImmLarge(u64),
/// Relative address
RelAddr(u64),
/// Floating-point immediate
ImmFloat(f32),
}
impl Operand {
fn from_raw(op: &disarm_sys::Da64Op, imm64: u64, float8: f32) -> Self {
let op_type = op.type_;
match op_type as u32 {
disarm_sys::Da64OpType_DA_OP_NONE => Operand::None,
disarm_sys::Da64OpType_DA_OP_REGGP => {
let sf = unsafe { op.__bindgen_anon_2.reggp.sf() };
Operand::GpReg(GpReg {
reg: unsafe { op.__bindgen_anon_1.reg },
is_64bit: sf != 0,
})
}
disarm_sys::Da64OpType_DA_OP_REGGPINC => {
let sf = unsafe { op.__bindgen_anon_2.reggp.sf() };
Operand::GpRegInc(GpReg {
reg: unsafe { op.__bindgen_anon_1.reg },
is_64bit: sf != 0,
})
}
disarm_sys::Da64OpType_DA_OP_REGGPEXT => {
let ext = unsafe { &op.__bindgen_anon_2.reggpext };
Operand::GpRegExt(GpRegExt {
reg: unsafe { op.__bindgen_anon_1.reg },
is_64bit: ext.sf() != 0,
extend: Extend::from_raw(ext.ext() as u8),
shift: ext.shift,
})
}
disarm_sys::Da64OpType_DA_OP_REGSP => {
let sf = unsafe { op.__bindgen_anon_2.reggp.sf() };
Operand::Sp(GpReg {
reg: unsafe { op.__bindgen_anon_1.reg },
is_64bit: sf != 0,
})
}
disarm_sys::Da64OpType_DA_OP_REGFP => Operand::FpReg(FpReg {
reg: unsafe { op.__bindgen_anon_1.reg },
size: unsafe { op.__bindgen_anon_2.regfp.size },
}),
disarm_sys::Da64OpType_DA_OP_REGVEC => {
let va = unsafe { op.__bindgen_anon_2.regvec.va };
Operand::VecReg(VecReg {
reg: unsafe { op.__bindgen_anon_1.reg },
arrangement: VectorArrangement::from_raw(va),
})
}
disarm_sys::Da64OpType_DA_OP_REGVTBL => {
let vtbl = unsafe { &op.__bindgen_anon_2.regvtbl };
Operand::VecRegTable(VecRegTable {
reg: unsafe { op.__bindgen_anon_1.reg },
arrangement: VectorArrangement::from_raw(vtbl.va),
count: vtbl.cnt,
})
}
disarm_sys::Da64OpType_DA_OP_REGVIDX => {
let vidx = unsafe { &op.__bindgen_anon_2.regvidx };
Operand::VecRegElement(VecRegElement {
reg: unsafe { op.__bindgen_anon_1.reg },
elem_size: vidx.esize,
elem_index: vidx.elem,
})
}
disarm_sys::Da64OpType_DA_OP_REGVTBLIDX => {
let vtblidx = unsafe { &op.__bindgen_anon_2.regvtblidx };
Operand::VecRegTableElement(VecRegTableElement {
reg: unsafe { op.__bindgen_anon_1.reg },
elem_size: vtblidx.esize() as u8,
elem_index: vtblidx.elem() as u8,
count: vtblidx.cnt,
})
}
disarm_sys::Da64OpType_DA_OP_MEMUOFF => Operand::MemUnsignedOffset(MemUnsignedOffset {
base: unsafe { op.__bindgen_anon_1.reg },
offset: unsafe { op.__bindgen_anon_2.uimm16 },
}),
disarm_sys::Da64OpType_DA_OP_MEMSOFF => Operand::MemSignedOffset(MemSignedOffset {
base: unsafe { op.__bindgen_anon_1.reg },
offset: unsafe { op.__bindgen_anon_2.simm16 },
}),
disarm_sys::Da64OpType_DA_OP_MEMSOFFPRE => Operand::MemPreIndex(MemSignedOffset {
base: unsafe { op.__bindgen_anon_1.reg },
offset: unsafe { op.__bindgen_anon_2.simm16 },
}),
disarm_sys::Da64OpType_DA_OP_MEMSOFFPOST => Operand::MemPostIndex(MemSignedOffset {
base: unsafe { op.__bindgen_anon_1.reg },
offset: unsafe { op.__bindgen_anon_2.simm16 },
}),
disarm_sys::Da64OpType_DA_OP_MEMREG => {
let memreg = unsafe { &op.__bindgen_anon_2.memreg };
Operand::MemRegOffset(MemRegOffset {
base: unsafe { op.__bindgen_anon_1.reg },
offset_reg: memreg.offreg,
extend: Extend::from_raw(memreg.ext() as u8),
shift: memreg.shift() as u8,
has_extend: memreg.sc() != 0,
})
}
disarm_sys::Da64OpType_DA_OP_MEMREGPOST => {
let memreg = unsafe { &op.__bindgen_anon_2.memreg };
Operand::MemRegPost(MemRegOffset {
base: unsafe { op.__bindgen_anon_1.reg },
offset_reg: memreg.offreg,
extend: Extend::from_raw(memreg.ext() as u8),
shift: memreg.shift() as u8,
has_extend: memreg.sc() != 0,
})
}
disarm_sys::Da64OpType_DA_OP_MEMINC => Operand::MemInc {
base: unsafe { op.__bindgen_anon_1.reg },
},
disarm_sys::Da64OpType_DA_OP_COND => {
Operand::Condition(Condition::from_raw(unsafe { op.__bindgen_anon_2.cond }))
}
disarm_sys::Da64OpType_DA_OP_PRFOP => {
Operand::Prefetch(PrefetchOp::from_raw(unsafe { op.__bindgen_anon_1.prfop }))
}
disarm_sys::Da64OpType_DA_OP_SYSREG => {
Operand::SysReg(unsafe { op.__bindgen_anon_2.sysreg })
}
disarm_sys::Da64OpType_DA_OP_IMMSMALL => {
Operand::ImmSmall(unsafe { op.__bindgen_anon_2.uimm16 })
}
disarm_sys::Da64OpType_DA_OP_SIMM => {
Operand::ImmSigned(unsafe { op.__bindgen_anon_2.simm16 })
}
disarm_sys::Da64OpType_DA_OP_UIMM => {
Operand::ImmUnsigned(unsafe { op.__bindgen_anon_2.uimm16 })
}
disarm_sys::Da64OpType_DA_OP_UIMMSHIFT => {
let immshift = unsafe { &op.__bindgen_anon_1.immshift };
Operand::ImmShifted(ShiftedImm {
value: unsafe { op.__bindgen_anon_2.uimm16 },
shift: immshift.shift() as u8,
shift_type: if immshift.mask() != 0 {
ShiftType::Msl
} else {
ShiftType::Lsl
},
})
}
disarm_sys::Da64OpType_DA_OP_IMMLARGE => Operand::ImmLarge(imm64),
disarm_sys::Da64OpType_DA_OP_RELADDR => Operand::RelAddr(imm64),
disarm_sys::Da64OpType_DA_OP_IMMFLOAT => Operand::ImmFloat(float8),
_ => Operand::None,
}
}
/// Returns true if this is an empty operand slot.
pub fn is_none(&self) -> bool {
matches!(self, Operand::None)
}
}
/// A decoded AArch64 instruction.
#[derive(Clone)]
pub struct Instruction {
inner: disarm_sys::Da64Inst,
}
impl Instruction {
/// Decode a 32-bit AArch64 instruction.
pub fn decode(inst: u32) -> Self {
let mut inner = MaybeUninit::<disarm_sys::Da64Inst>::uninit();
unsafe {
disarm_sys::da64_decode(inst, inner.as_mut_ptr());
Self {
inner: inner.assume_init(),
}
}
}
/// Get the instruction mnemonic kind.
pub fn mnemonic(&self) -> u16 {
self.inner.mnem
}
/// Get the number of operands (excluding empty slots).
pub fn num_operands(&self) -> usize {
self.inner
.ops
.iter()
.take_while(|op| op.type_ != disarm_sys::Da64OpType_DA_OP_NONE as u8)
.count()
}
/// Get an iterator over the operands.
pub fn operands(&self) -> impl Iterator<Item = Operand> + '_ {
let imm64 = unsafe { self.inner.__bindgen_anon_1.imm64 };
let float8 = unsafe { self.inner.__bindgen_anon_1.float8 };
self.inner
.ops
.iter()
.map(move |op| Operand::from_raw(op, imm64, float8))
.take_while(|op| !op.is_none())
}
/// Get all operands as a fixed-size array (including empty slots).
pub fn operands_all(&self) -> [Operand; 5] {
let imm64 = unsafe { self.inner.__bindgen_anon_1.imm64 };
let float8 = unsafe { self.inner.__bindgen_anon_1.float8 };
[
Operand::from_raw(&self.inner.ops[0], imm64, float8),
Operand::from_raw(&self.inner.ops[1], imm64, float8),
Operand::from_raw(&self.inner.ops[2], imm64, float8),
Operand::from_raw(&self.inner.ops[3], imm64, float8),
Operand::from_raw(&self.inner.ops[4], imm64, float8),
]
}
/// Get the large immediate value (for ImmLarge/RelAddr operands).
pub fn imm64(&self) -> u64 {
unsafe { self.inner.__bindgen_anon_1.imm64 }
}
/// Get the floating-point immediate value.
pub fn float_imm(&self) -> f32 {
unsafe { self.inner.__bindgen_anon_1.float8 }
}
/// Format the instruction as a string.
pub fn format(&self) -> String {
let mut buf = [0u8; 128];
unsafe {
disarm_sys::da64_format(&self.inner, buf.as_mut_ptr() as *mut i8);
}
let len = buf.iter().position(|&c| c == 0).unwrap_or(buf.len());
String::from_utf8_lossy(&buf[..len]).into_owned()
}
/// Format the instruction with an absolute address base.
///
/// This is useful for displaying PC-relative addresses correctly.
pub fn format_absolute(&self, addr: u64) -> String {
let mut buf = [0u8; 128];
unsafe {
disarm_sys::da64_format_abs(&self.inner, addr, buf.as_mut_ptr() as *mut i8);
}
let len = buf.iter().position(|&c| c == 0).unwrap_or(buf.len());
String::from_utf8_lossy(&buf[..len]).into_owned()
}
/// Get access to the raw instruction data.
pub fn raw(&self) -> &disarm_sys::Da64Inst {
&self.inner
}
}
impl fmt::Display for Instruction {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.format())
}
}
impl fmt::Debug for Instruction {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Instruction")
.field("mnemonic", &self.mnemonic())
.field("formatted", &self.format())
.finish()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_decode_nop() {
let inst = Instruction::decode(0xD503201F);
let formatted = inst.format();
assert_eq!(formatted, "hint #0x0");
}
#[test]
fn test_decode_ret() {
// RET instruction
let inst = Instruction::decode(0xD65F03C0);
let formatted = inst.format();
assert_eq!(formatted, "ret x30");
}
#[test]
fn test_display() {
let inst = Instruction::decode(0xD503201F);
assert_eq!(format!("{}", inst), "hint #0x0");
}
#[test]
fn test_operands_add() {
// ADD X0, X1, X2
let inst = Instruction::decode(0x8B020020);
println!("Instruction: {}", inst.format());
let ops: Vec<_> = inst.operands().collect();
println!("Operands: {:?}", ops);
assert_eq!(ops.len(), 3);
match ops[0] {
Operand::GpReg(r) => {
assert_eq!(r.reg, 0);
assert!(r.is_64bit);
}
_ => panic!("Expected GpReg for op[0], got {:?}", ops[0]),
}
match ops[1] {
Operand::GpReg(r) => {
assert_eq!(r.reg, 1);
assert!(r.is_64bit);
}
_ => panic!("Expected GpReg for op[1], got {:?}", ops[1]),
}
match ops[2] {
Operand::GpReg(r) => {
assert_eq!(r.reg, 2);
assert!(r.is_64bit);
}
Operand::GpRegExt(r) => {
// ADD with shifted register uses extended form
assert_eq!(r.reg, 2);
assert!(r.is_64bit);
}
_ => panic!("Expected GpReg or GpRegExt for op[2], got {:?}", ops[2]),
}
}
#[test]
fn test_operands_ldr() {
// LDR X0, [X1, #8]
let inst = Instruction::decode(0xF9400420);
let ops: Vec<_> = inst.operands().collect();
assert_eq!(ops.len(), 2);
match ops[0] {
Operand::GpReg(r) => {
assert_eq!(r.reg, 0);
assert!(r.is_64bit);
}
_ => panic!("Expected GpReg"),
}
match ops[1] {
Operand::MemUnsignedOffset(m) => {
assert_eq!(m.base, 1);
assert_eq!(m.offset, 8);
}
_ => panic!("Expected MemUnsignedOffset, got {:?}", ops[1]),
}
}
#[test]
fn test_operands_branch() {
// B.EQ +0x100
let inst = Instruction::decode(0x54000800);
let ops: Vec<_> = inst.operands().collect();
// Should have condition and relative address
assert!(
ops.iter()
.any(|op| matches!(op, Operand::Condition(Condition::Eq)))
);
}
#[test]
fn test_32bit_registers() {
// ADD W0, W1, W2
let inst = Instruction::decode(0x0B020020);
let ops: Vec<_> = inst.operands().collect();
assert_eq!(ops.len(), 3);
match ops[0] {
Operand::GpReg(r) => {
assert_eq!(r.reg, 0);
assert!(!r.is_64bit);
}
_ => panic!("Expected GpReg, got {:?}", ops[0]),
}
}
#[test]
fn test_str_pre_index() {
// STR X0, [X1, #-16]!
let inst = Instruction::decode(0xF81F0C20);
let ops: Vec<_> = inst.operands().collect();
assert_eq!(ops.len(), 2);
match ops[1] {
Operand::MemPreIndex(m) => {
assert_eq!(m.base, 1);
assert_eq!(m.offset, -16);
}
_ => panic!("Expected MemPreIndex, got {:?}", ops[1]),
}
}
#[test]
fn test_ldr_post_index() {
// LDR X0, [X1], #16
let inst = Instruction::decode(0xF8410420);
let ops: Vec<_> = inst.operands().collect();
assert_eq!(ops.len(), 2);
match ops[1] {
Operand::MemPostIndex(m) => {
assert_eq!(m.base, 1);
assert_eq!(m.offset, 16);
}
_ => panic!("Expected MemPostIndex, got {:?}", ops[1]),
}
}
#[test]
fn test_ldr_register_offset() {
// LDR X0, [X1, X2]
let inst = Instruction::decode(0xF8626820);
let ops: Vec<_> = inst.operands().collect();
assert_eq!(ops.len(), 2);
match ops[1] {
Operand::MemRegOffset(m) => {
assert_eq!(m.base, 1);
assert_eq!(m.offset_reg, 2);
}
_ => panic!("Expected MemRegOffset, got {:?}", ops[1]),
}
}
#[test]
fn test_mov_immediate() {
// MOV X0, #0x1234
let inst = Instruction::decode(0xD2824680);
let ops: Vec<_> = inst.operands().collect();
assert_eq!(ops.len(), 2);
match ops[0] {
Operand::GpReg(r) => {
assert_eq!(r.reg, 0);
assert!(r.is_64bit);
}
_ => panic!("Expected GpReg, got {:?}", ops[0]),
}
}
#[test]
fn test_fmov_register() {
// FMOV D0, D1
let inst = Instruction::decode(0x1E604020);
let ops: Vec<_> = inst.operands().collect();
assert_eq!(ops.len(), 2);
match ops[0] {
Operand::FpReg(r) => {
assert_eq!(r.reg, 0);
}
_ => panic!("Expected FpReg, got {:?}", ops[0]),
}
match ops[1] {
Operand::FpReg(r) => {
assert_eq!(r.reg, 1);
}
_ => panic!("Expected FpReg, got {:?}", ops[1]),
}
}
#[test]
fn test_simd_add_vector() {
// ADD V0.16B, V1.16B, V2.16B
let inst = Instruction::decode(0x4E228420);
let ops: Vec<_> = inst.operands().collect();
assert_eq!(ops.len(), 3);
match ops[0] {
Operand::VecReg(v) => {
assert_eq!(v.reg, 0);
assert_eq!(v.arrangement, VectorArrangement::B16);
}
_ => panic!("Expected VecReg, got {:?}", ops[0]),
}
}
#[test]
fn test_csel() {
// CSEL X0, X1, X2, EQ
let inst = Instruction::decode(0x9A820020);
let ops: Vec<_> = inst.operands().collect();
assert!(
ops.iter()
.any(|op| matches!(op, Operand::Condition(Condition::Eq)))
);
}
#[test]
fn test_cbz() {
// CBZ X0, +0x100
let inst = Instruction::decode(0xB4000800);
let ops: Vec<_> = inst.operands().collect();
assert_eq!(ops.len(), 2);
match ops[0] {
Operand::GpReg(r) => {
assert_eq!(r.reg, 0);
assert!(r.is_64bit);
}
_ => panic!("Expected GpReg, got {:?}", ops[0]),
}
match ops[1] {
Operand::RelAddr(addr) => {
assert_eq!(addr, 0x100);
}
_ => panic!("Expected RelAddr, got {:?}", ops[1]),
}
}
#[test]
fn test_bl() {
// BL +0x1000
let inst = Instruction::decode(0x94000400);
let ops: Vec<_> = inst.operands().collect();
assert_eq!(ops.len(), 1);
match ops[0] {
Operand::RelAddr(addr) => {
assert_eq!(addr, 0x1000);
}
_ => panic!("Expected RelAddr, got {:?}", ops[0]),
}
}
#[test]
fn test_adr() {
// ADR X0, +0x100
let inst = Instruction::decode(0x10000800);
let ops: Vec<_> = inst.operands().collect();
assert_eq!(ops.len(), 2);
match ops[0] {
Operand::GpReg(r) => {
assert_eq!(r.reg, 0);
assert!(r.is_64bit);
}
_ => panic!("Expected GpReg, got {:?}", ops[0]),
}
}
#[test]
fn test_stp() {
// STP X0, X1, [SP, #16]
let inst = Instruction::decode(0xa90107e0);
let ops: Vec<_> = inst.operands().collect();
assert_eq!(ops.len(), 3);
match ops[0] {
Operand::GpReg(r) => assert_eq!(r.reg, 0),
_ => panic!("Expected GpReg, got {:?}", ops[0]),
}
match ops[1] {
Operand::GpReg(r) => assert_eq!(r.reg, 1),
_ => panic!("Expected GpReg, got {:?}", ops[1]),
}
}
#[test]
fn test_ldp() {
// LDP X29, X30, [SP], #16
let inst = Instruction::decode(0xA8C17BFD);
let ops: Vec<_> = inst.operands().collect();
match ops[0] {
Operand::GpReg(r) => assert_eq!(r.reg, 29),
_ => panic!("Expected GpReg, got {:?}", ops[0]),
}
match ops[1] {
Operand::GpReg(r) => assert_eq!(r.reg, 30),
_ => panic!("Expected GpReg, got {:?}", ops[1]),
}
}
#[test]
fn test_sub_sp() {
// SUB SP, SP, #0x20
let inst = Instruction::decode(0xD10083FF);
let ops: Vec<_> = inst.operands().collect();
// First operand should be SP
match ops[0] {
Operand::Sp(r) => assert_eq!(r.reg, 31),
_ => panic!("Expected Sp, got {:?}", ops[0]),
}
}
#[test]
fn test_madd() {
// MADD X0, X1, X2, X3
let inst = Instruction::decode(0x9B020C20);
let ops: Vec<_> = inst.operands().collect();
assert_eq!(ops.len(), 4);
for (i, expected_reg) in [0, 1, 2, 3].iter().enumerate() {
match ops[i] {
Operand::GpReg(r) => assert_eq!(r.reg, *expected_reg),
_ => panic!("Expected GpReg for op[{}], got {:?}", i, ops[i]),
}
}
}
#[test]
fn test_format_absolute() {
// BL +0x1000
let inst = Instruction::decode(0x94000400);
let formatted = inst.format_absolute(0x1000);
assert!(formatted.contains("0x2000") || formatted.contains("2000"));
}
#[test]
fn test_num_operands() {
// NOP has 1 operand (the hint immediate)
let nop = Instruction::decode(0xD503201F);
assert_eq!(nop.num_operands(), 1);
// ADD X0, X1, X2 has 3 operands
let add = Instruction::decode(0x8B020020);
assert_eq!(add.num_operands(), 3);
// RET has 1 operand (x30)
let ret = Instruction::decode(0xD65F03C0);
assert_eq!(ret.num_operands(), 1);
}
#[test]
fn test_operands_all() {
// ADD X0, X1, X2
let inst = Instruction::decode(0x8B020020);
let ops = inst.operands_all();
assert_eq!(ops.len(), 5);
// First 3 should be operands, rest should be None
assert!(!ops[0].is_none());
assert!(!ops[1].is_none());
assert!(!ops[2].is_none());
assert!(ops[3].is_none());
assert!(ops[4].is_none());
}
#[test]
fn test_conditions() {
// Test various condition codes
let conditions = [
(0x54000000, Condition::Eq), // B.EQ
(0x54000001, Condition::Ne), // B.NE
(0x5400000A, Condition::Ge), // B.GE
(0x5400000B, Condition::Lt), // B.LT
(0x5400000C, Condition::Gt), // B.GT
(0x5400000D, Condition::Le), // B.LE
];
for (encoding, expected_cond) in conditions {
let inst = Instruction::decode(encoding);
let ops: Vec<_> = inst.operands().collect();
assert!(
ops.iter()
.any(|op| matches!(op, Operand::Condition(c) if *c == expected_cond)),
"Expected {:?} for encoding {:#x}",
expected_cond,
encoding
);
}
}
}
|
zyedidia/rdisarm
| 0
|
Rust
|
zyedidia
|
Zachary Yedidia
|
Stanford University
|
|
fadec-sys/build.rs
|
Rust
|
use std::env;
use std::path::PathBuf;
use std::process::Command;
fn main() {
let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap());
let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());
let fadec_dir = manifest_dir.join("fadec");
// Generate the decode tables using parseinstrs.py
let out_public = out_dir.join("fadec-decode-public.inc");
let out_private = out_dir.join("fadec-decode-private.inc");
let status = Command::new("python3")
.args([
fadec_dir.join("parseinstrs.py").to_str().unwrap(),
"decode",
fadec_dir.join("instrs.txt").to_str().unwrap(),
out_public.to_str().unwrap(),
out_private.to_str().unwrap(),
"--32",
"--64",
])
.status()
.expect("Failed to run parseinstrs.py");
if !status.success() {
panic!("parseinstrs.py failed");
}
// Build the C library
let mut build = cc::Build::new();
build
.include(&fadec_dir)
.include(&out_dir)
.flag_if_supported("-std=c11")
.flag_if_supported("-fstrict-aliasing");
if cfg!(feature = "decode") {
build.file(fadec_dir.join("decode.c"));
build.file(fadec_dir.join("format.c"));
}
if cfg!(feature = "encode") {
build.file(fadec_dir.join("encode.c"));
}
build.compile("fadec");
// Tell cargo to invalidate the built crate whenever these files change
println!("cargo:rerun-if-changed=fadec/fadec.h");
println!("cargo:rerun-if-changed=fadec/decode.c");
println!("cargo:rerun-if-changed=fadec/format.c");
println!("cargo:rerun-if-changed=fadec/encode.c");
println!("cargo:rerun-if-changed=fadec/instrs.txt");
println!("cargo:rerun-if-changed=fadec/parseinstrs.py");
}
|
zyedidia/rfadec
| 0
|
Rust
|
zyedidia
|
Zachary Yedidia
|
Stanford University
|
|
fadec-sys/src/lib.rs
|
Rust
|
//! Low-level FFI bindings to the fadec x86 decoder library.
//!
//! This crate provides raw bindings to the fadec C library. For a safe,
//! ergonomic Rust API, use the `rfadec` crate instead.
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
#![allow(non_upper_case_globals)]
use std::ffi::c_char;
use std::os::raw::c_int;
/// Register identifiers
pub type FdReg = u32;
pub const FD_REG_R0: FdReg = 0;
pub const FD_REG_R1: FdReg = 1;
pub const FD_REG_R2: FdReg = 2;
pub const FD_REG_R3: FdReg = 3;
pub const FD_REG_R4: FdReg = 4;
pub const FD_REG_R5: FdReg = 5;
pub const FD_REG_R6: FdReg = 6;
pub const FD_REG_R7: FdReg = 7;
pub const FD_REG_R8: FdReg = 8;
pub const FD_REG_R9: FdReg = 9;
pub const FD_REG_R10: FdReg = 10;
pub const FD_REG_R11: FdReg = 11;
pub const FD_REG_R12: FdReg = 12;
pub const FD_REG_R13: FdReg = 13;
pub const FD_REG_R14: FdReg = 14;
pub const FD_REG_R15: FdReg = 15;
// Alternative names for byte registers
pub const FD_REG_AL: FdReg = 0;
pub const FD_REG_CL: FdReg = 1;
pub const FD_REG_DL: FdReg = 2;
pub const FD_REG_BL: FdReg = 3;
pub const FD_REG_AH: FdReg = 4;
pub const FD_REG_CH: FdReg = 5;
pub const FD_REG_DH: FdReg = 6;
pub const FD_REG_BH: FdReg = 7;
// Alternative names for general purpose registers
pub const FD_REG_AX: FdReg = 0;
pub const FD_REG_CX: FdReg = 1;
pub const FD_REG_DX: FdReg = 2;
pub const FD_REG_BX: FdReg = 3;
pub const FD_REG_SP: FdReg = 4;
pub const FD_REG_BP: FdReg = 5;
pub const FD_REG_SI: FdReg = 6;
pub const FD_REG_DI: FdReg = 7;
// RIP register (64-bit mode only)
pub const FD_REG_IP: FdReg = 0x10;
// Segment registers
pub const FD_REG_ES: FdReg = 0;
pub const FD_REG_CS: FdReg = 1;
pub const FD_REG_SS: FdReg = 2;
pub const FD_REG_DS: FdReg = 3;
pub const FD_REG_FS: FdReg = 4;
pub const FD_REG_GS: FdReg = 5;
// No register specified
pub const FD_REG_NONE: FdReg = 0x3f;
/// Instruction type/mnemonic
pub type FdInstrType = u16;
/// Operand types
pub type FdOpType = u8;
pub const FD_OT_NONE: FdOpType = 0;
pub const FD_OT_REG: FdOpType = 1;
pub const FD_OT_IMM: FdOpType = 2;
pub const FD_OT_MEM: FdOpType = 3;
pub const FD_OT_OFF: FdOpType = 4;
pub const FD_OT_MEMBCST: FdOpType = 5;
/// Register types
pub type FdRegType = u8;
pub const FD_RT_VEC: FdRegType = 0;
pub const FD_RT_GPL: FdRegType = 1;
pub const FD_RT_GPH: FdRegType = 2;
pub const FD_RT_SEG: FdRegType = 3;
pub const FD_RT_FPU: FdRegType = 4;
pub const FD_RT_MMX: FdRegType = 5;
pub const FD_RT_TMM: FdRegType = 6;
pub const FD_RT_MASK: FdRegType = 7;
pub const FD_RT_BND: FdRegType = 8;
pub const FD_RT_CR: FdRegType = 9;
pub const FD_RT_DR: FdRegType = 10;
pub const FD_RT_MEM: FdRegType = 15;
/// Rounding control
pub type FdRoundControl = u8;
pub const FD_RC_RN: FdRoundControl = 1;
pub const FD_RC_RD: FdRoundControl = 3;
pub const FD_RC_RU: FdRoundControl = 5;
pub const FD_RC_RZ: FdRoundControl = 7;
pub const FD_RC_MXCSR: FdRoundControl = 0;
pub const FD_RC_SAE: FdRoundControl = 6;
/// Internal flags
pub const FD_FLAG_LOCK: u8 = 1 << 0;
pub const FD_FLAG_REP: u8 = 1 << 2;
pub const FD_FLAG_REPNZ: u8 = 1 << 1;
pub const FD_FLAG_64: u8 = 1 << 7;
/// Error codes
pub const FD_ERR_UD: c_int = -1;
pub const FD_ERR_INTERNAL: c_int = -2;
pub const FD_ERR_PARTIAL: c_int = -3;
/// Operand structure (internal use)
#[repr(C)]
#[derive(Debug, Clone, Copy, Default)]
pub struct FdOp {
pub type_: u8,
pub size: u8,
pub reg: u8,
pub misc: u8,
}
/// Decoded instruction
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct FdInstr {
pub type_: u16,
pub flags: u8,
pub segment: u8,
pub addrsz: u8,
pub operandsz: u8,
pub size: u8,
pub evex: u8,
pub operands: [FdOp; 4],
pub disp: i64,
pub imm: i64,
pub address: u64,
}
impl Default for FdInstr {
fn default() -> Self {
Self {
type_: 0,
flags: 0,
segment: 0,
addrsz: 0,
operandsz: 0,
size: 0,
evex: 0,
operands: [FdOp::default(); 4],
disp: 0,
imm: 0,
address: 0,
}
}
}
// Accessor macros implemented as functions
/// Gets the type/mnemonic of the instruction.
#[inline]
pub fn FD_TYPE(instr: &FdInstr) -> FdInstrType {
instr.type_
}
/// Gets the address of the instruction.
#[inline]
pub fn FD_ADDRESS(instr: &FdInstr) -> u64 {
instr.address
}
/// Gets the size of the instruction in bytes.
#[inline]
pub fn FD_SIZE(instr: &FdInstr) -> u8 {
instr.size
}
/// Gets the specified segment override, or FD_REG_NONE for default segment.
#[inline]
pub fn FD_SEGMENT(instr: &FdInstr) -> FdReg {
(instr.segment & 0x3f) as FdReg
}
/// Gets the address size attribute of the instruction in bytes.
#[inline]
pub fn FD_ADDRSIZE(instr: &FdInstr) -> u32 {
1 << instr.addrsz
}
/// Gets the logarithmic address size.
#[inline]
pub fn FD_ADDRSIZELG(instr: &FdInstr) -> u8 {
instr.addrsz
}
/// Gets the operation width in bytes.
#[inline]
pub fn FD_OPSIZE(instr: &FdInstr) -> u32 {
1 << instr.operandsz
}
/// Gets the logarithmic operand size.
#[inline]
pub fn FD_OPSIZELG(instr: &FdInstr) -> u8 {
instr.operandsz
}
/// Returns whether the instruction has a REP prefix.
#[inline]
pub fn FD_HAS_REP(instr: &FdInstr) -> bool {
(instr.flags & FD_FLAG_REP) != 0
}
/// Returns whether the instruction has a REPNZ prefix.
#[inline]
pub fn FD_HAS_REPNZ(instr: &FdInstr) -> bool {
(instr.flags & FD_FLAG_REPNZ) != 0
}
/// Returns whether the instruction has a LOCK prefix.
#[inline]
pub fn FD_HAS_LOCK(instr: &FdInstr) -> bool {
(instr.flags & FD_FLAG_LOCK) != 0
}
/// Returns whether the instruction is in 64-bit mode.
#[inline]
pub fn FD_IS64(instr: &FdInstr) -> bool {
(instr.flags & FD_FLAG_64) != 0
}
/// Gets the type of an operand at the given index.
#[inline]
pub fn FD_OP_TYPE(instr: &FdInstr, idx: usize) -> FdOpType {
instr.operands[idx].type_
}
/// Gets the size in bytes of an operand.
#[inline]
pub fn FD_OP_SIZE(instr: &FdInstr, idx: usize) -> u32 {
1 << instr.operands[idx].size >> 1
}
/// Gets the logarithmic size of an operand.
#[inline]
pub fn FD_OP_SIZELG(instr: &FdInstr, idx: usize) -> i8 {
instr.operands[idx].size as i8 - 1
}
/// Gets the accessed register index of a register operand.
#[inline]
pub fn FD_OP_REG(instr: &FdInstr, idx: usize) -> FdReg {
instr.operands[idx].reg as FdReg
}
/// Gets the type of the accessed register.
#[inline]
pub fn FD_OP_REG_TYPE(instr: &FdInstr, idx: usize) -> FdRegType {
instr.operands[idx].misc
}
/// Returns whether the accessed register is a high-byte register.
#[inline]
pub fn FD_OP_REG_HIGH(instr: &FdInstr, idx: usize) -> bool {
FD_OP_REG_TYPE(instr, idx) == FD_RT_GPH
}
/// Gets the index of the base register from a memory operand.
#[inline]
pub fn FD_OP_BASE(instr: &FdInstr, idx: usize) -> FdReg {
instr.operands[idx].reg as FdReg
}
/// Gets the index of the index register from a memory operand.
#[inline]
pub fn FD_OP_INDEX(instr: &FdInstr, idx: usize) -> FdReg {
(instr.operands[idx].misc & 0x3f) as FdReg
}
/// Gets the scale of the index register from a memory operand (as shift amount).
#[inline]
pub fn FD_OP_SCALE(instr: &FdInstr, idx: usize) -> u8 {
instr.operands[idx].misc >> 6
}
/// Gets the sign-extended displacement of a memory operand.
#[inline]
pub fn FD_OP_DISP(instr: &FdInstr, _idx: usize) -> i64 {
instr.disp
}
/// Gets the broadcast size in bytes.
#[inline]
pub fn FD_OP_BCSTSZ(instr: &FdInstr, idx: usize) -> u32 {
1 << FD_OP_BCSTSZLG(instr, idx)
}
/// Gets the logarithmic broadcast size.
#[inline]
pub fn FD_OP_BCSTSZLG(instr: &FdInstr, _idx: usize) -> u8 {
instr.segment >> 6
}
/// Gets the immediate value.
#[inline]
pub fn FD_OP_IMM(instr: &FdInstr, _idx: usize) -> i64 {
instr.imm
}
/// Gets the opmask register for EVEX-encoded instructions.
#[inline]
pub fn FD_MASKREG(instr: &FdInstr) -> u8 {
instr.evex & 0x07
}
/// Returns whether zero masking is used.
#[inline]
pub fn FD_MASKZERO(instr: &FdInstr) -> bool {
(instr.evex & 0x80) != 0
}
/// Gets the rounding mode for EVEX-encoded instructions.
#[inline]
pub fn FD_ROUNDCONTROL(instr: &FdInstr) -> FdRoundControl {
(instr.evex & 0x70) >> 4
}
unsafe extern "C" {
/// Decode an instruction.
///
/// # Arguments
/// * `buf` - Buffer containing instruction bytes
/// * `len` - Length of the buffer (max 15 bytes will be read)
/// * `mode` - Decoding mode: 32 or 64
/// * `address` - Virtual address (use 0 for FD_OT_OFF operands)
/// * `out_instr` - Output instruction buffer
///
/// # Returns
/// Number of bytes consumed, or negative error code
pub fn fd_decode(
buf: *const u8,
len: usize,
mode: c_int,
address: usize,
out_instr: *mut FdInstr,
) -> c_int;
/// Format an instruction to a string.
pub fn fd_format(instr: *const FdInstr, buf: *mut c_char, len: usize);
/// Format an instruction to a string with absolute address.
pub fn fd_format_abs(instr: *const FdInstr, addr: u64, buf: *mut c_char, len: usize);
/// Get the name of an instruction type.
pub fn fdi_name(ty: FdInstrType) -> *const c_char;
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_decode_nop() {
let code = [0x90u8]; // NOP
let mut instr = FdInstr::default();
unsafe {
let result = fd_decode(code.as_ptr(), code.len(), 64, 0, &mut instr);
assert_eq!(result, 1);
assert_eq!(FD_SIZE(&instr), 1);
}
}
#[test]
fn test_decode_xchg() {
let code = [0x49u8, 0x90]; // xchg r8, rax
let mut instr = FdInstr::default();
unsafe {
let result = fd_decode(code.as_ptr(), code.len(), 64, 0, &mut instr);
assert_eq!(result, 2);
assert_eq!(FD_SIZE(&instr), 2);
}
}
#[test]
fn test_format() {
let code = [0x49u8, 0x90]; // xchg r8, rax
let mut instr = FdInstr::default();
let mut buf = [0i8; 64];
unsafe {
fd_decode(code.as_ptr(), code.len(), 64, 0, &mut instr);
fd_format(&instr, buf.as_mut_ptr(), buf.len());
let s = std::ffi::CStr::from_ptr(buf.as_ptr());
assert_eq!(s.to_str().unwrap(), "xchg r8, rax");
}
}
}
|
zyedidia/rfadec
| 0
|
Rust
|
zyedidia
|
Zachary Yedidia
|
Stanford University
|
|
src/lib.rs
|
Rust
|
//! Safe Rust bindings for the fadec x86/x86-64 decoder.
//!
//! # Example
//!
//! ```
//! use rfadec::{Decoder, Mode};
//!
//! let code = [0x48, 0x89, 0xc3]; // mov rbx, rax
//! let decoder = Decoder::new(Mode::Long);
//!
//! if let Some(instr) = decoder.decode(&code) {
//! println!("{}", instr);
//! }
//! ```
use std::fmt;
pub use fadec_sys;
/// Decoding mode
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Mode {
/// 32-bit protected/compatibility mode
Protected = 32,
/// 64-bit long mode
Long = 64,
}
/// Operand type
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OpType {
/// No operand
None,
/// Register operand
Reg,
/// Immediate operand
Imm,
/// Memory operand
Mem,
/// Offset operand (for relative jumps/calls)
Off,
/// Memory operand with broadcast
MemBcst,
}
impl From<fadec_sys::FdOpType> for OpType {
fn from(ty: fadec_sys::FdOpType) -> Self {
match ty {
fadec_sys::FD_OT_NONE => OpType::None,
fadec_sys::FD_OT_REG => OpType::Reg,
fadec_sys::FD_OT_IMM => OpType::Imm,
fadec_sys::FD_OT_MEM => OpType::Mem,
fadec_sys::FD_OT_OFF => OpType::Off,
fadec_sys::FD_OT_MEMBCST => OpType::MemBcst,
_ => OpType::None,
}
}
}
/// Register type
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RegType {
/// Vector register (XMM/YMM/ZMM)
Vec,
/// Low general purpose register
Gpl,
/// High-byte general purpose register (AH, BH, CH, DH)
Gph,
/// Segment register
Seg,
/// FPU register ST(n)
Fpu,
/// MMX register
Mmx,
/// TMM register
Tmm,
/// Mask register (K0-K7)
Mask,
/// Bound register
Bnd,
/// Control register
Cr,
/// Debug register
Dr,
/// Memory operand marker
Mem,
}
impl From<fadec_sys::FdRegType> for RegType {
fn from(ty: fadec_sys::FdRegType) -> Self {
match ty {
fadec_sys::FD_RT_VEC => RegType::Vec,
fadec_sys::FD_RT_GPL => RegType::Gpl,
fadec_sys::FD_RT_GPH => RegType::Gph,
fadec_sys::FD_RT_SEG => RegType::Seg,
fadec_sys::FD_RT_FPU => RegType::Fpu,
fadec_sys::FD_RT_MMX => RegType::Mmx,
fadec_sys::FD_RT_TMM => RegType::Tmm,
fadec_sys::FD_RT_MASK => RegType::Mask,
fadec_sys::FD_RT_BND => RegType::Bnd,
fadec_sys::FD_RT_CR => RegType::Cr,
fadec_sys::FD_RT_DR => RegType::Dr,
fadec_sys::FD_RT_MEM => RegType::Mem,
_ => RegType::Gpl,
}
}
}
/// Decode error
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DecodeError {
/// Invalid/undefined instruction
Undefined,
/// Internal decoder error
Internal,
/// Incomplete instruction (need more bytes)
Partial,
}
/// A decoded x86 instruction
#[derive(Clone, Copy)]
pub struct Instruction {
inner: fadec_sys::FdInstr,
}
impl Instruction {
/// Returns the instruction type/mnemonic as a raw value.
#[inline]
pub fn mnemonic(&self) -> u16 {
fadec_sys::FD_TYPE(&self.inner)
}
/// Returns the size of the instruction in bytes.
#[inline]
pub fn size(&self) -> usize {
fadec_sys::FD_SIZE(&self.inner) as usize
}
/// Returns the address size in bytes.
#[inline]
pub fn addr_size(&self) -> u32 {
fadec_sys::FD_ADDRSIZE(&self.inner)
}
/// Returns the operand size in bytes.
#[inline]
pub fn op_size(&self) -> u32 {
fadec_sys::FD_OPSIZE(&self.inner)
}
/// Returns whether the instruction has a LOCK prefix.
#[inline]
pub fn has_lock(&self) -> bool {
fadec_sys::FD_HAS_LOCK(&self.inner)
}
/// Returns whether the instruction has a REP prefix.
#[inline]
pub fn has_rep(&self) -> bool {
fadec_sys::FD_HAS_REP(&self.inner)
}
/// Returns whether the instruction has a REPNZ prefix.
#[inline]
pub fn has_repnz(&self) -> bool {
fadec_sys::FD_HAS_REPNZ(&self.inner)
}
/// Returns the type of operand at the given index.
#[inline]
pub fn op_type(&self, idx: usize) -> OpType {
OpType::from(fadec_sys::FD_OP_TYPE(&self.inner, idx))
}
/// Returns the size of operand at the given index in bytes.
#[inline]
pub fn op_size_at(&self, idx: usize) -> u32 {
fadec_sys::FD_OP_SIZE(&self.inner, idx)
}
/// Returns the register index for a register operand.
#[inline]
pub fn op_reg(&self, idx: usize) -> u32 {
fadec_sys::FD_OP_REG(&self.inner, idx)
}
/// Returns the register type for a register operand.
#[inline]
pub fn op_reg_type(&self, idx: usize) -> RegType {
RegType::from(fadec_sys::FD_OP_REG_TYPE(&self.inner, idx))
}
/// Returns the base register for a memory operand.
#[inline]
pub fn op_base(&self, idx: usize) -> Option<u32> {
let base = fadec_sys::FD_OP_BASE(&self.inner, idx);
if base == fadec_sys::FD_REG_NONE {
None
} else {
Some(base)
}
}
/// Returns the index register for a memory operand.
#[inline]
pub fn op_index(&self, idx: usize) -> Option<u32> {
let index = fadec_sys::FD_OP_INDEX(&self.inner, idx);
if index == fadec_sys::FD_REG_NONE {
None
} else {
Some(index)
}
}
/// Returns the scale (as shift amount, 0-3) for a memory operand.
#[inline]
pub fn op_scale(&self, idx: usize) -> u8 {
fadec_sys::FD_OP_SCALE(&self.inner, idx)
}
/// Returns the displacement for a memory operand.
#[inline]
pub fn op_disp(&self, idx: usize) -> i64 {
fadec_sys::FD_OP_DISP(&self.inner, idx)
}
/// Returns the immediate value.
#[inline]
pub fn op_imm(&self, idx: usize) -> i64 {
fadec_sys::FD_OP_IMM(&self.inner, idx)
}
/// Formats the instruction to a string.
pub fn format(&self) -> String {
self.format_abs(0)
}
/// Formats the instruction to a string with an absolute address for offset operands.
pub fn format_abs(&self, addr: u64) -> String {
let mut buf = [0i8; 128];
unsafe {
fadec_sys::fd_format_abs(&self.inner, addr, buf.as_mut_ptr(), buf.len());
std::ffi::CStr::from_ptr(buf.as_ptr())
.to_string_lossy()
.into_owned()
}
}
/// Returns a reference to the underlying raw instruction.
#[inline]
pub fn raw(&self) -> &fadec_sys::FdInstr {
&self.inner
}
}
impl fmt::Display for Instruction {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.format())
}
}
impl fmt::Debug for Instruction {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Instruction")
.field("mnemonic", &self.mnemonic())
.field("size", &self.size())
.field("formatted", &self.format())
.finish()
}
}
/// An x86 instruction decoder
#[derive(Debug, Clone, Copy)]
pub struct Decoder {
mode: Mode,
}
impl Decoder {
/// Creates a new decoder for the specified mode.
pub fn new(mode: Mode) -> Self {
Self { mode }
}
/// Decodes a single instruction from the given bytes.
///
/// Returns `Some(Instruction)` on success, or `None` on failure.
pub fn decode(&self, bytes: &[u8]) -> Option<Instruction> {
self.try_decode(bytes).ok()
}
/// Decodes a single instruction from the given bytes.
///
/// Returns `Ok(Instruction)` on success, or `Err(DecodeError)` on failure.
pub fn try_decode(&self, bytes: &[u8]) -> Result<Instruction, DecodeError> {
let mut instr = fadec_sys::FdInstr::default();
let result = unsafe {
fadec_sys::fd_decode(
bytes.as_ptr(),
bytes.len(),
self.mode as i32,
0,
&mut instr,
)
};
if result > 0 {
Ok(Instruction { inner: instr })
} else {
Err(match result {
fadec_sys::FD_ERR_UD => DecodeError::Undefined,
fadec_sys::FD_ERR_INTERNAL => DecodeError::Internal,
fadec_sys::FD_ERR_PARTIAL => DecodeError::Partial,
_ => DecodeError::Internal,
})
}
}
/// Returns an iterator that decodes all instructions from the given bytes.
pub fn decode_all<'a>(&'a self, bytes: &'a [u8]) -> DecodeIter<'a> {
DecodeIter {
decoder: self,
bytes,
offset: 0,
}
}
}
/// Iterator over decoded instructions
pub struct DecodeIter<'a> {
decoder: &'a Decoder,
bytes: &'a [u8],
offset: usize,
}
impl<'a> Iterator for DecodeIter<'a> {
type Item = Result<Instruction, DecodeError>;
fn next(&mut self) -> Option<Self::Item> {
if self.offset >= self.bytes.len() {
return None;
}
let result = self.decoder.try_decode(&self.bytes[self.offset..]);
match &result {
Ok(instr) => self.offset += instr.size(),
Err(_) => self.offset = self.bytes.len(), // Stop on error
}
Some(result)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_decode_nop() {
let decoder = Decoder::new(Mode::Long);
let instr = decoder.decode(&[0x90]).unwrap();
assert_eq!(instr.size(), 1);
assert_eq!(instr.format(), "nop");
}
#[test]
fn test_decode_mov() {
let decoder = Decoder::new(Mode::Long);
let instr = decoder.decode(&[0x48, 0x89, 0xc3]).unwrap(); // mov rbx, rax
assert_eq!(instr.size(), 3);
assert_eq!(instr.format(), "mov rbx, rax");
}
#[test]
fn test_decode_xchg() {
let decoder = Decoder::new(Mode::Long);
let instr = decoder.decode(&[0x49, 0x90]).unwrap(); // xchg r8, rax
assert_eq!(instr.size(), 2);
assert_eq!(instr.format(), "xchg r8, rax");
}
#[test]
fn test_decode_all() {
let decoder = Decoder::new(Mode::Long);
let code = [0x90, 0x90, 0x90]; // three NOPs
let instrs: Vec<_> = decoder.decode_all(&code).collect();
assert_eq!(instrs.len(), 3);
for instr in instrs {
assert_eq!(instr.unwrap().format(), "nop");
}
}
#[test]
fn test_decode_error() {
let decoder = Decoder::new(Mode::Long);
// Test with an incomplete instruction (lone REX prefix)
let result = decoder.try_decode(&[0x48]);
assert_eq!(result.unwrap_err(), DecodeError::Partial);
}
#[test]
fn test_32bit_mode() {
let decoder = Decoder::new(Mode::Protected);
let instr = decoder.decode(&[0x89, 0xc3]).unwrap(); // mov ebx, eax
assert_eq!(instr.format(), "mov ebx, eax");
}
}
|
zyedidia/rfadec
| 0
|
Rust
|
zyedidia
|
Zachary Yedidia
|
Stanford University
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.