Skip to content

Instantly share code, notes, and snippets.

@robertleeplummerjr
Created March 20, 2020 12:50
Show Gist options
  • Select an option

  • Save robertleeplummerjr/abb8749ad0c0624e77a6989798981f48 to your computer and use it in GitHub Desktop.

Select an option

Save robertleeplummerjr/abb8749ad0c0624e77a6989798981f48 to your computer and use it in GitHub Desktop.

Revisions

  1. robertleeplummerjr created this gist Mar 20, 2020.
    49 changes: 49 additions & 0 deletions doodle-clz32-gpu.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,49 @@
    const { GPU } = require('./src');
    const gpu = new GPU();
    // language=GLSL
    const clz32 = `float clz32(float x) {
    int _x = int(x);
    _x -= bitwiseAnd(bitwiseSignedRightShift(_x, 1), ${0x55555555});
    _x = bitwiseAnd(bitwiseSignedRightShift(_x, 2), ${0x33333333}) + bitwiseAnd(_x, ${0x33333333});
    _x = bitwiseAnd((bitwiseSignedRightShift(_x, 4) + _x), ${0x0f0f0f0f});
    _x += bitwiseSignedRightShift(_x, 8);
    _x += bitwiseSignedRightShift(_x, 16);
    return float(bitwiseAnd(_x, ${0x0000003f}));
    }
    `;
    function clz32JS() {
    const int numIntBits = sizeof(int) * 8; //compile time constant
    //do the smearing
    x |= x >> 1;
    x |= x >> 2;
    x |= x >> 4;
    x |= x >> 8;
    x |= x >> 16;
    //count the ones
    x -= x >> 1 & 0x55555555;
    x = (x >> 2 & 0x33333333) + (x & 0x33333333);
    x = (x >> 4) + x & 0x0f0f0f0f;
    x += x >> 8;
    x += x >> 16;
    return numIntBits - (x & 0x0000003f); //subtract # of 1s from 32
    }
    gpu.addNativeFunction('clz32', clz32);
    const kernel = gpu.createKernel(function(value) {
    return clz32(value);
    }, {
    output: [1],
    pipeline: true,
    immutable: true,
    // debug: true,
    });

    console.log(Math.clz32(1.5));
    console.log(Math.clz32(2));
    const result = kernel(2);
    const clone1 = result.clone();
    const clone2 = clone1.clone();
    result.delete();
    clone1.clear();
    console.log(clone2.toArray());

    // Not working and no current hope