Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 24 additions & 2 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@ Release/
.vs/
*.exe
*.dll
web/dist/
11 changes: 11 additions & 0 deletions Code/AnotherFunc.hpp
Original file line number Diff line number Diff line change
@@ -1,11 +1,21 @@
#pragma once

#if !defined(__EMSCRIPTEN__) && !defined(SORTVIS_NO_SFML)
#include <SFML/Graphics.hpp>
#else
// Web build (web/shim.cpp) and native tests: no SFML.
// Include only what the sort and shuffle code needs.
#include <string>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#endif
#include <vector>
#include <math.h>

void drawing(std::vector<int>* 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<float> 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);
Expand All @@ -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<int> array);
int index_of_num_next_after(int num, std::vector<int> array);
Expand Down
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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

Expand Down
14 changes: 14 additions & 0 deletions build_web.sh
Original file line number Diff line number Diff line change
@@ -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
121 changes: 121 additions & 0 deletions web/shim.cpp
Original file line number Diff line number Diff line change
@@ -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 <cstdint>
#ifdef __EMSCRIPTEN__
#include <emscripten.h>
#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<int> 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<int> 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<int>& 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<int>* 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 <typename F> static int record(F run, int max_frames) {
Rng saved = rng;
std::vector<int> copy = arr;
counting = true; steps = 0;
run(&copy);
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<int>* a) { start_shuffle(a, s); }, max_frames);
}

EMSCRIPTEN_KEEPALIVE int sv_sort(const char* name, int max_frames) {
std::vector<std::string> 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<int>* 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(); }
}
Loading