threejs gpu pick

package.json

{
  "name": "gpu-pick-code",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "scripts": {
    "start": "webpack-dev-server"
  },
  "dependencies": {
    "three": "0.110.0",
    "three-orbitcontrols": "2.110.3"
  },
  "devDependencies": {
    "html-webpack-plugin": "4.5.0",
    "ts-loader": "6.2.2",
    "typescript": "4.3.5",
    "webpack": "4.42.1",
    "webpack-cli": "3.3.12",
    "webpack-dev-server": "3.11.2"
  }
}

tsconfig.json

{
    "compilerOptions": {
        "noEmit": true,
        "module": "esnext",
        "target": "es6",
        "lib": ["ES2019","dom"],
        "sourceMap": true,
        "moduleResolution": "node",
        "forceConsistentCasingInFileNames": true,
        "noImplicitReturns": true,
        "noImplicitThis": true,
        "skipLibCheck": true,
        "suppressImplicitAnyIndexErrors": true,
        "experimentalDecorators": true,
        "noUnusedLocals": true,
        "downlevelIteration": true,
        "strict": true,
        "strictPropertyInitialization": false,
        "allowSyntheticDefaultImports": true,
        "skipDefaultLibCheck": true
    },
    "exclude": [
        "node_modules",
    ]
}

webpack.config.js

const HtmlWebpackPlugin = require('html-webpack-plugin');
const { resolve } = require('path');

module.exports = {
    devtool: 'source-map',
    plugins: [
        new HtmlWebpackPlugin({
            template: resolve('./index.html')
        })
    ],
    resolve: {
        extensions: ['.ts', '.js']
    },
    module:{
            rules:[
                {
                    test: /\.ts$/,
                    exclude: /node_modules/,
                    loader: 'ts-loader',
                    options: {
                        transpileOnly: true,
                        experimentalWatchApi: true,
                    }
                },
            ],
        },
    devServer: {
        compress: true,
        stats: {
            assets: false,
            builtAt: true,
            modules: false,
            entrypoints: false,
            /**
             * ts-node transpileOnly: true
             * if you enable this option, webpack 4 will give you "export not found" warnings any time you re-export a type:
             * The reason this happens is that when typescript doesn't do a full type check, 
             * it does not have enough information to determine whether an imported name is a type or not, 
             * so when the name is then exported, typescript has no choice but to emit the export. 
             * Fortunately, the extraneous export should not be harmful, so you can just suppress these warnings:
             */
            // warningsFilter: /export .* was not found in/
        },
    },
};

src/three-orbitcontrols.d.ts

declare module 'three-orbitcontrols' {
    class OrbitControls {
        constructor( camera: THREE.Camera, dom: HTMLElement );
    }

   export = OrbitControls;
}

src/index.ts

import * as THREE from 'three';
import OrbitControls from 'three-orbitcontrols';

// 创建相机
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.z = 5;

// 创建渲染器
const renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );

// 创建场景
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xeaeaea);

// 创建mesh
const geometry = new THREE.BoxGeometry( 1, 1, 1 );
const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);

const edges = new THREE.EdgesGeometry(geometry);
const lineMaterial = new THREE.LineBasicMaterial({ color: 0x000000 });
const line = new THREE.LineSegments(edges, lineMaterial);
scene.add(line);

// 添加控制器
new OrbitControls(camera, document.body);

function animate() {
    requestAnimationFrame( animate );
    renderer.render( scene, camera );
}
animate();


const w = 20; // gpu拾取宽度
const pickingTexture = new THREE.WebGLRenderTarget(w, w);
const pickingBuffer = new Uint8Array(4 * w * w);

const canvas = document.querySelector('canvas')!;
const ctx = canvas.getContext('2d')!;


let lock = false;
document.addEventListener('mousedown', () => {
    lock = true;
    renderer.setRenderTarget(null);
    document.body.className = 'lock';
});

document.addEventListener('mouseup', () => {
    lock = false;
    setTimeout(() => document.body.className = '', 100);
});

document.addEventListener('mousemove', (event) => {
    if (lock) {
        return;
    }
    // 移动画布中的选中框
    const x = event.clientX - 10;
    const y = event.clientY - 10;
    const pick = document.querySelector('.pick') as HTMLElement;
    pick.style.transform = `translate(${x}px, ${y}px)`;

    // threejs拾取场景中的图像
    camera.setViewOffset(window.innerWidth, window.innerHeight, x, y, w, w);
    renderer.setRenderTarget(pickingTexture);
    renderer.render(scene, camera);
    pickingBuffer.fill(0);
    renderer.readRenderTargetPixels(pickingTexture, 0, 0, w, w, pickingBuffer);
    camera.clearViewOffset();

 
    // threejs中y坐标与canvas中的y坐标不一致 故要做转化
    const unit8ArrayGroup = [] as Uint8Array[];
    for (let i = 0; i < pickingBuffer.length; i += 4 * w) {
        unit8ArrayGroup.push(pickingBuffer.slice(i, i + 4* w));
    }
    const mirror = unit8ArrayGroup.reverse().reduce((arr, u) => {
        arr.push(...u);
        return arr;
    }, [] as number[]);

    // 将数据填充到canvas中
    const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
    const data = imageData.data;
    for (let i = 0; i < mirror.length; i++ ) {
        data[i] = mirror[i];
    }
    ctx.putImageData(imageData, 0, 0);
});
image.png

你可能感兴趣的:(threejs gpu pick)