Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                
              
            
!

CSS

              
                
              
            
!

JS

              
                /*
Original author:
https://zalo.github.io/blog/kabsch/

*/

import * as THREE from "https://cdn.jsdelivr.net/npm/three@0.114/build/three.module.js";
import {
    OrbitControls
}
from "https://cdn.jsdelivr.net/npm/three@0.114/examples/jsm/controls/OrbitControls.js";
import {
    DragControls
}
from "https://cdn.jsdelivr.net/npm/three@0.114/examples/jsm/controls/DragControls.js";
("use strict");

var g_camera, g_scene, g_renderer;
var g_controls;

var g_pointsRef = []; // blue boxes (The aim)
var g_pointsToMatch = []; // white boxes (to be transformed to match the aim)

var g_avg;
var g_curQuaternion = new THREE.Quaternion(0, 0, 0, 1);
var g_numPoints = 6;
var g_nb_iterations = 1;

// set to "true" to make the blue cubes rotates 
// and observe we are able to find back the rotation
var g_animate = false;
var g_do_matching = true;

// ===============================================================

init();
animate();

// ===============================================================

function pseudo_rand_1(i){ return ((i * 212435 + 2312  ) % 255) / 255.0; }
function pseudo_rand_2(i){ return ((i * 878923 + 123342  ) % 255) / 255.0; }
function pseudo_rand_3(i){ return ((i * 18464 + 79874  ) % 255) / 255.0; }

function pseudo_rand_4(i){ return ((i * 896559 + 626  ) % 255) / 255.0; }
function pseudo_rand_5(i){ return ((i * 3645 + 1666) % 255) / 255.0; }
function pseudo_rand_6(i){ return ((i * 85236 + 375961  ) % 255) / 255.0; }

function initPoints(draggableObjects) {
    let boxGeometry = new THREE.BoxBufferGeometry(100, 100, 100);
    let blue = new THREE.MeshPhongMaterial({
        color: 0x3399dd
    });
    let white = new THREE.MeshLambertMaterial({
        color: 0x888888
    });

    let scl = new THREE.Vector3(100, 100, 100);
    for (let i = 0; i < g_numPoints; i++) {
        let box = new THREE.Mesh(boxGeometry, blue);
        g_scene.add(box);
        box.scale.set(0.075, 0.075, 0.075);        
        if(true){
        box.position.set(
            pseudo_rand_1(i+628) * scl.x - scl.x / 2.0,
            pseudo_rand_2(i+923) * scl.y - scl.y / 2.0 + 100.0,
            pseudo_rand_3(i+123) * scl.z - scl.z / 2.0
            );      
        }else{
        box.position.set(
            Math.random() * scl.x - scl.x / 2,
            Math.random() * scl.y - scl.y / 2 + 100,
            Math.random() * scl.z - scl.z / 2
            );
        }
        box.castShadow = true;
        draggableObjects.push(box);
        g_pointsRef.push(box);
    }

    let rcl = new THREE.Vector3(20, 20, 20);
    for (let i = 0; i < g_numPoints; i++) {
        let box = new THREE.Mesh(boxGeometry, white);
        g_scene.add(box);
        box.scale.set(0.05, 0.05, 0.05);
        let randomOffset;
        if(true) {        
        randomOffset = new THREE.Vector3(
                pseudo_rand_4(i+1535) * rcl.x - rcl.x / 2 + pseudo_rand_1(i+628) * rcl.x * 3,
                pseudo_rand_5(i+6389) * rcl.y - rcl.y / 2 + 93,                
                pseudo_rand_6(i+1453) * rcl.z - rcl.z / 2 + 3);
        }else{ 
        randomOffset = new THREE.Vector3(
                Math.random() * rcl.x - rcl.x / 2,
                Math.random() * rcl.y - rcl.y / 2 + 100,
                Math.random() * rcl.z - rcl.z / 2);
        }

        box.position.copy(randomOffset.add(g_pointsRef[i].position));
        box.castShadow = true;
        g_pointsToMatch.push(box);
    }

    let average = getAverage(g_pointsRef);

    g_camera.position.y = 150;
    g_camera.lookAt(average);
    if (g_controls) {
        g_controls.target.set(average.x, average.y, average.z);
        g_controls.update();
    }

    g_avg = new THREE.Mesh(
            boxGeometry,
            new THREE.MeshPhongMaterial({
                color: 0xdd3333
            }));
    g_scene.add(g_avg);
    g_avg.scale.set(0.075, 0.075, 0.075);
    g_avg.position.set(average.x, average.y, average.z);
    g_avg.castShadow = true;
}

function getAverage(points) {
    let average = new THREE.Vector3(0, 0, 0);
    for (let i = 0; i < points.length; i++) {
        average.add(points[i].position);
    }
    average.divideScalar(points.length);
    return average;
}

//https://animation.rwth-aachen.de/media/papers/2016-MIG-StableRotation.pdf
//Iteratively apply torque to the basis using Cross products (in place of SVD)
function quaternionTorqueDecomposition(A, curQuaternion, iterations = 9) { 
    // Cancels out the momentum from the prior frame
    let resQuaternion = new THREE.Quaternion(0, 0, 0, 1);
    // or take int account previous frame for faster convergence:
    //resQuaternion.copy(curQuaternion);     
    
    let QuatBasis = [ 
        new THREE.Vector3(1, 0, 0),
        new THREE.Vector3(0, 1, 0),
        new THREE.Vector3(0, 0, 1)
    ];
  
    let quatMatrix = new THREE.Matrix4().makeRotationFromQuaternion(resQuaternion);

    for (let iter = 0; iter < iterations; iter++) {
        quatMatrix.makeRotationFromQuaternion(resQuaternion);
        quatMatrix.extractBasis(QuatBasis[0], QuatBasis[1], QuatBasis[2]);

        let omegaDenom = Math.abs(
                QuatBasis[0].dot(A[0]) +
                QuatBasis[1].dot(A[1]) +
                QuatBasis[2].dot(A[2]) +
                0.00000001);

        let omega = QuatBasis[0]
            .clone()
            .cross(A[0])
            .add(QuatBasis[1].clone().cross(A[1]))
            .add(QuatBasis[2].clone().cross(A[2]))
            .divideScalar(omegaDenom);

        let w = omega.length();
        if (w < 0.00000001) {
            break;
        }
        resQuaternion.premultiply(
            new THREE.Quaternion().setFromAxisAngle(omega.normalize(), w));
        resQuaternion.normalize(); //Normalizes the Quaternion; critical for error suppression
    }
  
  return resQuaternion;
}

function transposeMult(vec1, vec2) {
    let covariance = [
        // Initialize Cross Covariance Matrix
        new THREE.Vector3(0, 0, 0),
        new THREE.Vector3(0, 0, 0),
        new THREE.Vector3(0, 0, 0)
    ];

    for (let i = 0; i < 3; i++) {
        //i is the row in this matrix
        for (let j = 0; j < 3; j++) {
            //j is the column in the other matrix
            for (let k = 0; k < vec1.length; k++) {
                //k is the column in this matrix
                covariance[i].setComponent(
                    j,
                    covariance[i].getComponent(j) +
                    vec1[k].getComponent(i) * vec2[k].getComponent(j));
            }
        }
    }
    return covariance;
}

function kabschPoints(
            pointsIn /*To be transformed to match the aim (white*/,
            pointsRef /*Base position / aim (blue)*/) 
{
    let workingRef = [];
    let workingIn = [];
    let refAverage = getAverage(pointsRef);
    let inAverage = getAverage(pointsIn);

    // Mean-center the points for the optimal translation
    for (let i = 0; i < pointsRef.length; i++) {
        // p_i - avg      
        workingRef.push(pointsRef[i].position.clone().sub(refAverage));        
        workingIn .push(pointsIn[i] .position.clone().sub(inAverage ));
    }

    // Calculate the optimal rotation
    let crossCovarianceMatrix = transposeMult(/*const*/workingIn, /*const*/workingRef);
    g_curQuaternion = quaternionTorqueDecomposition(crossCovarianceMatrix, g_curQuaternion, g_nb_iterations);
     

    // Apply the optimal translation and rotation
    for (let i = 0; i < workingIn.length; i++) {
        workingIn[i].applyQuaternion(g_curQuaternion);
        pointsIn[i].position.copy(workingIn[i].add(refAverage));
    }
}

function init() {
    let container = document.createElement("div");
    document.body.appendChild(container);

    g_camera = new THREE.PerspectiveCamera(
            60,
            window.innerWidth / window.innerHeight,
            1,
            2000);
    g_camera.position.set(50, 100, 150);

    g_scene = new THREE.Scene();
    g_scene.background = new THREE.Color(0xa0a0a0); //0xffffff
    g_scene.fog = new THREE.Fog(0xa0a0a0, 200, 800); //0xffffff

    let light1 = new THREE.HemisphereLight(0xffffff, 0x444444);
    light1.position.set(0, 200, 0);
    g_scene.add(light1);

    let light2 = new THREE.DirectionalLight(0xbbbbbb);
    light2.position.set(0, 200, 100);
    light2.castShadow = true;
    light2.shadow.camera.top = 180;
    light2.shadow.camera.bottom = -100;
    light2.shadow.camera.left = -120;
    light2.shadow.camera.right = 120;
    g_scene.add(light2);
    //scene.add(new THREE.CameraHelper(light.shadow.camera));

    // ground
    let mesh = new THREE.Mesh(
            new THREE.PlaneBufferGeometry(2000, 2000),
            new THREE.MeshPhongMaterial({
                color: 0x999999,
                depthWrite: false
            }));
    mesh.rotation.x = -Math.PI / 2;
    mesh.receiveShadow = true;
    g_scene.add(mesh);

    let grid = new THREE.GridHelper(2000, 20, 0x000000, 0x000000);
    grid.material.opacity = 0.2;
    grid.material.transparent = true;
    g_scene.add(grid);

    g_renderer = new THREE.WebGLRenderer({
        antialias: true
    });
    g_renderer.setPixelRatio(window.devicePixelRatio);
    g_renderer.setSize(window.innerWidth, window.innerHeight);
    g_renderer.shadowMap.enabled = true;
    document.body.style.margin = 0;
    document.body.style.padding = 0;
    document.body.style.overflow = "hidden";
    document.body.style.position = "fixed";
    container.appendChild(g_renderer.domElement);
    window.addEventListener("resize", onWindowResize, false);

    g_controls = new /*THREE.*/ OrbitControls(g_camera, g_renderer.domElement);
    g_controls.target.set(0, 45, 0);
    g_controls.update();

    var draggableObjects = [];

    //draggableObjects.push(mesh);
    //g_scene.add(g_cogPointMesh);

    initPoints(draggableObjects);

    var dragControls = new /*THREE.*/ DragControls(
            draggableObjects,
            g_camera,
            g_renderer.domElement);

    dragControls.addEventListener("dragstart", function () {
        g_controls.enabled = false;
    });
    dragControls.addEventListener("dragend", function () {
        g_controls.enabled = true;
    });
}

function onWindowResize() {
    g_camera.aspect = window.innerWidth / window.innerHeight;
    g_camera.updateProjectionMatrix();
    g_renderer.setSize(window.innerWidth, window.innerHeight);
}

function animate() {
  
    if(g_animate){    
    for (let i = 0; i < g_pointsRef.length; i++) {            
        var axis = new THREE.Vector3(0, 1, 0 );
        var angle = Math.PI / 100;        
        g_pointsRef[i].position.applyAxisAngle( axis, angle );
    }
    }
  
    if(g_do_matching)
    {
        kabschPoints(g_pointsToMatch, g_pointsRef);

        let averageRef = getAverage(g_pointsRef);
        g_avg.position.set(averageRef.x, averageRef.y, averageRef.z);
    }
  
    requestAnimationFrame(animate);
    g_renderer.render(g_scene, g_camera);
}

              
            
!
999px

Console