“This is the 26th day of my participation in the First Challenge 2022. For details: First Challenge 2022”

The sample code USES three. Js – r73 version: cdnjs.cloudflare.com/ajax/libs/t…

In this section, we will mainly explain how to import the model into three.js so that three.js can display our model. Let’s take a look.

Reconstruction project

Because of the example we are doing now, there is a lot of code that does not need to be changed very often, but there is also a lot of code, we can find the trouble to modify the code, so we refactor the project.

Our project is divided into the following parts:

  • Initialize the renderer
  • Initialization Scenario
  • Initializing the camera
  • Initialize light
  • Initialize the trackball
  • Initialize the GUI interface
  • Initialize performance monitoring
  • Initialize the color picker
  • Initialize object
  • Render loop
  • Listen for browser sizing changes

The parts we often need to revise:

  • The camera
  • The light
  • GUI interface
  • object
  • Update of data during rendering loop
  • Color change update

Later, when the implementation loads the model example, the project is refactored by function.

Threejs model loading process

How does threejs load models? Let’s take a look at the simplification of threejs loading models.

  • Model files on the server are stored as text
    • The model files on the server are mostly stored vertex information of the model, not necessarily stored as text
  • Download the file from the browser to the local PC
  • Javascript parses model files through various Loaders to generate Mesh models
    • Using loader, we can parse model files in various formats
    • Javascript parses the text file and generates a geometry, which eventually generates a Mesh
  • Add the model to the scene and display it

Load VTK model

  • Vtk model is a textual 3D model file that can represent point and surface information and can be stored in text form in a human-readable manner. This file format is used a lot in scientific research.
  • We want to load VTK model, we need to prepare VTK model file (the previous section has been used) and parse VTK model file loader, I have helped you to prepare
  • VTK model file: Bunny.vtk.zip (890 kB)
  • Loader to parse VTK:Github.com/mrdoob/thre…
    • All loaders are in threejs source directoryexamples/js/loadersIn, it is best to find the loaders corresponding to threejs, otherwise error prone

HTML page

  • Introduce our various JS resources
<! DOCTYPEhtml>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0" />
    <title>Document</title>
    <script src=".. /.. /libs/three.js"></script>
    <script src=".. /.. /libs/dat.gui.js"></script>
    <script src=".. /.. /libs/TrackballControls.js"></script>
    <script src=".. /.. /libs/jscolor.js"></script>
    <script src=".. /.. /libs/stats.js"></script>
    <! -- Check whether the browser supports webGL -->
    <script src=".. /.. /libs/Detector.js"></script>
    <script src=".. /.. /libs/loaders/VTKLoader.js"></script>
  </head>
  <style type="text/css">
    body {
      margin: 0;
      overflow: hidden;
    }
    div#canvas-frame {
      border: none;
      cursor: pointer;
      width: 100%;
      height: 600px;
      background-color: #eeeeee;
    }
    #color-picker {
      position: absolute;
      bottom: 50px;
      left: 50px;
    }
  </style>
  <body>
    <div id="canvas-frame"></div>
    <script src="./index.js"></script>
  </body>
</html>

Copy the code

Initialize the renderer

  • Since our model is white, we set the canvas to black
const clearColor = 0x000000; // 0xFFFFFF

function initRenderer() {
    width = document.getElementById('canvas-frame').clientWidth;
    height = document.getElementById('canvas-frame').clientHeight;
    renderer = new THREE.WebGLRenderer({
        antialias: true
    });
    renderer.setSize(width, height);
    document.getElementById('canvas-frame').appendChild(renderer.domElement);
    renderer.setClearColor(clearColor, 1.0);
}
Copy the code

Initialization Scenario

function initScene() {
    scene = new THREE.Scene();
}
Copy the code

Initializing the camera

function initCamera() {
    camera = new THREE.PerspectiveCamera(60, width / height, near, far);
    camera.position.z = 0.2;
    scene.add(camera);
}
Copy the code

Initialize light

function initLight() {
    light = new THREE.DirectionalLight(0xffffff);
    light.position.set(200.200.1000).normalize();
    camera.add(light);
    camera.add(light.target);
}
Copy the code
  • We added light to the camera to simulate light coming out of the camera

Initialize object

Creating the base Material

// Initialize the object
function initObject() {
    var material = new THREE.MeshLambertMaterial({ color: 0xffffff.side: THREE.DoubleSide });
}
Copy the code

Loader loads the VTK model

  • We’re throughTHREE.VTKLoaderVTK model can be loaded to return onegeometry
var loader = new THREE.VTKLoader();
loader.load("https://threejs-models.vercel.app/models/vtk/bunny.vtk".function (geometry) {
    geometry.computeVertexNormals();
    var mesh = new THREE.Mesh(geometry, material);
    mesh.position.setY(- 0.09);
    scene.add(mesh);
});
Copy the code
  • After the loader is loaded, obtain thegeometry, we can create a grid and add it to the scene.

Initialize various controls

  • Here the initialization of the ball, GUI interface, performance monitoring, color selector, browser window changes when processing, before all the actual combat, I will not introduce one
var param
function initGUI() {
    var ParamObj = function () {
        this.repeat = 4;
        this.wrap = 1000;
    }
    param = new ParamObj();
    const gui = new dat.GUI();
    / / GUI. The add (param, "repeat", 100, 100). The name (' texture repeat)
    / / GUI. The add (param, "wrap", 1000, 1002). The name (' texture around). Step (1)
}

var stats;
function initStats() {
    stats = new Stats();
    stats.showPanel(0); // 0: fps, 1: ms, 2: mb, 3+: custom
    // Map the stats interface to the upper left corner
    stats.domElement.style.position = 'absolute';
    stats.domElement.style.left = '0px';
    stats.domElement.style.top = '0px';
    document.body.appendChild(stats.dom);
}

function initColorPicker() {
    const colorPicker = document.createElement('div');
    colorPicker.id = 'color-picker'
    document.body.appendChild(colorPicker);
    const html = ``
    const colorPickerDom = document.querySelector('#color-picker')
    colorPickerDom.innerHTML = html;

    jscolor.install(colorPickerDom)

    jscolor.presets.default = {
        width: 141.// make the picker a little narrower
        position: 'top'.// position it to the right of the target
        previewPosition: 'right'.// display color preview on the right
        previewSize: 40.// make the color preview bigger
        format: 'hex'.previewSize: 40.closeButton: true.closeText: 'off'.palette: [
            '# 000000'.'#7d7d7d'.'# 870014'.'#ec1c23'.'#ff7e26'.'#fef100'.'#22b14b'.'#00a1e7'.'#3f47cc'.'#a349a4'.'#ffffff'.'#c3c3c3'.'#b87957'.'#feaec9'.'#ffc80d'.'#eee3af'.'#b5e61d'.'#99d9ea'.'#7092be'.'#c8bfe7',].}}function initControls() {
    controls = new THREE.TrackballControls(camera);

    controls.rotateSpeed = 0.2;// Rotation speed
    controls.zoomSpeed = 0.2;// Zoom speed
    controls.panSpeed = 0.1;// 平controls
    controls.staticMoving = false;// Static movement, true, no inertia
    controls.dynamicDampingFactor = 0.2;// The smaller the damping coefficient, the larger the slip

    controls.minDistance = near; // Minimum viewing Angle
    controls.maxDistance = far;// The maximum Angle is Infinity
}

/* Window changes trigger */
function onWindowResize() {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(window.innerWidth, window.innerHeight);
}
Copy the code

Render loop

  • With all the preparation done, it’s time to render
function animation() {
    renderer.render(scene, camera);
    requestAnimationFrame(animation);
    stats.update();
    controls.update();
    update()
}

/* Data update */
function update() {
	// All parameters are updated
}

function threeStart() {
    // Initialize the renderer
    initRenderer()
    // Initialize the scene
    initScene();
    // Initialize the camera
    initCamera();
    // Initialize the light
    initLight();
    // Initialize the object
    initObject();

    // Initialize the ball placement
    initControls();
    // Initialize the GUI interface
    initGUI()
    // Initialize performance monitoring
    initStats()
    // Initialize the color picker
    initColorPicker()

    // Render loop
    animation();
    /* Listen on events */
    window.addEventListener('resize', onWindowResize, false);
}
Copy the code

Final reality effect Codepen sample code

conclusion

In this section, we mainly talk about the following contents:

  • Refactoring the project code
  • Threejs model loading process
  • Load VTK model