More utils files, some reorganization

This commit is contained in:
hppeng 2023-04-01 17:06:12 -07:00
parent b157f79fc0
commit f656c944e8
12 changed files with 238 additions and 2005 deletions

1
js/c++/.gitignore vendored Normal file
View file

@ -0,0 +1 @@
*.out

View file

@ -1,15 +1,15 @@
CXX=emcc
CXXFLAGS=-sENVIRONMENT=web -sSINGLE_FILE -sMODULARIZE -sWASM_ASYNC_COMPILATION=0 -lembind --closure 1
CXXFLAGS=-sENVIRONMENT=web -sSINGLE_FILE -sMODULARIZE -sWASM_ASYNC_COMPILATION=0 -sALLOW_MEMORY_GROWTH -lembind --closure 1
all: utils.js powders.js
%.js: %.cpp
$(CXX) $(CXXFLAGS) -sEXPORT_NAME=create_$* -o $@.out $<
%.js:
$(CXX) $(CXXFLAGS) -sEXPORT_NAME=create_$* -o $@.out $^
cat $@.out $@.in > ../$@
powders.js: powders.cpp
utils.js: utils.cpp
utils.js: utils.cpp utils/math_utils.cpp utils/base64.cpp
.PHONY: clean
clean:

0
js/c++/js_types.h Normal file
View file

File diff suppressed because one or more lines are too long

View file

@ -4,47 +4,77 @@ using namespace emscripten;
#endif
#include "utils.h"
#include "utils/math_utils.h"
#include "utils/base64.h"
#include <algorithm>
#include <vector>
/**
* Clamp number between low and high values.
*
* @param num: value to clamp
* @param low
* @param high
*
* @return clamped value
*/
float clamp(float num, float low, float high) {
return std::min(std::max(num, low), high);
}
namespace utils {
// Permutations in js reference (also cool algorithm):
// https://stackoverflow.com/a/41068709
//function perm(a){
// if (a.length == 0) return [[]];
// var r = [[a[0]]],
// t = [],
// s = [];
// if (a.length == 1) return r;
// for (var i = 1, la = a.length; i < la; i++){
// for (var j = 0, lr = r.length; j < lr; j++){
// r[j].push(a[i]);
// t.push(r[j]);
// for(var k = 1, lrj = r[j].length; k < lrj; k++){
// for (var l = 0; l < lrj; l++) s[l] = r[j][(k+l)%lrj];
// t[t.length] = s;
// s = [];
// }
// }
// r = t;
// t = [];
// }
// return r;
//}
// Uses Heap's method: https://stackoverflow.com/a/37580979
// https://en.wikipedia.org/wiki/Heap%27s_algorithm
// Note: different from old wynnbuilder permutation generator (https://stackoverflow.com/a/41068709)
template<typename T>
std::vector<std::vector<T>> perm(std::vector<T> a) {
std::vector<std::vector<T>> result;
result.push_back(a); // copy assignment
int l = a.size(); // haha signed int
std::vector<int> c(l, 0);
int i = 1;
while (i < l) {
if (c[i] < i) {
if (i % 2) {
// odd.
std::iter_swap(a.begin()+c[i], a.begin()+i);
}
else {
// even.
std::iter_swap(a.begin(), a.begin()+i);
}
result.push_back(a);
c[i] += 1;
i = 1;
}
else {
c[i] = 0;
i++;
}
}
return result;
}
#ifdef __EMSCRIPTEN__
val __perm_wrap(val a) {
const size_t l = a["length"].as<size_t>();
std::vector<val> things;
for (size_t i = 0; i < l; ++i) {
things.push_back(a[i]);
}
std::vector<std::vector<val>> res = perm(things);
val return_array = val::array();
for (auto it = res.begin(); it != res.end(); ++it) {
auto& subarray = *it;
val return_subarray = val::array();
for (auto it2 = subarray.begin(); it2 != subarray.end(); ++it2) {
return_subarray.call<void>("push", *it2);
}
return_array.call<void>("push", return_subarray);
}
return return_array;
}
#endif
#ifdef __EMSCRIPTEN__
EMSCRIPTEN_BINDINGS(utils) {
function("clamp", &clamp);
function("round_near", &round_near);
function("b64_fromIntV", &Base64::fromIntV);
function("b64_fromIntN", &Base64::fromIntN);
function("b64_toInt", &Base64::toInt);
function("b64_toIntSigned", &Base64::toIntSigned);
function("perm", &__perm_wrap);
}
#endif
} // namespace utils

View file

@ -1,12 +1,11 @@
#pragma once
/**
* Clamp number between low and high values.
* Generate all permutations of a vector.
*
* @param num: value to clamp
* @param low
* @param high
* @param a: vector containing the elements to permute.
*
* @return clamped value
* @return a vector with all permutations of `a`.
*/
float clamp(float num, float low, float high);
template<typename T>
std::vector<std::vector<T>> perm(std::vector<T> a);

View file

@ -3,22 +3,16 @@ const url_base = getUrl.protocol + "//" + getUrl.host + "/" + getUrl.pathname.sp
const _module_utils = create_utils();
const clamp = _module_utils.clamp;
// huge regex :doom:
// replace with navigator.userAgentData.mobile once it has wider support
const isMobile = function() {
let check = false;
(function(a){if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4))) check = true;})(navigator.userAgent||navigator.vendor||window.opera);
return check;
}(); // runs immediately, so mobileCheck is a boolean not a function
const zip2 = (a, b) => a.map((k, i) => [k, b[i]]);
const zip3 = (a, b, c) => a.map((k, i) => [k, b[i], c[i]]);
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
const round_near = _module_utils.round_near;
const log = _module_utils.log;
const Base64 = {
fromIntV: _module_utils.b64_fromIntV,
fromIntN: _module_utils.b64_fromIntN,
toInt: _module_utils.b64_toInt,
toIntSigned: _module_utils.b64_toIntSigned
}
// const perm = _module_utils.perm; way too garbage to use... we supply JS perm.
// Permutations in js reference (also cool algorithm):
// https://stackoverflow.com/a/41068709
function perm(a){
@ -43,12 +37,19 @@ function perm(a){
return r;
}
function round_near(value) {
let eps = 0.00000001;
if (Math.abs(value - Math.round(value)) < eps) {
return Math.round(value);
}
return value;
// huge regex :doom:
// replace with navigator.userAgentData.mobile once it has wider support
const isMobile = function() {
let check = false;
(function(a){if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4))) check = true;})(navigator.userAgent||navigator.vendor||window.opera);
return check;
}(); // runs immediately, so mobileCheck is a boolean not a function
const zip2 = (a, b) => a.map((k, i) => [k, b[i]]);
const zip3 = (a, b, c) => a.map((k, i) => [k, b[i], c[i]]);
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
function setText(id, text) {
@ -73,68 +74,6 @@ function getValue(id) {
return document.getElementById(id).value;
}
function log(b, n) {
return Math.log(n) / Math.log(b);
}
// Base 64 encoding tools
// https://stackoverflow.com/a/27696695
// Modified for fixed precision
// Base64.fromInt(-2147483648); // gives "200000"
// Base64.toInt("200000"); // gives -2147483648
Base64 = (function () {
var digitsStr =
// 0 8 16 24 32 40 48 56 63
// v v v v v v v v v
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+-";
var digits = digitsStr.split('');
var digitsMap = {};
for (var i = 0; i < digits.length; i++) {
digitsMap[digits[i]] = i;
}
return {
fromIntV: function(int32) {
var result = '';
while (true) {
result = digits[int32 & 0x3f] + result;
int32 >>>= 6;
if (int32 === 0)
break;
}
return result;
},
fromIntN: function(int32, n) {
var result = '';
for (let i = 0; i < n; ++i) {
result = digits[int32 & 0x3f] + result;
int32 >>= 6;
}
return result;
},
toInt: function(digitsStr) {
var result = 0;
var digits = digitsStr.split('');
for (var i = 0; i < digits.length; i++) {
result = (result << 6) + digitsMap[digits[i]];
}
return result;
},
toIntSigned: function(digitsStr) {
var result = 0;
var digits = digitsStr.split('');
if (digits[0] && (digitsMap[digits[0]] & 0x20)) {
result = -1;
}
for (var i = 0; i < digits.length; i++) {
result = (result << 6) + digitsMap[digits[i]];
}
return result;
}
};
})();
/** A class used to represent an arbitrary length bit vector. Very useful for encoding and decoding.
*
*/
@ -277,7 +216,7 @@ Base64 = (function () {
let b64_str = "";
let i = 0;
while (i < this.length) {
b64_str += Base64.fromIntV(this.slice(i, i + 6), 1);
b64_str += Base64.fromIntN(this.slice(i, i + 6), 1);
i += 6;
}

File diff suppressed because one or more lines are too long

42
js/c++/utils/base64.cpp Normal file
View file

@ -0,0 +1,42 @@
#include "base64.h"
namespace Base64 {
std::string fromIntV(unsigned int int32) {
std::string result;
while (true) {
result = digits[int32 & 0x3f] + result;
int32 >>= 6;
if (int32 == 0) { break; }
}
return result;
}
std::string fromIntN(unsigned int int32, int n) {
std::string result;
for (int i = 0; i < n; ++i) {
result = digits[int32 & 0x3f] + result;
int32 >>= 6;
}
return result;
}
unsigned int toInt(std::string digits) {
unsigned int result = 0;
for (size_t i = 0; i < digits.length(); ++i) {
result = (result << 6) + digitsMap.find(digits[i])->second;
}
return result;
}
int toIntSigned(std::string digits) {
int result = 0;
if (digits.length() > 0 && digitsMap.find(digits[0])->second & 0x20) {
result = -1;
}
for (size_t i = 0; i < digits.length(); ++i) {
result = (result << 6) + digitsMap.find(digits[i])->second;
}
return result;
}
}

32
js/c++/utils/base64.h Normal file
View file

@ -0,0 +1,32 @@
#pragma once
#include <string>
#include <map>
// Base 64 encoding tools
// https://stackoverflow.com/a/27696695
// Modified for fixed precision
// Base64.fromInt(-2147483648); // gives "200000"
// Base64.toInt("200000"); // gives -2147483648
namespace Base64 {
const std::string digits =
// 0 8 16 24 32 40 48 56 63
// v v v v v v v v v
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+-";
const std::map<char, size_t> digitsMap = []{
std::map<char, size_t> m;
for (size_t i = 0; i < digits.length(); ++i) {
m[digits[i]] = i;
}
return m;
}();
std::string fromIntV(unsigned int i);
std::string fromIntN(unsigned int i, int n);
unsigned int toInt(std::string digitsStr);
int toIntSigned(std::string digitsStr);
}

View file

@ -0,0 +1,40 @@
#include "math_utils.h"
#include <algorithm>
#include <cmath>
/**
* Clamp number between low and high values.
*
* @param num: value to clamp
* @param low
* @param high
*
* @return clamped value
*/
double clamp(double num, double low, double high) {
return std::min(std::max(num, low), high);
}
/**
* Round a value to an integer if it is veeeery close to one.
* (epsilon=0.00000001)
*
* @param value : value to round
*
* @return the same value, or rounded to an integer if it is close to one.
*/
double round_near(double value) {
const double eps = 0.00000001;
const double rounded = std::round(value);
if (std::abs(value - rounded) < eps) {
return rounded;
}
return value;
}
/**
* Compute log_b(n).
*/
double log(double b, double n) {
return std::log(n) / std::log(b);
}

28
js/c++/utils/math_utils.h Normal file
View file

@ -0,0 +1,28 @@
#pragma once
/**
* Clamp number between low and high values.
*
* @param num: value to clamp
* @param low
* @param high
*
* @return clamped value
*/
double clamp(double num, double low, double high);
/**
* Round a value to an integer if it is veeeery close to one.
* (epsilon=0.00000001)
*
* @param value : value to round
*
* @return the same value, or rounded to an integer if it is close to one.
*/
double round_near(double value);
/**
* Compute log_b(n).
*/
double log(double b, double n);