ArcGIS API在視圖中渲染Three.js場(chǎng)景

ArcGIS API中的SceneView使用WebGL在屏幕上渲染地圖和場(chǎng)景,還提供了一個(gè)底層接口來(lái)訪問(wèn)SceneView的WebGL上下文,因此可以創(chuàng)建與場(chǎng)景交互的自定義??可視化效果,方式與內(nèi)置圖層相同。那么我們可以直接編寫(xiě)WebGL代碼,也可以集成第三方WebGL庫(kù)(例如Three.js)。
現(xiàn)在我門(mén)就來(lái)嘗試在ArcGIS的三維場(chǎng)景中加入一個(gè)物體,比如說(shuō)UFO

UFO模型

該模型下載自CG模型網(wǎng)。然后通過(guò)3DS MAX軟件導(dǎo)出為obj格式模型。

1.引入需要用到的類(lèi)

引入以下所要用到的類(lèi),并創(chuàng)建一個(gè)地圖三維場(chǎng)景:

require([
    'esri/Map', // 生成地圖的類(lèi)
    'esri/views/SceneView', // 生成三維場(chǎng)景的類(lèi)
    'esri/views/3d/externalRenderers', // 外部渲染器對(duì)象
    'esri/geometry/SpatialReference', // 空間參考的類(lèi)
    ], function(Map, SceneView, externalRenderers, SpatialReference) {
    const map = new Map({
        basemap: 'topo-vector',
    });

    const view = new SceneView({
        container: 'viewDiv', // 包含視圖的容器
        map: map,
        center: [105, 29],
        zoom: 3,
    });
});

2.定義外部渲染器對(duì)象

我們需要使用回調(diào)方法和屬性來(lái)定義一個(gè)外部渲染器,在向SceneView注冊(cè)時(shí)需要用到。

const myRenderer = {
    renderer: null, // three.js 渲染器
    camera: null, // three.js 相機(jī)
    scene: null, // three.js 中的場(chǎng)景
    ambient: null, // three.js中的環(huán)境光
    sun: null, // three.js中的平行光源,模擬太陽(yáng)光
    ufo: null, // ufo

    setup: function(context) {},
    render: function(context) {},
    dispose: function(context) {},
};

其中setuprenderdispose為渲染器回調(diào)。

setup 函數(shù)通常在將外部渲染器添加到視圖后調(diào)用一次,或者每當(dāng)SceneView準(zhǔn)備就緒時(shí)調(diào)用一次。如果就緒狀態(tài)循環(huán)(例如,當(dāng)將不同的Map分配給視圖時(shí)),則可以再次調(diào)用它。接收一個(gè)類(lèi)型為RenderContext的參數(shù)。
render 函數(shù)在每一幀中調(diào)用以執(zhí)行狀態(tài)更新和繪制。接收一個(gè)類(lèi)型為RenderContext的參數(shù)。
dispose 函數(shù)在從視圖中移除外部渲染器時(shí),或者視圖的就緒狀態(tài)變?yōu)閒alse時(shí)調(diào)用。接收一個(gè)類(lèi)型為RenderContext的參數(shù)。

2.1完善setup回調(diào)函數(shù)

我們需要在該回調(diào)函數(shù)中定義Three.js的渲染器、場(chǎng)景、攝像機(jī)和光源,還要導(dǎo)入需要加載到場(chǎng)景中的UFO模型。

①定義Three.js的渲染器

this.renderer = new THREE.WebGLRenderer({
    context: context.gl, // 可用于將渲染器附加到已有的渲染環(huán)境(RenderingContext)中
    premultipliedAlpha: false, // renderer是否假設(shè)顏色有 premultiplied alpha. 默認(rèn)為true
});

設(shè)置設(shè)備像素比,可以避免HiDPI設(shè)備上繪圖模糊:

this.renderer.setPixelRatio(window.devicePixelRatio);

設(shè)置視口大小和三維場(chǎng)景的大小一樣:

this.renderer.setViewport(0, 0, view.width, view.height);

為了防止Three.js清除ArcGIS JS API提供的緩沖區(qū),需要添加以下代碼:

this.renderer.autoClearDepth = false; // 定義renderer是否清除深度緩存
this.renderer.autoClearStencil = false; // 定義renderer是否清除模板緩存
this.renderer.autoClearColor = false; // 定義renderer是否清除顏色緩存

ArcGIS JS API渲染自定義離屏緩沖區(qū),而不是默認(rèn)的幀緩沖區(qū)。我們必須將這段代碼注入到Three.js運(yùn)行時(shí)中,以便綁定這些緩沖區(qū)而不是默認(rèn)的緩沖區(qū)。

const originalSetRenderTarget = this.renderer.setRenderTarget.bind(
    this.renderer
);
this.renderer.setRenderTarget = function(target) {
    originalSetRenderTarget(target);
    if (target == null) {
        context.bindRenderTarget();
    }
};

②定義場(chǎng)景和相機(jī)

this.scene = new THREE.Scene(); // 場(chǎng)景
this.camera = new THREE.PerspectiveCamera(); // 相機(jī)

③定義光源并添加到場(chǎng)景中

this.ambient = new THREE.AmbientLight(0xffffff, 0.5); // 環(huán)境光
this.scene.add(this.ambient); // 把環(huán)境光添加到場(chǎng)景中
this.sun = new THREE.DirectionalLight(0xffffff, 0.5); // 平行光(模擬太陽(yáng)光)
this.scene.add(this.sun); // 把太陽(yáng)光添加到場(chǎng)景中

④添加輔助工具

為了更好的理解空間位置,可以添加坐標(biāo)軸輔助工具:

const axesHelper = new THREE.AxesHelper(10000000);
this.scene.add(axesHelper);

⑤加載OBJ模型

加載模型之前先要加載模型的材質(zhì)信息文件,也就是.mtl格式的文件,需要用到MTLLoader加載器。加載obj模型則需要用到OBJLoader加載器。它們都可以在全球最大同性交友網(wǎng)站(GitHub)的three.js代碼倉(cāng)庫(kù)下找到。

let mtlLoader = new MTLLoader();
mtlLoader.setPath('../assets/model/');
mtlLoader.load('ufo.mtl', materials => {
    materials.preload();
    // OBJLoader
    const loader = new OBJLoader();
    loader.setMaterials(materials);
    loader.setPath('../assets/model/');
    loader.load(
        'ufo.obj', // 資源地址
        // 加載成功后的回調(diào)
        object => {
            // ...
        },
        // 加載過(guò)程中的回調(diào)
        function(xhr) {
            // console.log((xhr.loaded / xhr.total) * 100 + '% loaded');
        },
        // 加載模型出錯(cuò)的回調(diào)
        function(error) {
            console.error('An error happened: ', error);
        }
    );
});

加載成功的回調(diào)方法接收一個(gè)參數(shù),該參數(shù)就是Object3D對(duì)象,也就是我們要加載的3D模型對(duì)象。在該回調(diào)中,我們可以進(jìn)行模型的位置調(diào)整,以及大小調(diào)整等設(shè)置,然后添加到場(chǎng)景中。

this.ufo = object;
const entryPos = [70, 0, 550000]; // 輸入位置 [經(jīng)度, 緯度, 高程]
const renderPos = [0, 0, 0]; // 渲染位置
externalRenderers.toRenderCoordinates(
    view,
    entryPos,
    0,
    SpatialReference.WGS84,
    renderPos,
    0,
    1
);
this.ufo.scale.set(100000, 100000, 100000); // UFO放大一點(diǎn)
this.ufo.position.set( // 設(shè)置UFO位置
    renderPos[0],
    renderPos[1],
    renderPos[2]
);
this.scene.add(this.ufo); // 添加到場(chǎng)景中

externalRenderers對(duì)象的toRenderCoordinates方法是將位置從給定的空間參考轉(zhuǎn)換為內(nèi)部渲染坐標(biāo)系,共接收7個(gè)參數(shù)(view, srcCoordinates, srcStart, srcSpatialReference, destCoordinates, destStart, count )。
view: 地圖場(chǎng)景。該參數(shù)類(lèi)型為SceneView
srcCoordinates: 一個(gè)或多個(gè)向量坐標(biāo)組成的一維數(shù)組,例如[x1, y1, z1, x2, y2, z2],數(shù)組中元素?cái)?shù)量必須是3的倍數(shù)。該參數(shù)類(lèi)型為Array
srcStart: srcCoordinates中的索引,從該索引開(kāi)始讀取坐標(biāo)。該參數(shù)類(lèi)型為Number
srcSpatialReference: 輸入坐標(biāo)的空間參考。如果為null,則用view.spatialReference替代。該參數(shù)類(lèi)型為SpatialReference
destCoordinates: 對(duì)要寫(xiě)入結(jié)果的數(shù)組的引用。該參數(shù)類(lèi)型為Array
destStart: destCoordinates中的索引,坐標(biāo)將從索引處開(kāi)始寫(xiě)入。該參數(shù)類(lèi)型為Number
count: 要轉(zhuǎn)換的坐標(biāo)數(shù)量。該參數(shù)類(lèi)型為Number

2.2完善render回調(diào)函數(shù)

在每一幀中都會(huì)調(diào)用該回調(diào)函數(shù),接收一個(gè)類(lèi)型為RenderContext的參數(shù)。在該回調(diào)中我們可以進(jìn)行相機(jī)參數(shù)更新,模型位置更新等操作。

// 更新相機(jī)參數(shù)
const cam = context.camera;
this.camera.position.set(cam.eye[0], cam.eye[1], cam.eye[2]);
this.camera.up.set(cam.up[0], cam.up[1], cam.up[2]);
this.camera.lookAt(
    new THREE.Vector3(cam.center[0], cam.center[1], cam.center[2])
);
// 投影矩陣可以直接復(fù)制
this.camera.projectionMatrix.fromArray(cam.projectionMatrix);

// 更新UFO
this.ufo.rotation.y += 0.1;

// 繪制場(chǎng)景
this.renderer.state.reset();
this.renderer.render(this.scene, this.camera);

externalRenderers.requestRender(view); // 請(qǐng)求重繪視圖。

// 清除WebGL狀態(tài)
context.resetWebGLState();

添加外部渲染器

最后還有一個(gè)關(guān)鍵步驟,向SceneView實(shí)例注冊(cè)外部渲染器:

externalRenderers.add(view, myRenderer);

這樣我們就成功地在地圖三維場(chǎng)景中渲染出用Three.js加載的外部模型UFO啦!

地圖中加載UFO模型


以下是完整代碼

<html>
  <head>
    <meta charset="utf-8" />
    <meta
      name="viewport"
      content="initial-scale=1, maximum-scale=1, user-scalable=no"
    />
    <title>ArcGIS API在視圖中渲染Three.js場(chǎng)景</title>
    <style>
      html,
      body,
      #viewDiv {
        padding: 0;
        margin: 0;
        height: 100%;
        width: 100%;
      }
    </style>

    <link
      rel="stylesheet"
      
    />
    <script src="https://js.arcgis.com/4.14/"></script>

    <script type="module">
      import * as THREE from 'https://threejs.org/build/three.module.js';
      import { OBJLoader } from 'https://threejs.org/examples/jsm/loaders/OBJLoader.js';
      import { MTLLoader } from 'https://threejs.org/examples/jsm/loaders/MTLLoader.js';

      require([
        'esri/Map',
        'esri/views/SceneView',
        'esri/views/3d/externalRenderers',
        'esri/geometry/SpatialReference',
      ], function(Map, SceneView, externalRenderers, SpatialReference) {
        const map = new Map({
          basemap: 'topo-vector',
        });

        const view = new SceneView({
          container: 'viewDiv',
          map: map,
          center: [105, 29],
          zoom: 3,
        });

        const myRenderer = {
          renderer: null, // three.js 渲染器
          camera: null, // three.js 相機(jī)
          scene: null, // three.js 中的場(chǎng)景
          ambient: null, // three.js中的環(huán)境光
          sun: null, // three.js中的平行光源,模擬太陽(yáng)光
          ufo: null, // ufo

          setup: function(context) {
            this.renderer = new THREE.WebGLRenderer({
              context: context.gl, // 可用于將渲染器附加到已有的渲染環(huán)境(RenderingContext)中
              premultipliedAlpha: false, // renderer是否假設(shè)顏色有 premultiplied alpha. 默認(rèn)為true
            });
            this.renderer.setPixelRatio(window.devicePixelRatio); // 設(shè)置設(shè)備像素比。通常用于避免HiDPI設(shè)備上繪圖模糊
            this.renderer.setViewport(0, 0, view.width, view.height); // 視口大小設(shè)置

            // 防止Three.js清除ArcGIS JS API提供的緩沖區(qū)。
            this.renderer.autoClearDepth = false; // 定義renderer是否清除深度緩存
            this.renderer.autoClearStencil = false; // 定義renderer是否清除模板緩存
            this.renderer.autoClearColor = false; // 定義renderer是否清除顏色緩存

            // ArcGIS JS API渲染自定義離屏緩沖區(qū),而不是默認(rèn)的幀緩沖區(qū)。
            // 我們必須將這段代碼注入到three.js運(yùn)行時(shí)中,以便綁定這些緩沖區(qū)而不是默認(rèn)的緩沖區(qū)。
            const originalSetRenderTarget = this.renderer.setRenderTarget.bind(
              this.renderer
            );
            this.renderer.setRenderTarget = function(target) {
              originalSetRenderTarget(target);
              if (target == null) {
                // 綁定外部渲染器應(yīng)該渲染到的顏色和深度緩沖區(qū)
                context.bindRenderTarget();
              }
            };

            this.scene = new THREE.Scene(); // 場(chǎng)景
            this.camera = new THREE.PerspectiveCamera(); // 相機(jī)

            this.ambient = new THREE.AmbientLight(0xffffff, 0.5); // 環(huán)境光
            this.scene.add(this.ambient); // 把環(huán)境光添加到場(chǎng)景中
            this.sun = new THREE.DirectionalLight(0xffffff, 0.5); // 平行光(模擬太陽(yáng)光)
            this.scene.add(this.sun); // 把太陽(yáng)光添加到場(chǎng)景中

            // 添加坐標(biāo)軸輔助工具
            const axesHelper = new THREE.AxesHelper(10000000);
            this.scene.add(axesHelper);

            // 加載模型
            let mtlLoader = new MTLLoader();
            mtlLoader.setPath('../assets/model/');
            mtlLoader.load('ufo.mtl', materials => {
              materials.preload();
              // OBJLoader
              const loader = new OBJLoader();
              loader.setMaterials(materials);
              loader.setPath('../assets/model/');
              loader.load(
                'ufo.obj', // 資源地址
                // 加載成功后的回調(diào)
                object => {
                  this.ufo = object;
                  const entryPos = [70, 0, 550000]; // 輸入位置
                  const renderPos = [0, 0, 0]; // 渲染位置
                  externalRenderers.toRenderCoordinates(
                    view,
                    entryPos,
                    0,
                    SpatialReference.WGS84,
                    renderPos,
                    0,
                    1
                  );
                  this.ufo.scale.set(100000, 100000, 100000); // ufo放大一點(diǎn)
                  this.ufo.position.set(
                    renderPos[0],
                    renderPos[1],
                    renderPos[2]
                  );
                  this.scene.add(this.ufo);
                  context.resetWebGLState();
                },
                // 加載過(guò)程中的回調(diào)
                function(xhr) {
                  // console.log((xhr.loaded / xhr.total) * 100 + '% loaded');
                },
                // 加載模型出錯(cuò)的回調(diào)
                function(error) {
                  console.error('An error happened: ', error);
                }
              );
            });
          },
          render: function(context) {
            // 更新相機(jī)參數(shù)
            const cam = context.camera;
            this.camera.position.set(cam.eye[0], cam.eye[1], cam.eye[2]);
            this.camera.up.set(cam.up[0], cam.up[1], cam.up[2]);
            this.camera.lookAt(
              new THREE.Vector3(cam.center[0], cam.center[1], cam.center[2])
            );
            // 投影矩陣可以直接復(fù)制
            this.camera.projectionMatrix.fromArray(cam.projectionMatrix);
            // 更新UFO
            this.ufo.rotation.y += 0.1;
            // 繪制場(chǎng)景
            this.renderer.state.reset();
            this.renderer.render(this.scene, this.camera);
            // 請(qǐng)求重繪視圖。
            externalRenderers.requestRender(view); 
            // cleanup
            context.resetWebGLState();
          },
        };
        // 注冊(cè)renderer
        externalRenderers.add(view, myRenderer);
      });
    </script>
  </head>
  <body>
    <div id="viewDiv"></div>
  </body>
</html>
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容