This commit is contained in:
Aitor
2023-03-17 13:29:57 +01:00
parent 7d8e985877
commit 79b06aa092
20 changed files with 52 additions and 720 deletions

View File

@@ -389,6 +389,7 @@
([vector]
(move (empty) vector)))
;; This function is never used
(defn move-parent-modifiers
([x y]
(move-parent (empty) (gpt/point x y)))
@@ -403,6 +404,7 @@
([vector origin transform transform-inverse]
(resize (empty) vector origin transform transform-inverse)))
;; This function is never used
(defn resize-parent-modifiers
([vector origin]
(resize-parent (empty) vector origin))

View File

@@ -1,3 +1,10 @@
all:
mkdir -p build
em++ -std=c++20 -O3 -sINCOMING_MODULE_JS_API=['print'] -sENVIRONMENT=web,node,worker -sFILESYSTEM=0 src/main.cpp -o build/main.js
clang \
-target wasm32 \
-nostdlib \
-Wl,--no-entry \
-Wl,--export-all \
-o build/resize.wasm \
src/resize.c

View File

@@ -1,72 +0,0 @@
# Notas
## TO DO
- [ ] Mover todo esto a algún otro sitio mejor que no sea `resources/public`.
- [ ] Implementar tanto `clang-format` como `clang-tidy` para formatear el código.
- [ ] Implementar algún sistema de testing (Catch2, Google Test, CppUnit, etc).
- [ ] Implementar CMake para construir el proyecto.
Para compilar el código en C++ se puede usar la siguiente línea:
```sh
g++ -std=c++20 src/main.cpp -o main
```
## Emscripten
### Instalación
1. Clonar repositorio:
```sh
git clone https://github.com/emscripten-core/emsdk.git
cd emsdk
```
2. Actualizar e instalar dependencias:
```sh
git pull
./emsdk install latest
./emsdk activate latest
source ./emsdk_env.sh
```
3. Probar:
:bulb: Ahora deberíamos tener disponibles herramientas como `emcc` (equivalente a
`gcc` o `clang`), `em++` (equivalente a `g++` o `clang++`), `emmake`
(equivalente a `make`) o `emcmake` (equivalente a `cmake`).
Puedes compilar el proyecto con:
```sh
emmake make
```
## WebAssembly
### Memoria
La memoria de WebAssembly se crea cuando se instancia el módulo de WebAssembly, aunque esta memoria puede crecer. Si no se pasa un `WebAssembly.Memory` al módulo en la instanciación, crea una memoria por defecto con el número de páginas que indique el módulo.
:bulb: Para averiguar cuál es este valor por defecto podemos usar `wasm-objdump -x <module.wasm> | grep 'pages:'`.
La memoria de WebAssembly se reserva usando páginas (una página equivale a 64KB).
El máximo de memoria que puede reservar un módulo de WebAssembly ahora mismo son 4GB (65536 páginas).
:bulb: Ahora mismo existen dos _proposals_ para ampliar estos límites: [Memory64](https://github.com/WebAssembly/memory64) y [Multi-Memory](https://github.com/WebAssembly/multi-memory/blob/master/proposals/multi-memory/Overview.md)
## Documentos
- [C++ Core Guidelines](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#S-introduction)
## Recursos
- [Compiling C to WebAssembly without Emscripten](https://surma.dev/things/c-to-webassembly/)
- [Emscripten: C/C++ compiler toolchain](https://emscripten.org/)
- [Emscripten: settings.js](https://github.com/emscripten-core/emscripten/blob/main/src/settings.js)
- [WABT: WebAssembly Binary Toolkit](https://github.com/WebAssembly/wabt)
- [Binaryen: Compiler Toolchain](https://github.com/WebAssembly/binaryen)

File diff suppressed because one or more lines are too long

View File

@@ -1,3 +0,0 @@
all:
em++ --no-entry -sEXPORT_KEEPALIVE=1 -sENVIRONMENT=web -sFILESYSTEM=0 vector.cpp -o vector.wasm

View File

@@ -1,9 +0,0 @@
import Vector from './vector.mjs'
console.log(Vector)
async function main()
{
const vector = await Vector()
}
main()

View File

@@ -1,25 +0,0 @@
#include <emscripten.h>
#include <iostream>
#include <vector>
#include <memory>
enum ShapeType
{
FRAME = 0,
RECT,
ELLIPSE,
};
struct Shape {
ShapeType type;
Shape() : type(FRAME) {};
};
static std::shared_ptr<Shape> root;
void EMSCRIPTEN_KEEPALIVE resize(const std::shared_ptr<Shape> ptr)
{
std::cout << "resize" << std::endl;
}

View File

@@ -1,54 +0,0 @@
#pragma once
#include "Vector2.h"
template <typename T>
struct Box2
{
Vector2<T> position;
Vector2<T> size;
Box2(T x, T y, T width, T height) {
position.set(x, y);
size.set(width, height);
}
Box2(const Box2<T>& box) : position(box.position), size(box.size) {}
Box2(const Vector2<T>& position, const Vector2<T>& size) : position(position), size(size) {}
auto left() const
{
return position.x;
}
auto right() const
{
return position.x + size.x;
}
auto top() const
{
return position.y;
}
auto bottom() const
{
return position.y + size.y;
}
bool contains(const Vector2<T>& point) const {
return point.x > position.x
&& point.x < position.x + size.x
&& point.y > position.y
&& point.y < position.y + size.y;
}
bool intersects(const Box2<T> &other) const {
if (left() > other.right() || right() < other.left())
return false;
if (top() > other.bottom() || bottom() < other.top())
return false;
return true;
}
};

View File

@@ -1,96 +0,0 @@
#pragma once
template <typename T>
struct Color {
T r, g, b, a;
Color<T>& set(T new_r, T new_g, T new_b, T new_a)
{
r = new_r;
g = new_g;
b = new_b;
a = new_a;
return *this;
}
Color<T>& set(T new_r, T new_g, T new_b)
{
r = new_r;
g = new_g;
b = new_b;
return *this;
}
Color<T> operator+(const Color<T> other)
{
return {
r + other.r,
g + other.g,
b + other.b
};
}
Color<T> operator-(const Color<T> other)
{
return {
r - other.r,
g - other.g,
b - other.b
};
}
Color<T> operator*(const Color<T> other)
{
return {
r * other.r,
g * other.g,
b * other.b
};
}
Color<T> operator/(const Color<T> other)
{
return {
r / other.r,
g / other.g,
b / other.b
};
}
Color<T> operator+(const T scalar)
{
return {
r + scalar,
g + scalar,
b + scalar
};
}
Color<T> operator-(const T scalar)
{
return {
r - scalar,
g - scalar,
b - scalar
};
}
Color<T> operator*(const T scalar)
{
return {
r * scalar,
g * scalar,
b * scalar
};
}
Color<T> operator/(const T scalar)
{
return {
r / scalar,
g / scalar,
b / scalar
};
}
}

View File

@@ -1,20 +0,0 @@
#pragma once
namespace Interpolation {
template <typename T>
T linear(const T x, const T a, const T b) {
return (1 - x) * a + x * b;
}
template <typename T>
T quadratic(const T x, const T a, const T b, const T c) {
return linear(x, linear(x, a, b), linear(x, b, c));
}
template <typename T>
T cubic(const T x, const T a, const T b, const T c, const T d) {
return linear(x, quadratic(x, a, b, c), quadratic(x, b, c, d));
}
}

View File

@@ -1,122 +0,0 @@
#pragma once
#include <cmath>
#include <iostream>
template <typename T>
struct Matrix2D {
// a c tx
// b d ty
T a, b, c, d, tx, ty;
Matrix2D() : a(1), b(0), c(0), d(1), tx(0), ty(0) {}
Matrix2D(T a, T b, T c, T d, T tx, T ty) : a(a), b(b), c(c), d(d), tx(tx), ty(ty) {}
Matrix2D(const Matrix2D<T>& other) : a(other.a), b(other.b), c(other.c), d(other.d), tx(other.tx), ty(other.ty) {}
auto determinant() const {
return a * d - b * c;
}
Matrix2D<T>& identity()
{
a = 1;
b = 0;
c = 0;
d = 1;
tx = 0;
ty = 0;
return *this;
}
Matrix2D<T>& translate(T x, T y)
{
tx += x;
ty += y;
return *this;
}
Matrix2D<T>& scale(T x, T y)
{
a *= x;
b *= y;
c *= x;
d *= y;
return *this;
}
Matrix2D<T>& rotate(auto angle)
{
auto cos = std::cos(angle);
auto sin = std::sin(angle);
auto new_a = a * cos + c * sin;
auto new_b = b * cos + d * sin;
auto new_c = c * cos - a * sin;
auto new_d = d * cos - b * sin;
a = new_a;
b = new_b;
c = new_c;
d = new_d;
return *this;
}
Matrix2D<T> invert()
{
auto det = determinant();
if (det == 0)
{
return *this;
}
auto inv_det = 1.0 / det;
return {
d * inv_det,
-b * inv_det,
-c * inv_det,
a * inv_det,
(c * ty - d * tx) * inv_det,
(b * tx - a * ty) * inv_det
};
}
Matrix2D<T> operator*(const Matrix2D<T>& other)
{
// M N
// a c x a c x
// b d y x b d y = T
// 0 0 1 0 0 1
return {
a * other.a + b * other.c,
a * other.b + b * other.d,
c * other.a + d * other.c,
c * other.b + d * other.d,
tx * other.a + ty * other.c + other.tx,
tx * other.b + ty * other.d + other.ty
};
}
static Matrix2D<T> create_translation(const T x, const T y)
{
return { 1, 0, 0, 1, x, y };
}
static Matrix2D<T> create_scale(const T x, const T y)
{
return { x, 0, 0, y, 0, 0 };
}
static Matrix2D<T> create_rotation(auto angle)
{
auto c = std::cos(angle);
auto s = std::sin(angle);
return { c, s, -s, c, 0, 0 };
}
};
template <typename T>
std::ostream &operator<<(std::ostream &os, const Matrix2D<T> &matrix)
{
os << "Matrix2D(" << matrix.a << ", " << matrix.b << ", " << matrix.c << ", " << matrix.d << ", " << matrix.tx << ", " << matrix.ty << ")";
return os;
}

View File

@@ -1,65 +0,0 @@
#pragma once
#include <vector>
#include <memory>
#include "Vector2.h"
#include "Matrix2D.h"
#include "Color.h"
enum ShapeType
{
FRAME = 0,
RECT,
ELLIPSE,
PATH,
TEXT
};
enum PaintType
{
COLOR = 0,
IMAGE,
PATTERN,
LINEAR_GRADIENT,
RADIAL_GRADIENT
};
struct MatrixTransform
{
Matrix2D<float> concatenatedMatrix;
Matrix2D<float> matrix;
};
struct Transform
{
Vector2<float> position;
Vector2<float> scale;
float rotation;
};
struct Paint
{
PaintType type;
};
struct Stroke
{
float width;
Paint paint;
};
struct Fill
{
Paint paint;
};
struct Shape
{
ShapeType type;
Transform transform;
std::shared_ptr<Shape> parent;
std::vector<std::shared_ptr<Shape>> children;
// std::vector<Stroke> strokes;
// std::vector<Fill> fills;
};

View File

@@ -1,198 +0,0 @@
#pragma once
#include <cmath>
#include <iostream>
#include "Interpolation.h"
#include "Matrix2D.h"
template <typename T>
struct Vector2 {
T x, y;
Vector2() : x(0), y(0) {}
Vector2(T x, T y) : x(x), y(y) {}
Vector2(const Vector2<T>& other) : x(other.x), y(other.y) {}
auto dot(const Vector2<T> &other) const
{
return x * other.x + y * other.y;
}
auto cross(const Vector2<T> &other) const
{
return x * other.y - y * other.x;
}
auto direction() const
{
return std::atan2(y, x);
}
auto length() const
{
return std::hypot(x, y);
}
auto lengthSquared() const
{
return x * x + y * y;
}
Vector2<T>& normalize()
{
auto l = length();
return set(x / l, x / l);
}
Vector2<T>& perpLeft()
{
return set(y, -x);
}
Vector2<T>& perpRight()
{
return set(-y, x);
}
Vector2<T>& rotate(auto rotation)
{
auto c = std::cos(rotation);
auto s = std::sin(rotation);
return set(
c * x - s * y,
s * x + c * y
);
}
Vector2<T>& scale(auto s)
{
return set(
x * s,
y * s
);
}
Vector2<T>& set(T newX, T newY)
{
x = newX;
y = newY;
return *this;
}
Vector2<T>& copy(const Vector2<T>& other)
{
return set(other.x, other.y);
}
Vector2<T>& linear(auto p, Vector2<T>& a, Vector2<T>& b)
{
return set(
Interpolation::linear(p, a.x, b.x),
Interpolation::linear(p, a.y, b.y)
);
}
Vector2<T>& quadratic(auto p, Vector2<T>& a, Vector2<T>& b, Vector2<T>& c)
{
return set(
Interpolation::quadratic(p, a.x, b.x, c.x),
Interpolation::quadratic(p, a.y, b.y, c.y)
);
}
Vector2<T>& cubic(auto p, Vector2<T>& a, Vector2<T>& b, Vector2<T>& c, Vector2<T>& d)
{
return set(
Interpolation::cubic(p, a.x, b.x, c.x, d.x),
Interpolation::cubic(p, a.y, b.y, c.y, d.y)
);
}
Vector2<T> operator*(const Matrix2D<T> m)
{
return {
x * m.a + y * m.c + m.tx,
x * m.b + y * m.d + m.ty
};
}
Vector2<T> operator+(const Vector2<T> other)
{
return {
x + other.x,
y + other.y
};
}
Vector2<T> operator-(const Vector2<T> other)
{
return {
x - other.x,
y - other.y
};
}
Vector2<T> operator*(const Vector2<T> other)
{
return {
x * other.x,
y * other.y
};
}
Vector2<T> operator/(const Vector2<T> other)
{
return {
x / other.x,
y / other.y
};
}
Vector2<T> operator+(T scalar)
{
return {
x + scalar,
y + scalar
};
}
Vector2<T> operator-(T scalar)
{
return {
x - scalar,
y - scalar
};
}
Vector2<T> operator*(T scalar)
{
return {
x * scalar,
y * scalar
};
}
Vector2<T> operator/(T scalar)
{
return {
x / scalar,
y / scalar
};
}
Vector2<T> operator-() const
{
return {
-x,
-y
};
}
};
template <typename T>
std::ostream& operator<<(std::ostream &os, const Vector2<T>& vector)
{
os << "Vector2(" << vector.x << ", " << vector.y << ")";
return os;
}

View File

@@ -1,34 +0,0 @@
#include <cmath>
#include <iostream>
#include "Interpolation.h"
#include "Matrix2D.h"
#include "Vector2.h"
#include "Box2.h"
void resize()
{
}
int main(int argc, char** argv)
{
Vector2<float> a(1, 0);
Vector2<float> b(0, 1);
Matrix2D<float> m;
std::cout << m << std::endl;
std::cout << m.rotate(M_PI / 2) << std::endl;
Vector2<float> a2 = a * m;
Vector2<float> b2 = b * m;
std::cout << a << ", " << a2 << std::endl;
std::cout << b << ", " << b2 << std::endl;
std::cout << "Hello, World!" << std::endl;
return 0;
}

View File

@@ -392,6 +392,7 @@
(reduce merge {}))
undo-id (js/Symbol)]
(js/console.log (clj->js object-modifiers) (clj->js text-modifiers) (clj->js objects))
(rx/concat
(if undo-transation?
(rx/of (dwu/start-undo-transaction undo-id))

View File

@@ -29,6 +29,7 @@
[app.main.snap :as snap]
[app.main.streams :as ms]
[app.util.dom :as dom]
[app.wasm :as wasm]
[beicon.core :as rx]
[cljs.spec.alpha :as s]
[potok.core :as ptk]))
@@ -175,6 +176,9 @@
set-fix-height?
(not (mth/close? (:y scalev) 1))
;; Creates the initial structure of modifiers
;; that will be later filled in the create-modif-tree
;; call
modifiers
(-> (ctm/empty)
(cond-> displacement
@@ -190,7 +194,10 @@
(cond-> scale-text
(ctm/scale-content (:x scalev))))
modif-tree (dwm/create-modif-tree ids modifiers)]
;; Fills modifiers using identifiers
modif-tree (dwm/create-modif-tree ids modifiers)]
(js/console.log (clj->js modif-tree))
(wasm/resize handler ids shape)
(rx/of (dwm/set-modifiers modif-tree))))
;; Unifies the instantaneous proportion lock modifier
@@ -209,7 +216,7 @@
ptk/WatchEvent
(watch [_ state stream]
(let [initial-position @ms/mouse-position
stoper (rx/filter ms/mouse-up? stream)
stopper (rx/filter ms/mouse-up? stream)
layout (:workspace-layout state)
page-id (:current-page-id state)
focus (:workspace-focus-selected state)
@@ -226,7 +233,7 @@
(->> (snap/closest-snap-point page-id resizing-shapes objects layout zoom focus point)
(rx/map #(conj current %)))))
(rx/mapcat (partial resize shape initial-position layout))
(rx/take-until stoper))
(rx/take-until stopper))
(rx/of (dwm/apply-modifiers)
(finish-transform))))))))

View File

@@ -370,6 +370,7 @@
(when (dom/left-mouse? event)
(dom/stop-propagation event)
(st/emit! (dw/start-resize current-position selected shape))))
;;(js/console.log event (dw/start-resize current-position selected shape))))
on-rotate
(fn [event]
@@ -410,6 +411,7 @@
(when (dom/left-mouse? event)
(dom/stop-propagation event)
(st/emit! (dw/start-resize current-position #{shape-id} shape))))
;;(js/console.log event (clj->js (dw/start-resize current-position #{shape-id} shape)))))
on-rotate
(fn [event]

View File

@@ -2,7 +2,7 @@
(:require
[promesa.core :as p]))
(defonce instance (atom nil))
(defonce assembly (atom nil))
(defn load-wasm
"Loads a WebAssembly module"
@@ -10,7 +10,7 @@
(->
(p/let [response (js/fetch uri)
array-buffer (.arrayBuffer response)
assembly (.instantiate js/WebAssembly array-buffer)]
assembly (.instantiate js/WebAssembly array-buffer (js-obj "env" (js-obj)))]
assembly)
(p/catch (fn [error] (prn "error: " error)))))
@@ -18,18 +18,30 @@
"Initializes WebAssembly module"
[]
(p/then
(load-wasm "wasm/add.wasm")
(fn [assembly]
(let [operations (js/Int32Array.
assembly.instance.exports.memory.buffer ;; buffer we want to use
assembly.instance.exports.operations.value ;; offset of pointer 'operations'
(* 2048 12))]
(aset operations 0 2)
(aset operations 1 2)
(.set operations #js [4 5 -1] 3)
(js/console.time "compute")
(assembly.instance.exports.compute)
(js/console.timeEnd "compute")
(js/console.log assembly)
)
(reset! instance assembly.instance))))
(load-wasm "wasm/build/resize.wasm")
(fn [asm]
(reset! assembly
(js-obj "instance" asm.instance
"module" asm.module
"exports" asm.instance.exports)))))
(defn get-handler-id
[handler]
(case handler
:top 0
:top-right 1
:right 2
:bottom-right 3
:bottom 4
:bottom-left 5
:left 6
:top-left 7))
(defn resize
[handler ids shape]
;; TODO: Tenemos que resolver los diferentes shapes
;; para subirlos al módulo de WebAssembly.
(when @assembly
(let [asm @assembly]
(js/console.log (clj->js ids) (clj->js shape))
(asm.exports.resize (get-handler-id handler) ids shape))))