jscad / OpenJSCAD.org

JSCAD is an open source set of modular, browser and command line tools for creating parametric 2D and 3D designs with JavaScript code. It provides a quick, precise and reproducible method for generating 3D models, and is especially useful for 3D printing applications.
https://openjscad.xyz/
MIT License
2.68k stars 516 forks source link

V3 tree shaking and gl-matrix #1163

Open hrgdavor opened 2 years ago

hrgdavor commented 2 years ago

I was building sth regl related for jscad and seen that regl-renderer uses some fork of gl-matrix, as probably an old way to reduce size of the bundle. Also jscad has copy of glmatrix functions....

nowdays when we have build tools that easily do tree shaking with ES imodules it would be a good idea to start using gl-matrix directly again in jscad V3. While testing how tree shaking performs also take steps that jscad remains easy to tree shake.

for example, gl-matrix has deployed esm and cjs variants for each version so this type of improvement does not have to impact old usage patterns.

naively importing gl-matrix and using just one function creates a 35KB bundle (not minified)

import {mat4} from 'gl-matrix';

export function testGl(a,b){
  return mat4.add(a,b)
}

but these two variants work nicely with esbuild and treeshaking produces only 600B of code (not minified)

import * as mat4 from 'gl-matrix/esm/mat4.js';

export function testGl(a,b){
  return mat4.add(a,b)
}

or

import {add} from 'gl-matrix/esm/mat4.js';

export function testGl(a,b){
  return add(a,b)
}

produces this:

(() => {
  // ../../node_modules/gl-matrix/esm/mat4.js
  function add(out, a, b) {
    out[0] = a[0] + b[0];
    out[1] = a[1] + b[1];
    out[2] = a[2] + b[2];
    out[3] = a[3] + b[3];
    out[4] = a[4] + b[4];
    out[5] = a[5] + b[5];
    out[6] = a[6] + b[6];
    out[7] = a[7] + b[7];
    out[8] = a[8] + b[8];
    out[9] = a[9] + b[9];
    out[10] = a[10] + b[10];
    out[11] = a[11] + b[11];
    out[12] = a[12] + b[12];
    out[13] = a[13] + b[13];
    out[14] = a[14] + b[14];
    out[15] = a[15] + b[15];
    return out;
  }

  // gltest.js
  function testGl(a, b) {
    return add(a, b);
  }
})();
z3dev commented 9 months ago

@hrgdavor what are you using in jscadui now?

it may be possible to switch some of the math to glmatrix as the libraries seem to be heading the same direction now.

hrgdavor commented 9 months ago

@z3dev yes, I am using gl-matrix in the above mentioned treeshaking friendly way .. for example here https://github.com/hrgdavor/jscadui/blob/main/packages/orbit/src/calcCamPos.js

... a bit of digression:

I also am doing this freaky thing for one specific combined operation I need... https://github.com/hrgdavor/jscadui/blob/main/packages/orbit/fromXZRotation.gen.js