From a5947d19ed1e41792729b684bed46eab17651da1 Mon Sep 17 00:00:00 2001 From: Ilja Safronovs <96627800+ilyaeis@users.noreply.github.com> Date: Sat, 31 Oct 2026 12:17:13 +0200 Subject: [PATCH] Add a WebAssembly build of the algorithms The sort and shuffle code now also builds with Emscripten. AnotherFunc.hpp leaves out the SFML parts when __EMSCRIPTEN__ or SORTVIS_NO_SFML is defined. The native build does not change. web/shim.cpp replaces Main.cpp and the menu. Its drawing() records the steps into a log, like record mode. It has the glibc rand(), so a seed gives the same shuffle as the Linux program. build_web.sh builds web/dist/sortvis.js and sortvis.wasm. The CI has a new web job, and releases attach the two files. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_012G3kWcaMBo7MSwGBgwXaju --- .github/workflows/build.yml | 26 +++++++- .gitignore | 1 + Code/AnotherFunc.hpp | 11 ++++ README.md | 21 +++++++ build_web.sh | 14 +++++ web/shim.cpp | 121 ++++++++++++++++++++++++++++++++++++ 6 files changed, 192 insertions(+), 2 deletions(-) create mode 100755 build_web.sh create mode 100644 web/shim.cpp diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index f67e05a..8ee0310 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -51,9 +51,28 @@ jobs: name: sort_visualization-${{ matrix.name }} path: sort_visualization-${{ matrix.name }}.zip + web: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - uses: mymindstorm/setup-emsdk@v14 + with: + version: 6.0.13 + + - name: Build + run: ./build_web.sh + + - uses: actions/upload-artifact@v4 + with: + name: sortvis-web + path: | + web/dist/sortvis.js + web/dist/sortvis.wasm + release: if: startsWith(github.ref, 'refs/tags/v') - needs: build + needs: [build, web] runs-on: ubuntu-latest permissions: contents: write @@ -64,5 +83,8 @@ jobs: merge-multiple: true - uses: softprops/action-gh-release@v2 with: - files: dist/*.zip + files: | + dist/*.zip + dist/sortvis.js + dist/sortvis.wasm generate_release_notes: true diff --git a/.gitignore b/.gitignore index baebd93..81fa363 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,4 @@ Release/ .vs/ *.exe *.dll +web/dist/ diff --git a/Code/AnotherFunc.hpp b/Code/AnotherFunc.hpp index 6caea30..80a7198 100644 --- a/Code/AnotherFunc.hpp +++ b/Code/AnotherFunc.hpp @@ -1,11 +1,21 @@ #pragma once +#if !defined(__EMSCRIPTEN__) && !defined(SORTVIS_NO_SFML) #include +#else +// Web build (web/shim.cpp) and native tests: no SFML. +// Include only what the sort and shuffle code needs. +#include +#include +#include +#include +#endif #include #include void drawing(std::vector* array, int i, int first_column, int second_column); +#if !defined(__EMSCRIPTEN__) && !defined(SORTVIS_NO_SFML) sf::RectangleShape get_rectangle(int x, int y, int width, int height, sf::Color color); sf::ConvexShape get_convex_shape(std::vector cords, sf::Color color, sf::Color outline_color, int outline_size); sf::Vertex* get_line(float x1, float y1, float x2, float y2, sf::Color color); @@ -16,6 +26,7 @@ sf::Text get_text(std::string text_line, int size, int x, int y, int screen_widt sf::Font get_font(); sf::Color HSL_to_RGB(float h, float s, float l); +#endif int find_index_of_max(std::vector array); int index_of_num_next_after(int num, std::vector array); diff --git a/README.md b/README.md index 41b3aea..3d77175 100644 --- a/README.md +++ b/README.md @@ -99,6 +99,26 @@ ffmpeg -framerate 15 -i frames/f%06d.png \ clip.gif ``` +## Web build + +The sorting and shuffle algorithms also build to WebAssembly. `Code/SortAlgorithms.cpp` and `Code/ShuffleAlgorithms.cpp` compile unchanged. Without SFML, `Code/AnotherFunc.hpp` leaves out the SFML parts (when `__EMSCRIPTEN__` or `SORTVIS_NO_SFML` is defined). + +`web/shim.cpp` takes the place of `Main.cpp` and the menu: + +- Its `drawing()` does not draw. It records the steps, like record mode: a dry run counts the steps, then the real run saves every n-th step. +- It has the same `rand()` as glibc, so a seed gives the same shuffle as the Linux program. +- It fills the array like the menu: 500 values, ascending, descending or random. + +The log is a list of 32-bit integers: `[total steps, stride, frame count]`, then for each frame `first, second, k` and `k` pairs `(index, value)`: the cells that changed since the frame before. The last frame has `first = second = -1` and shows the sorted array. + +To build, install [emsdk](https://emscripten.org/docs/getting_started/downloads.html), then: + +```sh +./build_web.sh # writes web/dist/sortvis.js and web/dist/sortvis.wasm +``` + +The [CI](.github/workflows/build.yml) builds it too (artifact `sortvis-web`). The page at https://ilyaeis.github.io/apps/sorting/ uses it. The drawing there is a JavaScript port of `ArrayDrawer.cpp`. + ## Algorithms Each strip shows, from left to right: the shuffled array, the sort at about 25 %, 50 % and 75 % of its steps, and the sorted array. Columns layout, theme 0, seed 1. @@ -204,6 +224,7 @@ Sorts the first 2/3, the last 2/3, then the first 2/3 again. It is very slow. - C++17 - SFML 2.6.2 (downloaded by CMake, linked static) - CMake +- Emscripten (web build only) ## Status diff --git a/build_web.sh b/build_web.sh new file mode 100755 index 0000000..234f1b2 --- /dev/null +++ b/build_web.sh @@ -0,0 +1,14 @@ +#!/bin/sh +# Builds the sorting algorithms to WebAssembly (see "Web build" in README.md). +# Needs em++ from emsdk on the PATH. Output: web/dist/sortvis.js and web/dist/sortvis.wasm. +set -e +cd "$(dirname "$0")" +mkdir -p web/dist +em++ -Oz -std=c++17 -fno-exceptions -fno-rtti \ + web/shim.cpp Code/SortAlgorithms.cpp Code/ShuffleAlgorithms.cpp \ + -sMODULARIZE -sEXPORT_ES6 -sEXPORT_NAME=createSortVis \ + -sENVIRONMENT=web,worker -sALLOW_MEMORY_GROWTH -sFILESYSTEM=0 -sSTACK_SIZE=1MB \ + -sEXPORTED_FUNCTIONS=_sv_srand,_sv_rand,_sv_fill,_sv_gen_shuffle,_sv_shuffle,_sv_sort,_sv_log,_sv_array,_sv_length,_malloc,_free \ + -sEXPORTED_RUNTIME_METHODS=ccall,cwrap,HEAP32 \ + -o web/dist/sortvis.js +ls -l web/dist diff --git a/web/shim.cpp b/web/shim.cpp new file mode 100644 index 0000000..45fd354 --- /dev/null +++ b/web/shim.cpp @@ -0,0 +1,121 @@ +// Web build glue. It replaces Main.cpp, Menu.cpp and AnotherFunc.cpp (they need SFML). +// The algorithms in SortAlgorithms.cpp and ShuffleAlgorithms.cpp compile unchanged. +// drawing() records the steps into a log that JavaScript reads. +#include "../Code/SortAlgorithms.hpp" +#include "../Code/ShuffleAlgorithms.hpp" +#include +#ifdef __EMSCRIPTEN__ +#include +#else +#define EMSCRIPTEN_KEEPALIVE +#endif + +// ---- rand() as in glibc (TYPE_3), so a seed gives the same shuffle as the Linux build. +struct Rng { uint32_t r[34]; int pos; }; +static Rng rng; +extern "C" int rand() { + int p = rng.pos; // slot of r[i] + rng.pos = (p + 1) % 34; + rng.r[p] = rng.r[(p + 3) % 34] + rng.r[(p + 31) % 34]; // r[i-31] + r[i-3] + return int(rng.r[p] >> 1); +} +extern "C" void srand(unsigned seed) { + int32_t s = int32_t(seed ? seed : 1); + rng.r[0] = uint32_t(s); + for (int i = 1; i < 31; i++) { + int64_t v = (16807LL * int32_t(rng.r[i - 1])) % 2147483647; + rng.r[i] = uint32_t(int32_t(v < 0 ? v + 2147483647 : v)); + } + for (int i = 31; i < 34; i++) rng.r[i] = rng.r[i - 31]; + rng.pos = 0; // r[34] goes to slot 0 + for (int i = 0; i < 310; i++) rand(); // glibc drops these +} + +// ---- helper from AnotherFunc.cpp that radix sort needs +int find_index_of_max(std::vector array) { + int remember = 0; + for (int i = 0; i < (int)array.size(); i++) if (array[i] > array[remember]) remember = i; + return remember; +} + +// ---- recording +static std::vector arr, prev, logv; // the array, the last recorded state, the log +static long steps = 0, stride = 1; +static bool counting = false; +static int frames = 0; + +// Log one frame: the two indexes, then the cells that changed since the last frame. +static void frame(const std::vector& a, int first, int second) { + logv.push_back(first); + logv.push_back(second); + size_t kpos = logv.size(); + logv.push_back(0); + for (int i = 0; i < (int)a.size(); i++) { + if (a[i] == prev[i]) continue; + logv.push_back(i); + logv.push_back(a[i]); + prev[i] = a[i]; + logv[kpos]++; + } + frames++; +} + +// Called by the algorithms once per step, before the swap or write of that step. +void drawing(std::vector* array, int, int first, int second) { + if (!counting && steps % stride == 0) frame(*array, first, second); + steps++; +} + +// Like plan_frames() in Main.cpp: a dry run on a copy counts the steps, +// then the real run records every stride-th step. Returns the log length. +template static int record(F run, int max_frames) { + Rng saved = rng; + std::vector copy = arr; + counting = true; steps = 0; + run(©); + long total = steps; + rng = saved; // real run gets the same numbers + long m = max_frames > 0 ? max_frames : 1; + stride = total > m ? (total + m - 1) / m : 1; + counting = false; steps = 0; frames = 0; + prev = arr; + logv.assign({ int(total), int(stride), 0 }); + run(&arr); + frame(arr, -1, -1); // last frame: the final array + logv[2] = frames; + return (int)logv.size(); +} + +extern "C" { +EMSCRIPTEN_KEEPALIVE void sv_srand(unsigned seed) { srand(seed); } +EMSCRIPTEN_KEEPALIVE int sv_rand() { return rand(); } + +// 0 ascending, 1 descending, 2 random. Same values as Menu::array_filler (500 items, size 2). +EMSCRIPTEN_KEEPALIVE int sv_fill(int order) { + const int n = 500, size = 2, max_num = 1000; + arr.clear(); + for (int i = 0; i < n; i++) arr.push_back(order == 2 ? rand() % max_num + 1 : (i + 1) * size); + if (order == 1) for (int i = 0; i < n / 2; i++) swap(&arr[i], &arr[n - i - 1]); + return n; +} + +EMSCRIPTEN_KEEPALIVE int sv_gen_shuffle(int start) { return generate_shuffle(start != 0).type_of_shuffle; } + +EMSCRIPTEN_KEEPALIVE int sv_shuffle(int type, int max_frames) { + if (type < 0 || type > 2) return -1; // the original exits here + Shuffle s{}; + s.type_of_shuffle = type; + return record([&](std::vector* a) { start_shuffle(a, s); }, max_frames); +} + +EMSCRIPTEN_KEEPALIVE int sv_sort(const char* name, int max_frames) { + std::vector names = get_sorts_table_origin(); + std::string n = name; + if (std::find(names.begin(), names.end(), n) == names.end()) return -1; // the original exits here + return record([&](std::vector* a) { start_right_sort(a, n); }, max_frames); +} + +EMSCRIPTEN_KEEPALIVE int* sv_log() { return logv.data(); } +EMSCRIPTEN_KEEPALIVE int* sv_array() { return arr.data(); } +EMSCRIPTEN_KEEPALIVE int sv_length() { return (int)arr.size(); } +}