<aside> 💡 Description: Sandbox Avatar material customiser. Custom 2D UI integration from dynamic 3D scene control.

</aside>

Geenee AR Vox Customizer.mp4

ColorPicker - handle color picker logic & UI

const events = {
  initializeColorInput : "initializeColorInput",
  onChangeColorInput : "onChangeColorInput"
}

const colorisStyles = document.createElement('link');
colorisStyles.href = 'https://cdn.jsdelivr.net/gh/mdbassit/Coloris@latest/dist/coloris.min.css';
colorisStyles.rel = 'stylesheet';
document.getElementsByTagName('head')[0].appendChild(colorisStyles);

//Using loadScript instead
// const colorisScript = document.createElement('script');
// colorisScript.setAttribute('src','https://cdn.jsdelivr.net/gh/mdbassit/Coloris@latest/dist/coloris.min.js');
// document.head.appendChild(colorisScript);

function loadScript( url, callback ) {
  var script = document.createElement( "script" )
  script.type = "text/javascript";
  if(script.readyState) {  // only required for IE <9
    script.onreadystatechange = function() {
      if ( script.readyState === "loaded" || script.readyState === "complete" ) {
        script.onreadystatechange = null;
        callback();
      }
    };
  } else {  //Others
    script.onload = function() {
      callback();
    };
  }

  script.src = url;
  document.getElementsByTagName( "head" )[0].appendChild( script );
}

const onScriptLoaded = () => {
    const globalWrapper = document.getElementById("geenee-ui-global--wrapper");

    Coloris({
      focusInput: false
    })
    //Instead of initializing UI using listeners
    // const buttons = {
    //     top: ["160px", "240px", "320px"],
    // };
    // const initializeUI = () => {
    //     for (let i = 0; i < buttons.top.length; i++) {
    //         initializeButtons(
    //             buttons.top[i]
    //         );
    //     }
    // }
    //initializeUI();

    const initializeColorInput = (e) => {
        const left = e.detail.left;
        const top = e.detail.top;
        const id = e.detail.id;
        const color = e.detail.color;
        //console.log("Initialize color input with values: " + JSON.stringify(e.detail));

        const divWrapper = document.createElement("div");
        divWrapper.style = buttonWrapperStyle;
        divWrapper.style.top = top;
        divWrapper.style.left = left;
        globalWrapper.appendChild(divWrapper);

        const colorInput = document.createElement("input");
        colorInput.type = "text";
        colorInput.setAttribute("data-coloris", "");
        colorInput.style = inputStyle;
        colorInput.setAttribute("materialId", id);
        colorInput.value = color;
        colorInput.style.backgroundColor = color;
        colorInput.setAttribute("readonly", "");
        colorInput.onfocus = () => { document.activeElement.blur(); };
        colorInput.onfocus = () => { colorInput.removeAttribute("readonly"), "" };
        colorInput.onblur = () => {colorInput.setAttribute("readonly", "")};
        divWrapper.appendChild(colorInput);

        colorInput.addEventListener('change', (e) => {
            colorInput.style.backgroundColor = e.target.value;
            const onChangeColorInput = new CustomEvent(events.onChangeColorInput, {
              detail: {
                id: colorInput.getAttribute("materialId"),
                color: e.target.value
              }
            });
            document.dispatchEvent(onChangeColorInput);
        });
    }
    document.addEventListener(events.initializeColorInput, initializeColorInput);
}

const buttonWrapperStyle =
  "position: absolute; z-index: 1; left: 15px; top: 80px; background-color: rgba(255, 255, 255, 0.15); -webkit-backdrop-filter: blur(15px); width: 45px; height: 45px; border-top-left-radius: 100%; border-top-right-radius: 100%; border-bottom-right-radius: 100%; border-bottom-left-radius: 100%; display: flex; -webkit-box-align: center; align-items: center; -webkit-box-pack: center; justify-content: center;";  

const inputStyle = "caret-color: transparent; width: 30px; height: 30px; color: transparent; border: transparent; border-radius: 30px";

const pathtoscript = "https://cdn.jsdelivr.net/gh/mdbassit/Coloris@latest/dist/coloris.min.js";
loadScript(pathtoscript, onScriptLoaded);

Vox Mesh Factory - handle mesh creation

const events = {
  initializeColorInput: "initializeColorInput",
  onChangeColorInput: "onChangeColorInput",
};

this.activeSceneModel.$parent.emitter.addListener("geenee-model-placed", () => {
  //console.dir(this.object3D.parent);
  //console.log("Name: " + this.object3D.children[0].children[0].name); // Our cube object

  //Disable gestures. Optional.
  this.activeSceneModel.setScene3DSettingsOption("defaultCanvasClick", false);
  this.activeSceneModel.setGestureOption("dragOn", false);

  const thisObject3D = this.object3D;
  const thisObjectGroup = this.object3D.children[0];
  const thisObjectMesh = this.object3D.children[0].children[0];
  thisObjectMesh.visible = false;

  document.addEventListener("onVoxModelLoaded", function (e) {
    //console.log(e.detail);
    const voxData = JSON.parse(e.detail);
    meshFactory(voxData);
  });

  async function meshFactory(voxData) {
    let meshGroup = new THREE.Group();
    const meshes = new Array();
    thisObjectGroup.add(meshGroup);
    const colors = voxData.rgba.values;

    //Create materials
    const materials = createMaterials(voxData, colors);

    //Create meshes
    for (let i = 0; i < voxData.xyzi.values.length; i++) {
      meshes.push(createMesh(voxData.xyzi.values[i], meshGroup, materials));
    }

    //Recenter meshGroup
    let bboxGroup = new THREE.Group();
    for (const mesh of meshes) bboxGroup.attach(mesh);
    let bboxInital = new THREE.Box3().setFromObject(bboxGroup);
    let bboxCenter = new THREE.Vector3();
    bboxInital.getCenter(bboxCenter);
    meshGroup.position.set(bboxCenter.x, bboxCenter.y, bboxCenter.z);

    //Attach meshes
    for await (const mesh of meshes) meshGroup.attach(mesh);

    //Set Rotation & Scale
    meshGroup.position.set(1, 0, 0); // 1 is a temporarly workaround. Probably position should be 100% precise based on this.Object3D center. TODO.
    meshGroup.scale.set(0.05, 0.05, 0.05);
    meshGroup.rotateX(degToRad(-90));
    meshGroup.rotateZ(degToRad(180));
    //console.log("meshGroup.position: " + JSON.stringify(meshGroup.position));
    //console.log("thisObjectMesh.position: " + JSON.stringify(thisObjectMesh.position));

    //Create & compute bounding box
    let bbox = new THREE.Box3().setFromObject(meshGroup);
    // Visible bounding box
    // let helper = new THREE.BoundingBoxHelper(meshGroup, 0xff0000);
    // helper.update();
    // scene.add(helper);

    //Reposition model to be on the ground
    const bboxScale = new THREE.Vector3();
    bbox.getSize(bboxScale);
    const bottomPivotY = bboxScale.y / 2;
    meshGroup.position.setY(bottomPivotY);

    //Initialize color inputs
    //top: ["160px", "240px", "320px"],
    let y = 0;
    const itemsInColumn = 8;
    let mathFloorBuffer = 0;
    for (let i = 0; i < materials.length; i++) {
      const mathFloor = Math.floor(i / itemsInColumn);
      y = mathFloorBuffer != mathFloor ? 0 : i - mathFloor * itemsInColumn;
      const top = 40 + y * 60 + "px";
      const left = 15 + mathFloor * 60 + "px";
      const initializeColorInput = new CustomEvent(
        events.initializeColorInput,
        {
          detail: {
            id: i,
            color: materials[i].material.color.getHexString(),
            top: top,
            left: left,
          },
        }
      );
      document.dispatchEvent(initializeColorInput);
      mathFloorBuffer = mathFloor;
      y++;
    }
    //Change material colors on color input change
    document.addEventListener(events.onChangeColorInput, (e) => {
      const id = e.detail.id;
      const color = e.detail.color;
      const rgb255Color = hexToRgb(color);
      materials[id].material.color.set(
        `rgb(${rgb255Color.r}, ${rgb255Color.g}, ${rgb255Color.b})`
      );
      materials[id].material.needsUpdate = true;
      //console.log(`Change material ${id} color with value hex: ${color} and rgb: ${JSON.stringify(rgb255Color)}`);
      //console.log(`New material ${id} color: ${materials[id].material.color.getHexString()}`)
    });
  }

  function createMaterials(voxData, colorsArray) {
    const materials = new Array();
    const colorIndexes = voxData.xyzi.values.map((value) => value.i);
    const uniqueColorIndexes = [...new Set(colorIndexes)];
    for (let i = 0; i < uniqueColorIndexes.length; i++) {
      materials[i] = {};
      materials[i].index = uniqueColorIndexes[i];
      const material = new THREE.MeshStandardMaterial(); //new THREE.MeshBasicMaterial();
      const color = colorsArray[uniqueColorIndexes[i] - 1];
      material.color = new THREE.Color(
        `rgb(${color.r}, ${color.g}, ${color.b})`
      );
      materials[i].material = material;
    }
    //console.log("colorIndexes:" + uniqueColorIndexes);
    //console.log("Materials Length: " + materials.length);
    return materials;
  }

  const createMesh = (voxel, meshGroup, materials) => {
    const geometry = new THREE.BoxBufferGeometry(1, 1, 1);
    const material = materials.find(
      (material) => material.index === voxel.i
    ).material;

    //Unique material for each cube. Could be useful for others POCs.
    // const material = new THREE.MeshBasicMaterial();
    // const color = colorsArray[voxel.i-1];
    // material.color = new THREE.Color(`rgb(${color.r}, ${color.g}, ${color.b})`);

    const cube = new THREE.Mesh(geometry, material);
    cube.position.set(voxel.x, voxel.y, voxel.z);
    thisObjectGroup.add(cube);
    //scene.add(cube);
    return cube;
  };
});

function degToRad(degrees) {
  let pi = Math.PI;
  return degrees * (pi / 180);
}

function hexToRgb(hex) {
  var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  return result
    ? {
        r: parseInt(result[1], 16),
        g: parseInt(result[2], 16),
        b: parseInt(result[3], 16),
      }
    : null;
}

function rgb255ToRgb(rgb) {
  return {
    r: rgb.r / 255,
    g: rgb.g / 255,
    b: rgb.b / 255,
  };
}

Vox Loader ( Built with webpack )