optimize-lots-of-objects.html 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  1. <!DOCTYPE html><html lang="ja"><head>
  2. <meta charset="utf-8">
  3. <title>で多くのオブジェクトを最適化</title>
  4. <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
  5. <meta name="twitter:card" content="summary_large_image">
  6. <meta name="twitter:site" content="@threejs">
  7. <meta name="twitter:title" content="Three.js – で多くのオブジェクトを最適化">
  8. <meta property="og:image" content="https://threejs.org/files/share.png">
  9. <link rel="shortcut icon" href="../../files/favicon_white.ico" media="(prefers-color-scheme: dark)">
  10. <link rel="shortcut icon" href="../../files/favicon.ico" media="(prefers-color-scheme: light)">
  11. <link rel="stylesheet" href="../resources/lesson.css">
  12. <link rel="stylesheet" href="../resources/lang.css">
  13. <!-- Import maps polyfill -->
  14. <!-- Remove this when import maps will be widely supported -->
  15. <script async src="https://unpkg.com/[email protected]/dist/es-module-shims.js"></script>
  16. <script type="importmap">
  17. {
  18. "imports": {
  19. "three": "../../build/three.module.js"
  20. }
  21. }
  22. </script>
  23. </head>
  24. <body>
  25. <div class="container">
  26. <div class="lesson-title">
  27. <h1>で多くのオブジェクトを最適化</h1>
  28. </div>
  29. <div class="lesson">
  30. <div class="lesson-main">
  31. <p>この記事はthree.jsの連載記事の1つです。最初の記事は<a href="fundamentals.html">Three.jsの基礎知識</a>です。まだ読んでいない場合はそこから始めて下さい。</p>
  32. <p>three.jsには最適化する方法は多々あります。1つの方法は<em>ジオメトリのマージ</em>と呼ばれています。メッシュを作成すると描画リクエストを1つ以上行った事を表します。
  33. 2つのメッシュを描画すると結果が同じでも1つのメッシュを描画するよりもオーバーヘッドが大きく、最適化する1つの方法がメッシュのマージです。</p>
  34. <p>これが問題解決になるか、例を示してみます。
  35. <a href="https://globe.chromeexperiments.com/">WebGL Globe</a>を作り直してみましょう。</p>
  36. <p>まずデータが必要です。WebGL Globeで使用しているデータは<a href="http://sedac.ciesin.columbia.edu/gpw/">SEDAC</a>です。
  37. サイトをチェックすると<a href="https://beta.sedac.ciesin.columbia.edu/data/set/gpw-v4-basic-demographic-characteristics-rev10">人口統計データのグリッド形式</a>があります。
  38. 私は60分間の解像度データをダウンロードしました。データを見てみると以下のような感じになっています。</p>
  39. <pre class="prettyprint showlinemods notranslate lang-txt" translate="no"> ncols 360
  40. nrows 145
  41. xllcorner -180
  42. yllcorner -60
  43. cellsize 0.99999999999994
  44. NODATA_value -9999
  45. -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 ...
  46. -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 ...
  47. -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 ...
  48. -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 ...
  49. -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 ...
  50. -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 ...
  51. -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 ...
  52. -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 ...
  53. -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 ...
  54. -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 ...
  55. -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 ...
  56. -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 ...
  57. -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 ...
  58. 9.241768 8.790958 2.095345 -9999 0.05114867 -9999 -9999 -9999 -9999 -999...
  59. 1.287993 0.4395509 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999...
  60. -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 ...
  61. </pre>
  62. <p>キーと値のペアのような行がいくつかあり、その行に続くグリッドポイントごとの値の行があり、データポイントごとに1行ずつ並んでいます。
  63. データをもっと理解するために2Dでプロットしてみましょう。</p>
  64. <p>最初にテキストファイルをロードするコードです。</p>
  65. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">async function loadFile(url) {
  66. const res = await fetch(url);
  67. return res.text();
  68. }
  69. </pre>
  70. <p>上記のコードは <code class="notranslate" translate="no">Promise</code> を返しファイルの内容は <code class="notranslate" translate="no">url</code> にあります。
  71. 次にファイルを解析するコードが必要です。</p>
  72. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">function parseData(text) {
  73. const data = [];
  74. const settings = {data};
  75. let max;
  76. let min;
  77. // split into lines
  78. text.split('\n').forEach((line) =&gt; {
  79. // split the line by whitespace
  80. const parts = line.trim().split(/\s+/);
  81. if (parts.length === 2) {
  82. // only 2 parts, must be a key/value pair
  83. settings[parts[0]] = parseFloat(parts[1]);
  84. } else if (parts.length &gt; 2) {
  85. // more than 2 parts, must be data
  86. const values = parts.map((v) =&gt; {
  87. const value = parseFloat(v);
  88. if (value === settings.NODATA_value) {
  89. return undefined;
  90. }
  91. max = Math.max(max === undefined ? value : max, value);
  92. min = Math.min(min === undefined ? value : min, value);
  93. return value;
  94. });
  95. data.push(values);
  96. }
  97. });
  98. return Object.assign(settings, {min, max});
  99. }
  100. </pre>
  101. <p>上記のコードはファイルから全てのキーと値のペアを持つオブジェクトを返します。また<code class="notranslate" translate="no">data</code> プロパティには全てのデータを1つの大きな配列にまとめて、データに含まれる <code class="notranslate" translate="no">min</code> と <code class="notranslate" translate="no">max</code> の値を返します。</p>
  102. <p>次にデータの描画コードが必要です。</p>
  103. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">function drawData(file) {
  104. const {min, max, data} = file;
  105. const range = max - min;
  106. const ctx = document.querySelector('canvas').getContext('2d');
  107. // make the canvas the same size as the data
  108. ctx.canvas.width = ncols;
  109. ctx.canvas.height = nrows;
  110. // but display it double size so it's not too small
  111. ctx.canvas.style.width = px(ncols * 2);
  112. ctx.canvas.style.height = px(nrows * 2);
  113. // fill the canvas to dark gray
  114. ctx.fillStyle = '#444';
  115. ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
  116. // draw each data point
  117. data.forEach((row, latNdx) =&gt; {
  118. row.forEach((value, lonNdx) =&gt; {
  119. if (value === undefined) {
  120. return;
  121. }
  122. const amount = (value - min) / range;
  123. const hue = 1;
  124. const saturation = 1;
  125. const lightness = amount;
  126. ctx.fillStyle = hsl(hue, saturation, lightness);
  127. ctx.fillRect(lonNdx, latNdx, 1, 1);
  128. });
  129. });
  130. }
  131. function px(v) {
  132. return `${v | 0}px`;
  133. }
  134. function hsl(h, s, l) {
  135. return `hsl(${h * 360 | 0},${s * 100 | 0}%,${l * 100 | 0}%)`;
  136. }
  137. </pre>
  138. <p>最後にすべてを統合します。</p>
  139. <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')
  140. .then(parseData)
  141. .then(drawData);
  142. </pre>
  143. <p>そして、以下のような結果が得られました。</p>
  144. <p></p><div translate="no" class="threejs_example_container notranslate">
  145. <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/gpw-data-viewer.html"></iframe></div>
  146. <a class="threejs_center" href="/manual/examples/gpw-data-viewer.html" target="_blank">ここをクリックして別のウィンドウで開きます</a>
  147. </div>
  148. <p></p>
  149. <p>どうやら上手くいったようです。</p>
  150. <p>これを3Dでやってみましょう。
  151. <a href="rendering-on-demand.html">要求されたレンダリング</a>のコードから始めてファイル内のデータごとに1つのボックスを作ります。</p>
  152. <p>まずは世界地図テクスチャで簡単な球体を作ってみましょう。テクスチャはこんな感じです。</p>
  153. <div class="threejs_center"><img src="../examples/resources/images/world.jpg" style="width: 600px"></div>
  154. <p>テクスチャをセットするコードです。</p>
  155. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">{
  156. const loader = new THREE.TextureLoader();
  157. const texture = loader.load('resources/images/world.jpg', render);
  158. const geometry = new THREE.SphereGeometry(1, 64, 32);
  159. const material = new THREE.MeshBasicMaterial({map: texture});
  160. scene.add(new THREE.Mesh(geometry, material));
  161. }
  162. </pre>
  163. <p>テクスチャ読込後に <code class="notranslate" translate="no">render</code> を呼び出している部分に注目して下さい。
  164. renderが必要なのは連続的なレンダリングでなく、<a href="rendering-on-demand.html">要求されたレンダリング</a>なのでテクスチャ読込後に一度レンダリングする必要があるからです。</p>
  165. <p>次に上記のデータポイントごとにドット描画するコードをデータポイントごとにボックスを作成するコードに変更する必要があります。</p>
  166. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">function addBoxes(file) {
  167. const {min, max, data} = file;
  168. const range = max - min;
  169. // make one box geometry
  170. const boxWidth = 1;
  171. const boxHeight = 1;
  172. const boxDepth = 1;
  173. const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth);
  174. // make it so it scales away from the positive Z axis
  175. geometry.applyMatrix4(new THREE.Matrix4().makeTranslation(0, 0, 0.5));
  176. // these helpers will make it easy to position the boxes
  177. // We can rotate the lon helper on its Y axis to the longitude
  178. const lonHelper = new THREE.Object3D();
  179. scene.add(lonHelper);
  180. // We rotate the latHelper on its X axis to the latitude
  181. const latHelper = new THREE.Object3D();
  182. lonHelper.add(latHelper);
  183. // The position helper moves the object to the edge of the sphere
  184. const positionHelper = new THREE.Object3D();
  185. positionHelper.position.z = 1;
  186. latHelper.add(positionHelper);
  187. const lonFudge = Math.PI * .5;
  188. const latFudge = Math.PI * -0.135;
  189. data.forEach((row, latNdx) =&gt; {
  190. row.forEach((value, lonNdx) =&gt; {
  191. if (value === undefined) {
  192. return;
  193. }
  194. const amount = (value - min) / range;
  195. const material = new THREE.MeshBasicMaterial();
  196. const hue = THREE.MathUtils.lerp(0.7, 0.3, amount);
  197. const saturation = 1;
  198. const lightness = THREE.MathUtils.lerp(0.1, 1.0, amount);
  199. material.color.setHSL(hue, saturation, lightness);
  200. const mesh = new THREE.Mesh(geometry, material);
  201. scene.add(mesh);
  202. // adjust the helpers to point to the latitude and longitude
  203. lonHelper.rotation.y = THREE.MathUtils.degToRad(lonNdx + file.xllcorner) + lonFudge;
  204. latHelper.rotation.x = THREE.MathUtils.degToRad(latNdx + file.yllcorner) + latFudge;
  205. // use the world matrix of the position helper to
  206. // position this mesh.
  207. positionHelper.updateWorldMatrix(true, false);
  208. mesh.applyMatrix4(positionHelper.matrixWorld);
  209. mesh.scale.set(0.005, 0.005, THREE.MathUtils.lerp(0.01, 0.5, amount));
  210. });
  211. });
  212. }
  213. </pre>
  214. <p>2Dドットの描画コードからほとんどの部分が単純明快なものになっています。</p>
  215. <p>1つのボックスを作り、ボックスの中心が正のZから離れるように調整します。これをしないと中心からのスケールになってしまうため、原点から離れるようになってほしいからです。</p>
  216. <div class="spread">
  217. <div>
  218. <div data-diagram="scaleCenter" style="height: 250px"></div>
  219. <div class="code">default</div>
  220. </div>
  221. <div>
  222. <div data-diagram="scalePositiveZ" style="height: 250px"></div>
  223. <div class="code">adjusted</div>
  224. </div>
  225. </div>
  226. <p><a href="scenegraph.html">シーングラフ</a>で説明したように、多くの <a href="/docs/#api/ja/core/Object3D"><code class="notranslate" translate="no">THREE.Object3D</code></a> オブジェクトでボックスを親にして解決できますが、シーングラフにノードを追加すればするほど遅くなってしまいます。</p>
  227. <p>また <code class="notranslate" translate="no">lonHelper</code>、<code class="notranslate" translate="no">latHelper</code>、<code class="notranslate" translate="no">positionHelper</code>という小さなノード階層を設定します。
  228. これらのオブジェクトを使用し、ボックスを配置する球体の周りの位置を計算します。</p>
  229. <div class="spread">
  230. <div data-diagram="lonLatPos" style="width: 600px; height: 400px;"></div>
  231. </div>
  232. <p>上記の<span style="color: green;">green bar</span>は <code class="notranslate" translate="no">lonHelper</code> と <code class="notranslate" translate="no">longHelper</code> を表し、赤道上の経度方向に回転させるために使用します。
  233. <span style="color: blue;">blue bar</span> は <code class="notranslate" translate="no">latHelper</code> を表し、赤道上や赤道下の緯度を回転させるために使用します。
  234. <span style="color: red;">red sphere</span>は <code class="notranslate" translate="no">positionHelper</code> が提供するオフセットを表します。</p>
  235. <p>地球儀上の位置の計算を手動で行う事もできますが、ほとんどの計算をライブラリ自体に任せてしまうので処理をする必要がありません。</p>
  236. <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> に適用します。
  237. 最後にメッシュを新しい位置で拡大縮小します。</p>
  238. <p>上記のように新しいボックスを作成する度に <code class="notranslate" translate="no">latHelper</code>、<code class="notranslate" translate="no">lonHelper</code>、<code class="notranslate" translate="no">positionHelper</code> を作成できましたが、それではさらに時間がかかります。</p>
  239. <p>これから作るボックスは360 × 145まであります。最大で52000個のボックスです。
  240. いくつかのデータポイントが "NO_DATA "とマークされているので、実際に作成するボックスの数は約19000個です。
  241. 1ボックスごとに3つのヘルパーオブジェクトを追加した場合、シーングラフのノードが80000個近くになり、THREE.jsはその位置を計算しなければなりません。
  242. ヘルパーの1つのセットを使用して単にメッシュを使用する事で約60000回の操作を削減できます。</p>
  243. <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回転です。
  244. これは理にかなっています。テクスチャやテクスチャ座標が地球の周りの異なるオフセットから始まる事を意味しているだけです。
  245. 一方、<code class="notranslate" translate="no">latFudge</code>についてはなぜπ * -0.135にする必要があるのか私にはわかりません。</p>
  246. <p>最後に行う必要があるのはローダーの呼出です。</p>
  247. <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')
  248. .then(parseData)
  249. - .then(drawData)
  250. + .then(addBoxes)
  251. + .then(render);
  252. </pre><p>データ読込と解析が終わったら、少なくとも一度は<a href="rendering-on-demand.html">要求されたレンダリング</a>をする必要があります。</p>
  253. <p></p><div translate="no" class="threejs_example_container notranslate">
  254. <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>
  255. <a class="threejs_center" href="/manual/examples/lots-of-objects-slow.html" target="_blank">ここをクリックして別のウィンドウで開きます</a>
  256. </div>
  257. <p></p>
  258. <p>上記のサンプルをドラッグして回転させようとすると遅い事に気づくでしょう。</p>
  259. <p><a href="debugging-javascript.html">devtoolsを開いて</a>FPS meterをオンにする事でFPSを確認できます。</p>
  260. <div class="threejs_center"><img src="../resources/images/bring-up-fps-meter.gif"></div>
  261. <p>私のマシンでは20fps以下のFPSが表示されています。</p>
  262. <div class="threejs_center"><img src="../resources/images/fps-meter.gif"></div>
  263. <p>FPSの遅延はあまり好ましくなく、多くの人々がさらにFPSが遅くなるマシンを持っているのではないでしょうか。最適化を検討した方がいいですね。</p>
  264. <p>このFPS遅延の問題解決では、全てのボックスを1つのジオメトリに統合する事ができます。
  265. 現在は19000個前後のボックスを描画してます。1つのジオメトリに統合する事で18999個の操作を削除する事ができます。</p>
  266. <p>以下はボックスを1つのジオメトリに統合する新しいコードです。</p>
  267. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">function addBoxes(file) {
  268. const {min, max, data} = file;
  269. const range = max - min;
  270. - // make one box geometry
  271. - const boxWidth = 1;
  272. - const boxHeight = 1;
  273. - const boxDepth = 1;
  274. - const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth);
  275. - // make it so it scales away from the positive Z axis
  276. - geometry.applyMatrix4(new THREE.Matrix4().makeTranslation(0, 0, 0.5));
  277. // these helpers will make it easy to position the boxes
  278. // We can rotate the lon helper on its Y axis to the longitude
  279. const lonHelper = new THREE.Object3D();
  280. scene.add(lonHelper);
  281. // We rotate the latHelper on its X axis to the latitude
  282. const latHelper = new THREE.Object3D();
  283. lonHelper.add(latHelper);
  284. // The position helper moves the object to the edge of the sphere
  285. const positionHelper = new THREE.Object3D();
  286. positionHelper.position.z = 1;
  287. latHelper.add(positionHelper);
  288. + // Used to move the center of the box so it scales from the position Z axis
  289. + const originHelper = new THREE.Object3D();
  290. + originHelper.position.z = 0.5;
  291. + positionHelper.add(originHelper);
  292. const lonFudge = Math.PI * .5;
  293. const latFudge = Math.PI * -0.135;
  294. + const geometries = [];
  295. data.forEach((row, latNdx) =&gt; {
  296. row.forEach((value, lonNdx) =&gt; {
  297. if (value === undefined) {
  298. return;
  299. }
  300. const amount = (value - min) / range;
  301. - const material = new THREE.MeshBasicMaterial();
  302. - const hue = THREE.MathUtils.lerp(0.7, 0.3, amount);
  303. - const saturation = 1;
  304. - const lightness = THREE.MathUtils.lerp(0.1, 1.0, amount);
  305. - material.color.setHSL(hue, saturation, lightness);
  306. - const mesh = new THREE.Mesh(geometry, material);
  307. - scene.add(mesh);
  308. + const boxWidth = 1;
  309. + const boxHeight = 1;
  310. + const boxDepth = 1;
  311. + const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth);
  312. // adjust the helpers to point to the latitude and longitude
  313. lonHelper.rotation.y = THREE.MathUtils.degToRad(lonNdx + file.xllcorner) + lonFudge;
  314. latHelper.rotation.x = THREE.MathUtils.degToRad(latNdx + file.yllcorner) + latFudge;
  315. - // use the world matrix of the position helper to
  316. - // position this mesh.
  317. - positionHelper.updateWorldMatrix(true, false);
  318. - mesh.applyMatrix4(positionHelper.matrixWorld);
  319. -
  320. - mesh.scale.set(0.005, 0.005, THREE.MathUtils.lerp(0.01, 0.5, amount));
  321. + // use the world matrix of the origin helper to
  322. + // position this geometry
  323. + positionHelper.scale.set(0.005, 0.005, THREE.MathUtils.lerp(0.01, 0.5, amount));
  324. + originHelper.updateWorldMatrix(true, false);
  325. + geometry.applyMatrix4(originHelper.matrixWorld);
  326. +
  327. + geometries.push(geometry);
  328. });
  329. });
  330. + const mergedGeometry = BufferGeometryUtils.mergeGeometries(
  331. + geometries, false);
  332. + const material = new THREE.MeshBasicMaterial({color:'red'});
  333. + const mesh = new THREE.Mesh(mergedGeometry, material);
  334. + scene.add(mesh);
  335. }
  336. </pre>
  337. <p>上記ではボックスジオメトリの中心点を変更していたコードを削除し、代わりに <code class="notranslate" translate="no">originHelper</code> を追加しています。
  338. 前は同じジオメトリを19000回も使っていました。
  339. 今回は1つ1つのジオメトリを新しく作成し、各ボックスジオメトリの頂点を移動するために <code class="notranslate" translate="no">applyMatrix</code> を使用するので、2回ではなく1回にした方が良いかもしれません。</p>
  340. <p>最後に全てのジオメトリの配列を <code class="notranslate" translate="no">BufferGeometryUtils.mergeGeometries</code> に渡します。
  341. また <code class="notranslate" translate="no">BufferGeometryUtils</code> も含める必要があります。</p>
  342. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">import * as BufferGeometryUtils from 'three/addons/utils/BufferGeometryUtils.js';
  343. </pre>
  344. <p>少なくとも私のマシンでは毎秒60フレームになりました。</p>
  345. <p></p><div translate="no" class="threejs_example_container notranslate">
  346. <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>
  347. <a class="threejs_center" href="/manual/examples/lots-of-objects-merged.html" target="_blank">ここをクリックして別のウィンドウで開きます</a>
  348. </div>
  349. <p></p>
  350. <p>これで上手くいったのですが、以前はそれぞれのボックスに異なる色がありましたが、1つのメッシュなので1つのマテリアルとなり1つの色だけになります。
  351. これは頂点カラーを使い修正できます。</p>
  352. <p>頂点カラーは頂点ごとに色を追加します。各ボックスの各頂点の全ての色を特定の色に設定する事で、全てのボックスが異なる色を持つようになります。</p>
  353. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">+const color = new THREE.Color();
  354. const lonFudge = Math.PI * .5;
  355. const latFudge = Math.PI * -0.135;
  356. const geometries = [];
  357. data.forEach((row, latNdx) =&gt; {
  358. row.forEach((value, lonNdx) =&gt; {
  359. if (value === undefined) {
  360. return;
  361. }
  362. const amount = (value - min) / range;
  363. const boxWidth = 1;
  364. const boxHeight = 1;
  365. const boxDepth = 1;
  366. const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth);
  367. // adjust the helpers to point to the latitude and longitude
  368. lonHelper.rotation.y = THREE.MathUtils.degToRad(lonNdx + file.xllcorner) + lonFudge;
  369. latHelper.rotation.x = THREE.MathUtils.degToRad(latNdx + file.yllcorner) + latFudge;
  370. // use the world matrix of the origin helper to
  371. // position this geometry
  372. positionHelper.scale.set(0.005, 0.005, THREE.MathUtils.lerp(0.01, 0.5, amount));
  373. originHelper.updateWorldMatrix(true, false);
  374. geometry.applyMatrix4(originHelper.matrixWorld);
  375. + // compute a color
  376. + const hue = THREE.MathUtils.lerp(0.7, 0.3, amount);
  377. + const saturation = 1;
  378. + const lightness = THREE.MathUtils.lerp(0.4, 1.0, amount);
  379. + color.setHSL(hue, saturation, lightness);
  380. + // get the colors as an array of values from 0 to 255
  381. + const rgb = color.toArray().map(v =&gt; v * 255);
  382. +
  383. + // make an array to store colors for each vertex
  384. + const numVerts = geometry.getAttribute('position').count;
  385. + const itemSize = 3; // r, g, b
  386. + const colors = new Uint8Array(itemSize * numVerts);
  387. +
  388. + // copy the color into the colors array for each vertex
  389. + colors.forEach((v, ndx) =&gt; {
  390. + colors[ndx] = rgb[ndx % 3];
  391. + });
  392. +
  393. + const normalized = true;
  394. + const colorAttrib = new THREE.BufferAttribute(colors, itemSize, normalized);
  395. + geometry.setAttribute('color', colorAttrib);
  396. geometries.push(geometry);
  397. });
  398. });
  399. </pre>
  400. <p>上記のコードではジオメトリから <code class="notranslate" translate="no">position</code> を取得して必要な頂点の数を調べています。
  401. 次に色を入れるための変数を <code class="notranslate" translate="no">Uint8Array</code> で作成します。その後に <code class="notranslate" translate="no">geometry.setAttribute</code> を呼び出して属性として追加します。</p>
  402. <p>最後に頂点カラーを扱うようにthree.jsで指定する必要があります。</p>
  403. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const mergedGeometry = BufferGeometryUtils.mergeGeometries(
  404. geometries, false);
  405. -const material = new THREE.MeshBasicMaterial({color:'red'});
  406. +const material = new THREE.MeshBasicMaterial({
  407. + vertexColors: true,
  408. +});
  409. const mesh = new THREE.Mesh(mergedGeometry, material);
  410. scene.add(mesh);
  411. </pre>
  412. <p>これで色を取り戻す事ができました。</p>
  413. <p></p><div translate="no" class="threejs_example_container notranslate">
  414. <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>
  415. <a class="threejs_center" href="/manual/examples/lots-of-objects-merged-vertexcolors.html" target="_blank">ここをクリックして別のウィンドウで開きます</a>
  416. </div>
  417. <p></p>
  418. <p>ジオメトリのマージは一般的な最適化手法です。
  419. 例えば100本の木を1つのジオメトリに統合したり、個々の岩の山を1つの岩のジオメトリに統合したり、個々の杭から1つの柵メッシュに統合したりする事ができます。
  420. 別の例としてマインクラフトではそれぞれのキューブを個別に描画するのではなく、マージされたキューブのグループを作成したり描画されない面は選択的に削除したりします。</p>
  421. <p>全てを1つのメッシュにする問題点としては、以前は分離されていた部分を移動する事が容易ではなくなった事です。
  422. ユースケースに応じて創造的なソリューションがあります。
  423. 1つは<a href="optimize-lots-of-objects-animated.html">別の記事</a>で紹介します。</p>
  424. <p><canvas id="c"></canvas></p>
  425. <script type="module" src="../resources/threejs-lots-of-objects.js"></script>
  426. </div>
  427. </div>
  428. </div>
  429. <script src="../resources/prettify.js"></script>
  430. <script src="../resources/lesson.js"></script>
  431. </body></html>