nandi/vflutter_ffipublic Fork 0
main
Commits
Clone
git clone https://git.rickub.com/nandi/vflutter_ffi.git
git clone ssh://git@rickub.com/nandi/vflutter_ffi.git

Host key fingerprint (ed25519): SHA256:iycHnxEyq0Q7uyVpB7JlznP0G7JrTPXLYRcAU5CSLhc — verify it before your first connect.

nimflutter_pool.js · 74 lines · 2.3 KBJavaScript Blame HistoryRaw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// A worker pool for band rendering, exposed to Dart as one promise-returning
// function.
//
// The pool lives here rather than in Dart because dart:js_interop has no
// ergonomic Worker binding, and because the interesting part — a work queue
// feeding N workers — is the same code in either language.
(function () {
  const workers = [];
  const idle = [];
  let nextId = 1;
  let poolSize = 0;

  // More bands than cores is deliberate: bands cost wildly different amounts
  // (interior rows run the full iteration cap), so over-decomposing keeps a
  // free worker busy instead of waiting on the slowest band. Same finding as
  // `just sweep` on native.
  const maxWorkers = Math.max(1, (self.navigator && self.navigator.hardwareConcurrency) || 4);

  function grow(n) {
    const want = Math.min(n, maxWorkers);
    while (workers.length < want) {
      const w = new Worker('nimflutter_worker.js');
      w.pending = new Map();
      w.onmessage = (e) => {
        const resolve = w.pending.get(e.data.id);
        if (!resolve) return;
        w.pending.delete(e.data.id);
        resolve(e.data);
      };
      workers.push(w);
      idle.push(w);
    }
    poolSize = workers.length;
  }

  function run(worker, job) {
    return new Promise((resolve) => {
      worker.pending.set(job.id, resolve);
      worker.postMessage(job);
    });
  }

  self.nimflutterPoolSize = () => poolSize;

  self.nimflutterRenderParallel = function (w, h, cx, cy, scale, iter, tiles) {
    const count = Math.max(1, Math.min(tiles, h));
    grow(count);

    const rowsPer = Math.ceil(h / count);
    const queue = [];
    for (let t = 0; t < count; t++) {
      const y0 = t * rowsPer;
      const y1 = Math.min((t + 1) * rowsPer, h);
      if (y0 >= y1) break;
      queue.push({ id: nextId++, w, h, cx, cy, scale, iter, y0, y1 });
    }

    const out = new Uint8Array(w * h * 4);

    // Hand each worker the next band as it frees up, rather than dealing the
    // whole deck up front — that is what turns uneven band costs into a
    // balanced schedule.
    const pump = (worker) => {
      const job = queue.shift();
      if (!job) return Promise.resolve();
      return run(worker, job).then((res) => {
        out.set(res.band, res.y0 * w * 4);
        return pump(worker);
      });
    };

    return Promise.all(workers.map(pump)).then(() => out);
  };
})();