123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467 |
- <!DOCTYPE html><html lang="ja"><head>
- <meta charset="utf-8">
- <title>で多くのオブジェクトを最適化</title>
- <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
- <meta name="twitter:card" content="summary_large_image">
- <meta name="twitter:site" content="@threejs">
- <meta name="twitter:title" content="Three.js – で多くのオブジェクトを最適化">
- <meta property="og:image" content="https://threejs.org/files/share.png">
- <link rel="shortcut icon" href="../../files/favicon_white.ico" media="(prefers-color-scheme: dark)">
- <link rel="shortcut icon" href="../../files/favicon.ico" media="(prefers-color-scheme: light)">
- <link rel="stylesheet" href="../resources/lesson.css">
- <link rel="stylesheet" href="../resources/lang.css">
- <script type="importmap">
- {
- "imports": {
- "three": "../../build/three.module.js"
- }
- }
- </script>
- </head>
- <body>
- <div class="container">
- <div class="lesson-title">
- <h1>で多くのオブジェクトを最適化</h1>
- </div>
- <div class="lesson">
- <div class="lesson-main">
- <p>この記事はthree.jsの連載記事の1つです。最初の記事は<a href="fundamentals.html">Three.jsの基礎知識</a>です。まだ読んでいない場合はそこから始めて下さい。</p>
- <p>three.jsには最適化する方法は多々あります。1つの方法は<em>ジオメトリのマージ</em>と呼ばれています。メッシュを作成すると描画リクエストを1つ以上行った事を表します。
- 2つのメッシュを描画すると結果が同じでも1つのメッシュを描画するよりもオーバーヘッドが大きく、最適化する1つの方法がメッシュのマージです。</p>
- <p>これが問題解決になるか、例を示してみます。
- <a href="https://globe.chromeexperiments.com/">WebGL Globe</a>を作り直してみましょう。</p>
- <p>まずデータが必要です。WebGL Globeで使用しているデータは<a href="http://sedac.ciesin.columbia.edu/gpw/">SEDAC</a>です。
- サイトをチェックすると<a href="https://beta.sedac.ciesin.columbia.edu/data/set/gpw-v4-basic-demographic-characteristics-rev10">人口統計データのグリッド形式</a>があります。
- 私は60分間の解像度データをダウンロードしました。データを見てみると以下のような感じになっています。</p>
- <pre class="prettyprint showlinemods notranslate lang-txt" translate="no"> ncols 360
- nrows 145
- xllcorner -180
- yllcorner -60
- cellsize 0.99999999999994
- NODATA_value -9999
- -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 ...
- -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 ...
- -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 ...
- -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 ...
- -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 ...
- -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 ...
- -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 ...
- -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 ...
- -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 ...
- -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 ...
- -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 ...
- -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 ...
- -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 ...
- 9.241768 8.790958 2.095345 -9999 0.05114867 -9999 -9999 -9999 -9999 -999...
- 1.287993 0.4395509 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999...
- -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 ...
- </pre>
- <p>キーと値のペアのような行がいくつかあり、その行に続くグリッドポイントごとの値の行があり、データポイントごとに1行ずつ並んでいます。
- データをもっと理解するために2Dでプロットしてみましょう。</p>
- <p>最初にテキストファイルをロードするコードです。</p>
- <pre class="prettyprint showlinemods notranslate lang-js" translate="no">async function loadFile(url) {
- const res = await fetch(url);
- return res.text();
- }
- </pre>
- <p>上記のコードは <code class="notranslate" translate="no">Promise</code> を返しファイルの内容は <code class="notranslate" translate="no">url</code> にあります。
- 次にファイルを解析するコードが必要です。</p>
- <pre class="prettyprint showlinemods notranslate lang-js" translate="no">function parseData(text) {
- const data = [];
- const settings = {data};
- let max;
- let min;
- // split into lines
- text.split('\n').forEach((line) => {
- // split the line by whitespace
- const parts = line.trim().split(/\s+/);
- if (parts.length === 2) {
- // only 2 parts, must be a key/value pair
- settings[parts[0]] = parseFloat(parts[1]);
- } else if (parts.length > 2) {
- // more than 2 parts, must be data
- const values = parts.map((v) => {
- const value = parseFloat(v);
- if (value === settings.NODATA_value) {
- return undefined;
- }
- max = Math.max(max === undefined ? value : max, value);
- min = Math.min(min === undefined ? value : min, value);
- return value;
- });
- data.push(values);
- }
- });
- return Object.assign(settings, {min, max});
- }
- </pre>
- <p>上記のコードはファイルから全てのキーと値のペアを持つオブジェクトを返します。また<code class="notranslate" translate="no">data</code> プロパティには全てのデータを1つの大きな配列にまとめて、データに含まれる <code class="notranslate" translate="no">min</code> と <code class="notranslate" translate="no">max</code> の値を返します。</p>
- <p>次にデータの描画コードが必要です。</p>
- <pre class="prettyprint showlinemods notranslate lang-js" translate="no">function drawData(file) {
- const {min, max, data} = file;
- const range = max - min;
- const ctx = document.querySelector('canvas').getContext('2d');
- // make the canvas the same size as the data
- ctx.canvas.width = ncols;
- ctx.canvas.height = nrows;
- // but display it double size so it's not too small
- ctx.canvas.style.width = px(ncols * 2);
- ctx.canvas.style.height = px(nrows * 2);
- // fill the canvas to dark gray
- ctx.fillStyle = '#444';
- ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
- // draw each data point
- data.forEach((row, latNdx) => {
- row.forEach((value, lonNdx) => {
- if (value === undefined) {
- return;
- }
- const amount = (value - min) / range;
- const hue = 1;
- const saturation = 1;
- const lightness = amount;
- ctx.fillStyle = hsl(hue, saturation, lightness);
- ctx.fillRect(lonNdx, latNdx, 1, 1);
- });
- });
- }
- function px(v) {
- return `${v | 0}px`;
- }
- function hsl(h, s, l) {
- return `hsl(${h * 360 | 0},${s * 100 | 0}%,${l * 100 | 0}%)`;
- }
- </pre>
- <p>最後にすべてを統合します。</p>
- <pre class="prettyprint showlinemods notranslate lang-js" translate="no">loadFile('resources/data/gpw/gpw_v4_basic_demographic_characteristics_rev10_a000_014mt_2010_cntm_1_deg.asc')
- .then(parseData)
- .then(drawData);
- </pre>
- <p>そして、以下のような結果が得られました。</p>
- <p></p><div translate="no" class="threejs_example_container notranslate">
- <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/gpw-data-viewer.html"></iframe></div>
- <a class="threejs_center" href="/manual/examples/gpw-data-viewer.html" target="_blank">ここをクリックして別のウィンドウで開きます</a>
- </div>
- <p></p>
- <p>どうやら上手くいったようです。</p>
- <p>これを3Dでやってみましょう。
- <a href="rendering-on-demand.html">要求されたレンダリング</a>のコードから始めてファイル内のデータごとに1つのボックスを作ります。</p>
- <p>まずは世界地図テクスチャで簡単な球体を作ってみましょう。テクスチャはこんな感じです。</p>
- <div class="threejs_center"><img src="../examples/resources/images/world.jpg" style="width: 600px"></div>
- <p>テクスチャをセットするコードです。</p>
- <pre class="prettyprint showlinemods notranslate lang-js" translate="no">{
- const loader = new THREE.TextureLoader();
- const texture = loader.load('resources/images/world.jpg', render);
- const geometry = new THREE.SphereGeometry(1, 64, 32);
- const material = new THREE.MeshBasicMaterial({map: texture});
- scene.add(new THREE.Mesh(geometry, material));
- }
- </pre>
- <p>テクスチャ読込後に <code class="notranslate" translate="no">render</code> を呼び出している部分に注目して下さい。
- renderが必要なのは連続的なレンダリングでなく、<a href="rendering-on-demand.html">要求されたレンダリング</a>なのでテクスチャ読込後に一度レンダリングする必要があるからです。</p>
- <p>次に上記のデータポイントごとにドット描画するコードをデータポイントごとにボックスを作成するコードに変更する必要があります。</p>
- <pre class="prettyprint showlinemods notranslate lang-js" translate="no">function addBoxes(file) {
- const {min, max, data} = file;
- const range = max - min;
- // make one box geometry
- const boxWidth = 1;
- const boxHeight = 1;
- const boxDepth = 1;
- const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth);
- // make it so it scales away from the positive Z axis
- geometry.applyMatrix4(new THREE.Matrix4().makeTranslation(0, 0, 0.5));
- // these helpers will make it easy to position the boxes
- // We can rotate the lon helper on its Y axis to the longitude
- const lonHelper = new THREE.Object3D();
- scene.add(lonHelper);
- // We rotate the latHelper on its X axis to the latitude
- const latHelper = new THREE.Object3D();
- lonHelper.add(latHelper);
- // The position helper moves the object to the edge of the sphere
- const positionHelper = new THREE.Object3D();
- positionHelper.position.z = 1;
- latHelper.add(positionHelper);
- const lonFudge = Math.PI * .5;
- const latFudge = Math.PI * -0.135;
- data.forEach((row, latNdx) => {
- row.forEach((value, lonNdx) => {
- if (value === undefined) {
- return;
- }
- const amount = (value - min) / range;
- const material = new THREE.MeshBasicMaterial();
- const hue = THREE.MathUtils.lerp(0.7, 0.3, amount);
- const saturation = 1;
- const lightness = THREE.MathUtils.lerp(0.1, 1.0, amount);
- material.color.setHSL(hue, saturation, lightness);
- const mesh = new THREE.Mesh(geometry, material);
- scene.add(mesh);
- // adjust the helpers to point to the latitude and longitude
- lonHelper.rotation.y = THREE.MathUtils.degToRad(lonNdx + file.xllcorner) + lonFudge;
- latHelper.rotation.x = THREE.MathUtils.degToRad(latNdx + file.yllcorner) + latFudge;
- // use the world matrix of the position helper to
- // position this mesh.
- positionHelper.updateWorldMatrix(true, false);
- mesh.applyMatrix4(positionHelper.matrixWorld);
- mesh.scale.set(0.005, 0.005, THREE.MathUtils.lerp(0.01, 0.5, amount));
- });
- });
- }
- </pre>
- <p>2Dドットの描画コードからほとんどの部分が単純明快なものになっています。</p>
- <p>1つのボックスを作り、ボックスの中心が正のZから離れるように調整します。これをしないと中心からのスケールになってしまうため、原点から離れるようになってほしいからです。</p>
- <div class="spread">
- <div>
- <div data-diagram="scaleCenter" style="height: 250px"></div>
- <div class="code">default</div>
- </div>
- <div>
- <div data-diagram="scalePositiveZ" style="height: 250px"></div>
- <div class="code">adjusted</div>
- </div>
- </div>
- <p><a href="scenegraph.html">シーングラフ</a>で説明したように、多くの <a href="/docs/#api/ja/core/Object3D"><code class="notranslate" translate="no">THREE.Object3D</code></a> オブジェクトでボックスを親にして解決できますが、シーングラフにノードを追加すればするほど遅くなってしまいます。</p>
- <p>また <code class="notranslate" translate="no">lonHelper</code>、<code class="notranslate" translate="no">latHelper</code>、<code class="notranslate" translate="no">positionHelper</code>という小さなノード階層を設定します。
- これらのオブジェクトを使用し、ボックスを配置する球体の周りの位置を計算します。</p>
- <div class="spread">
- <div data-diagram="lonLatPos" style="width: 600px; height: 400px;"></div>
- </div>
- <p>上記の<span style="color: green;">green bar</span>は <code class="notranslate" translate="no">lonHelper</code> と <code class="notranslate" translate="no">longHelper</code> を表し、赤道上の経度方向に回転させるために使用します。
- <span style="color: blue;">blue bar</span> は <code class="notranslate" translate="no">latHelper</code> を表し、赤道上や赤道下の緯度を回転させるために使用します。
- <span style="color: red;">red sphere</span>は <code class="notranslate" translate="no">positionHelper</code> が提供するオフセットを表します。</p>
- <p>地球儀上の位置の計算を手動で行う事もできますが、ほとんどの計算をライブラリ自体に任せてしまうので処理をする必要がありません。</p>
- <p>各データポイントに対して <a href="/docs/#api/ja/materials/MeshBasicMaterial"><code class="notranslate" translate="no">MeshBasicMaterial</code></a> と <a href="/docs/#api/ja/objects/Mesh"><code class="notranslate" translate="no">Mesh</code></a> を作成し、<code class="notranslate" translate="no">positionHelper</code> のワールド座標を求めてそれを新しい <a href="/docs/#api/ja/objects/Mesh"><code class="notranslate" translate="no">Mesh</code></a> に適用します。
- 最後にメッシュを新しい位置で拡大縮小します。</p>
- <p>上記のように新しいボックスを作成する度に <code class="notranslate" translate="no">latHelper</code>、<code class="notranslate" translate="no">lonHelper</code>、<code class="notranslate" translate="no">positionHelper</code> を作成できましたが、それではさらに時間がかかります。</p>
- <p>これから作るボックスは360 × 145まであります。最大で52000個のボックスです。
- いくつかのデータポイントが "NO_DATA "とマークされているので、実際に作成するボックスの数は約19000個です。
- 1ボックスごとに3つのヘルパーオブジェクトを追加した場合、シーングラフのノードが80000個近くになり、THREE.jsはその位置を計算しなければなりません。
- ヘルパーの1つのセットを使用して単にメッシュを使用する事で約60000回の操作を削減できます。</p>
- <p>また <code class="notranslate" translate="no">lonFudge</code> と <code class="notranslate" translate="no">latFudge</code> には注意点があります。<code class="notranslate" translate="no">lonFudge</code> はπ/2で1/4回転です。
- これは理にかなっています。テクスチャやテクスチャ座標が地球の周りの異なるオフセットから始まる事を意味しているだけです。
- 一方、<code class="notranslate" translate="no">latFudge</code>についてはなぜπ * -0.135にする必要があるのか私にはわかりません。</p>
- <p>最後に行う必要があるのはローダーの呼出です。</p>
- <pre class="prettyprint showlinemods notranslate notranslate" translate="no">loadFile('resources/data/gpw/gpw_v4_basic_demographic_characteristics_rev10_a000_014mt_2010_cntm_1_deg.asc')
- .then(parseData)
- - .then(drawData)
- + .then(addBoxes)
- + .then(render);
- </pre><p>データ読込と解析が終わったら、少なくとも一度は<a href="rendering-on-demand.html">要求されたレンダリング</a>をする必要があります。</p>
- <p></p><div translate="no" class="threejs_example_container notranslate">
- <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/lots-of-objects-slow.html"></iframe></div>
- <a class="threejs_center" href="/manual/examples/lots-of-objects-slow.html" target="_blank">ここをクリックして別のウィンドウで開きます</a>
- </div>
- <p></p>
- <p>上記のサンプルをドラッグして回転させようとすると遅い事に気づくでしょう。</p>
- <p><a href="debugging-javascript.html">devtoolsを開いて</a>FPS meterをオンにする事でFPSを確認できます。</p>
- <div class="threejs_center"><img src="../resources/images/bring-up-fps-meter.gif"></div>
- <p>私のマシンでは20fps以下のFPSが表示されています。</p>
- <div class="threejs_center"><img src="../resources/images/fps-meter.gif"></div>
- <p>FPSの遅延はあまり好ましくなく、多くの人々がさらにFPSが遅くなるマシンを持っているのではないでしょうか。最適化を検討した方がいいですね。</p>
- <p>このFPS遅延の問題解決では、全てのボックスを1つのジオメトリに統合する事ができます。
- 現在は19000個前後のボックスを描画してます。1つのジオメトリに統合する事で18999個の操作を削除する事ができます。</p>
- <p>以下はボックスを1つのジオメトリに統合する新しいコードです。</p>
- <pre class="prettyprint showlinemods notranslate lang-js" translate="no">function addBoxes(file) {
- const {min, max, data} = file;
- const range = max - min;
- - // make one box geometry
- - const boxWidth = 1;
- - const boxHeight = 1;
- - const boxDepth = 1;
- - const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth);
- - // make it so it scales away from the positive Z axis
- - geometry.applyMatrix4(new THREE.Matrix4().makeTranslation(0, 0, 0.5));
- // these helpers will make it easy to position the boxes
- // We can rotate the lon helper on its Y axis to the longitude
- const lonHelper = new THREE.Object3D();
- scene.add(lonHelper);
- // We rotate the latHelper on its X axis to the latitude
- const latHelper = new THREE.Object3D();
- lonHelper.add(latHelper);
- // The position helper moves the object to the edge of the sphere
- const positionHelper = new THREE.Object3D();
- positionHelper.position.z = 1;
- latHelper.add(positionHelper);
- + // Used to move the center of the box so it scales from the position Z axis
- + const originHelper = new THREE.Object3D();
- + originHelper.position.z = 0.5;
- + positionHelper.add(originHelper);
- const lonFudge = Math.PI * .5;
- const latFudge = Math.PI * -0.135;
- + const geometries = [];
- data.forEach((row, latNdx) => {
- row.forEach((value, lonNdx) => {
- if (value === undefined) {
- return;
- }
- const amount = (value - min) / range;
- - const material = new THREE.MeshBasicMaterial();
- - const hue = THREE.MathUtils.lerp(0.7, 0.3, amount);
- - const saturation = 1;
- - const lightness = THREE.MathUtils.lerp(0.1, 1.0, amount);
- - material.color.setHSL(hue, saturation, lightness);
- - const mesh = new THREE.Mesh(geometry, material);
- - scene.add(mesh);
- + const boxWidth = 1;
- + const boxHeight = 1;
- + const boxDepth = 1;
- + const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth);
- // adjust the helpers to point to the latitude and longitude
- lonHelper.rotation.y = THREE.MathUtils.degToRad(lonNdx + file.xllcorner) + lonFudge;
- latHelper.rotation.x = THREE.MathUtils.degToRad(latNdx + file.yllcorner) + latFudge;
- - // use the world matrix of the position helper to
- - // position this mesh.
- - positionHelper.updateWorldMatrix(true, false);
- - mesh.applyMatrix4(positionHelper.matrixWorld);
- -
- - mesh.scale.set(0.005, 0.005, THREE.MathUtils.lerp(0.01, 0.5, amount));
- + // use the world matrix of the origin helper to
- + // position this geometry
- + positionHelper.scale.set(0.005, 0.005, THREE.MathUtils.lerp(0.01, 0.5, amount));
- + originHelper.updateWorldMatrix(true, false);
- + geometry.applyMatrix4(originHelper.matrixWorld);
- +
- + geometries.push(geometry);
- });
- });
- + const mergedGeometry = BufferGeometryUtils.mergeGeometries(
- + geometries, false);
- + const material = new THREE.MeshBasicMaterial({color:'red'});
- + const mesh = new THREE.Mesh(mergedGeometry, material);
- + scene.add(mesh);
- }
- </pre>
- <p>上記ではボックスジオメトリの中心点を変更していたコードを削除し、代わりに <code class="notranslate" translate="no">originHelper</code> を追加しています。
- 前は同じジオメトリを19000回も使っていました。
- 今回は1つ1つのジオメトリを新しく作成し、各ボックスジオメトリの頂点を移動するために <code class="notranslate" translate="no">applyMatrix</code> を使用するので、2回ではなく1回にした方が良いかもしれません。</p>
- <p>最後に全てのジオメトリの配列を <code class="notranslate" translate="no">BufferGeometryUtils.mergeGeometries</code> に渡します。
- また <code class="notranslate" translate="no">BufferGeometryUtils</code> も含める必要があります。</p>
- <pre class="prettyprint showlinemods notranslate lang-js" translate="no">import * as BufferGeometryUtils from 'three/addons/utils/BufferGeometryUtils.js';
- </pre>
- <p>少なくとも私のマシンでは毎秒60フレームになりました。</p>
- <p></p><div translate="no" class="threejs_example_container notranslate">
- <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/lots-of-objects-merged.html"></iframe></div>
- <a class="threejs_center" href="/manual/examples/lots-of-objects-merged.html" target="_blank">ここをクリックして別のウィンドウで開きます</a>
- </div>
- <p></p>
- <p>これで上手くいったのですが、以前はそれぞれのボックスに異なる色がありましたが、1つのメッシュなので1つのマテリアルとなり1つの色だけになります。
- これは頂点カラーを使い修正できます。</p>
- <p>頂点カラーは頂点ごとに色を追加します。各ボックスの各頂点の全ての色を特定の色に設定する事で、全てのボックスが異なる色を持つようになります。</p>
- <pre class="prettyprint showlinemods notranslate lang-js" translate="no">+const color = new THREE.Color();
- const lonFudge = Math.PI * .5;
- const latFudge = Math.PI * -0.135;
- const geometries = [];
- data.forEach((row, latNdx) => {
- row.forEach((value, lonNdx) => {
- if (value === undefined) {
- return;
- }
- const amount = (value - min) / range;
- const boxWidth = 1;
- const boxHeight = 1;
- const boxDepth = 1;
- const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth);
- // adjust the helpers to point to the latitude and longitude
- lonHelper.rotation.y = THREE.MathUtils.degToRad(lonNdx + file.xllcorner) + lonFudge;
- latHelper.rotation.x = THREE.MathUtils.degToRad(latNdx + file.yllcorner) + latFudge;
- // use the world matrix of the origin helper to
- // position this geometry
- positionHelper.scale.set(0.005, 0.005, THREE.MathUtils.lerp(0.01, 0.5, amount));
- originHelper.updateWorldMatrix(true, false);
- geometry.applyMatrix4(originHelper.matrixWorld);
- + // compute a color
- + const hue = THREE.MathUtils.lerp(0.7, 0.3, amount);
- + const saturation = 1;
- + const lightness = THREE.MathUtils.lerp(0.4, 1.0, amount);
- + color.setHSL(hue, saturation, lightness);
- + // get the colors as an array of values from 0 to 255
- + const rgb = color.toArray().map(v => v * 255);
- +
- + // make an array to store colors for each vertex
- + const numVerts = geometry.getAttribute('position').count;
- + const itemSize = 3; // r, g, b
- + const colors = new Uint8Array(itemSize * numVerts);
- +
- + // copy the color into the colors array for each vertex
- + colors.forEach((v, ndx) => {
- + colors[ndx] = rgb[ndx % 3];
- + });
- +
- + const normalized = true;
- + const colorAttrib = new THREE.BufferAttribute(colors, itemSize, normalized);
- + geometry.setAttribute('color', colorAttrib);
- geometries.push(geometry);
- });
- });
- </pre>
- <p>上記のコードではジオメトリから <code class="notranslate" translate="no">position</code> を取得して必要な頂点の数を調べています。
- 次に色を入れるための変数を <code class="notranslate" translate="no">Uint8Array</code> で作成します。その後に <code class="notranslate" translate="no">geometry.setAttribute</code> を呼び出して属性として追加します。</p>
- <p>最後に頂点カラーを扱うようにthree.jsで指定する必要があります。</p>
- <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const mergedGeometry = BufferGeometryUtils.mergeGeometries(
- geometries, false);
- -const material = new THREE.MeshBasicMaterial({color:'red'});
- +const material = new THREE.MeshBasicMaterial({
- + vertexColors: true,
- +});
- const mesh = new THREE.Mesh(mergedGeometry, material);
- scene.add(mesh);
- </pre>
- <p>これで色を取り戻す事ができました。</p>
- <p></p><div translate="no" class="threejs_example_container notranslate">
- <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/lots-of-objects-merged-vertexcolors.html"></iframe></div>
- <a class="threejs_center" href="/manual/examples/lots-of-objects-merged-vertexcolors.html" target="_blank">ここをクリックして別のウィンドウで開きます</a>
- </div>
- <p></p>
- <p>ジオメトリのマージは一般的な最適化手法です。
- 例えば100本の木を1つのジオメトリに統合したり、個々の岩の山を1つの岩のジオメトリに統合したり、個々の杭から1つの柵メッシュに統合したりする事ができます。
- 別の例としてマインクラフトではそれぞれのキューブを個別に描画するのではなく、マージされたキューブのグループを作成したり描画されない面は選択的に削除したりします。</p>
- <p>全てを1つのメッシュにする問題点としては、以前は分離されていた部分を移動する事が容易ではなくなった事です。
- ユースケースに応じて創造的なソリューションがあります。
- 1つは<a href="optimize-lots-of-objects-animated.html">別の記事</a>で紹介します。</p>
- <p><canvas id="c"></canvas></p>
- <script type="module" src="../resources/threejs-lots-of-objects.js"></script>
- </div>
- </div>
- </div>
- <script src="../resources/prettify.js"></script>
- <script src="../resources/lesson.js"></script>
- </body></html>
|