optimize-lots-of-objects.html 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. <!DOCTYPE html><html lang="ko"><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. <link rel="stylesheet" href="/manual/ko/lang.css">
  24. </head>
  25. <body>
  26. <div class="container">
  27. <div class="lesson-title">
  28. <h1>다중 요소 렌더링 최적화하기</h1>
  29. </div>
  30. <div class="lesson">
  31. <div class="lesson-main">
  32. <p>※ 이 글은 Three.js의 튜토리얼 시리즈로서,
  33. 먼저 <a href="fundamentals.html">Three.js의 기본 구조에 관한 글</a>을
  34. 읽고 오길 권장합니다.</p>
  35. <p>Three.js에서 요소를 최적화하는 방법은 아주 다양합니다. 가장 많이 언급되는 방법은 <em>geometry를 합치는 것</em>이죠. Three.js는 사용자가 <a href="/docs/#api/ko/objects/Mesh"><code class="notranslate" translate="no">Mesh</code></a>를 하나 만들 때마다 매번 시스템에 하나 이상의 렌더링 요청을 보냅니다. 결과물이 완벽히 같더라도 mesh를 1개를 렌더링할 때보다 2개를 렌더링할 때 <a href="https://ko.wikipedia.org/wiki/%EC%98%A4%EB%B2%84%ED%97%A4%EB%93%9C">오버헤드(overhead)</a>가 더 많이 발생한다는 이야기죠. 그러니 이 mesh를 하나로 합친다면 오버헤드를 줄일 수 있습니다.</p>
  36. <p>간단한 예제를 통해 이 방법이 어떤 경우 적합한지 알아보도록 하겠습니다. <a href="https://globe.chromeexperiments.com/">WebGL 지구본</a>을 베껴 직접 구현해보겠습니다.</p>
  37. <p>먼저 데이터를 작성합니다. WebGL 지구본 개발진은 <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>가 있네요. resolution 값을 60 minute으로 설정해 데이터를 다운로드합니다.</p>
  38. <p>받은 데이터는 아래와 같습니다.</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>키/값 쌍 데이터가 몇 줄 있고 나머지는 격자점(grid point) 데이터네요. 데이터의 한 줄은 각 좌표에 대한 데이터입니다.</p>
  63. <p>이해를 돕기 위해 데이터를 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">url</code>의 파일 내용을 반환하는 <code class="notranslate" translate="no">Promise</code>를 반환합니다.</p>
  71. <p>※참고: <a href="https://developer.mozilla.org/ko/docs/Web/API/Fetch_API">fetch API</a>. 역주.</p>
  72. <p>다음으로 텍스트 데이터를 파싱하는 함수를 작성합니다.</p>
  73. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">function parseData(text) {
  74. const data = [];
  75. const settings = { data };
  76. let max;
  77. let min;
  78. // 각 줄을 쪼갭니다.
  79. text.split('\n').forEach((line) =&gt; {
  80. // 해당 줄을 공백을 기준으로 쪼갭니다.
  81. const parts = line.trim().split(/\s+/);
  82. if (parts.length === 2) {
  83. // 2개로 나눠졌다면 키/값 쌍 데이터입니다.
  84. settings[parts[0]] = parseFloat(parts[1]);
  85. } else if (parts.length &gt; 2) {
  86. // 2개보다 많다면 좌표 데이터입니다.
  87. const values = parts.map((v) =&gt; {
  88. const value = parseFloat(v);
  89. if (value === settings.NODATA_value) {
  90. return undefined;
  91. }
  92. max = Math.max(max === undefined ? value : max, value);
  93. min = Math.min(min === undefined ? value : min, value);
  94. return value;
  95. });
  96. data.push(values);
  97. }
  98. });
  99. return Object.assign(settings, { min, max });
  100. }
  101. </pre>
  102. <p>위 함수는 데이터 파일의 키/값 쌍, 좌표 데이터를 하나의 배열 만든 <code class="notranslate" translate="no">data</code> 속성, 그리고 좌표 데이터를 기반으로 한 <code class="notranslate" translate="no">min</code>, <code class="notranslate" translate="no">max</code> 속성을 가진 객체를 반환합니다.</p>
  103. <p>그리고 데이터를 렌더링하는 코드를 작성합니다.</p>
  104. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">function drawData(file) {
  105. const { min, max, data } = file;
  106. const range = max - min;
  107. const ctx = document.querySelector('canvas').getContext('2d');
  108. // 데이터와 같은 크기로 캔버스 해상도를 맞춥니다.
  109. ctx.canvas.width = ncols;
  110. ctx.canvas.height = nrows;
  111. // 캔버스 요소의 크기를 두 배로 지정해 너무 작게 보이지 않도록 합니다.
  112. ctx.canvas.style.width = px(ncols * 2);
  113. ctx.canvas.style.height = px(nrows * 2);
  114. // 배경을 짙은 회색으로 채웁니다.
  115. ctx.fillStyle = '#444';
  116. ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
  117. // 각 좌표에 점을 그립니다.
  118. data.forEach((row, latNdx) =&gt; {
  119. row.forEach((value, lonNdx) =&gt; {
  120. if (value === undefined) {
  121. return;
  122. }
  123. const amount = (value - min) / range;
  124. const hue = 1;
  125. const saturation = 1;
  126. const lightness = amount;
  127. ctx.fillStyle = hsl(hue, saturation, lightness);
  128. ctx.fillRect(lonNdx, latNdx, 1, 1);
  129. });
  130. });
  131. }
  132. function px(v) {
  133. return `${ v | 0 }px`;
  134. }
  135. function hsl(h, s, l) {
  136. return `hsl(${ h * 360 | 0 },${ s * 100 | 0 }%,${ l * 100 | 0 }%)`;
  137. }
  138. </pre>
  139. <p>작성한 함수를 순서대로 실행하면 끝입니다.</p>
  140. <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')
  141. .then(parseData)
  142. .then(drawData);
  143. </pre>
  144. <p>결과를 볼까요?</p>
  145. <p></p><div translate="no" class="threejs_example_container notranslate">
  146. <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/gpw-data-viewer.html"></iframe></div>
  147. <a class="threejs_center" href="/manual/examples/gpw-data-viewer.html" target="_blank">새 탭에서 보기</a>
  148. </div>
  149. <p></p>
  150. <p>데이터가 잘 렌더링된 것 같네요.</p>
  151. <p>이제 이걸 3D로 만들어봅시다. <a href="rendering-on-demand.html">불필요한 렌더링 제거하기</a>에서 썼던 예제를 가져와 각 데이터마다 육면체를 하나씩 만들 겁니다.</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> 함수를 호출하게 했습니다. 화면을 반복해서 렌더링하지 않고 <a href="rendering-on-demand.html">필요할 때만 렌더링</a>하므로, 텍스처를 불러온 뒤 다시 한 번 렌더링해야 합니다.</p>
  164. <p>다음으로 데이터를 하나의 점으로 표시하는 대신 좌표 데이터마다 육면체를 하나씩 생성합니다.</p>
  165. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">function addBoxes(file) {
  166. const { min, max, data } = file;
  167. const range = max - min;
  168. // 육면체 geometry를 만듭니다.
  169. const boxWidth = 1;
  170. const boxHeight = 1;
  171. const boxDepth = 1;
  172. const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth);
  173. // 중심이 아닌 양의 z축 방향으로 커지게끔 만듭니다.
  174. geometry.applyMatrix4(new THREE.Matrix4().makeTranslation(0, 0, 0.5));
  175. // 아래 헬퍼 Object3D는 육면체들의 위치 변화를 간단하게 만들어줍니다.
  176. // lonHelper를 Y축으로 돌려 경도(longitude)를 맞출 수 있습니다.
  177. const lonHelper = new THREE.Object3D();
  178. scene.add(lonHelper);
  179. // latHelper를 X축으로 돌려 위도(latitude)를 맞출 수 있습니다.
  180. const latHelper = new THREE.Object3D();
  181. lonHelper.add(latHelper);
  182. // positionHelper는 다른 요소의 기준축을 구체의 끝에 맞추는 역할을 합니다.
  183. const positionHelper = new THREE.Object3D();
  184. positionHelper.position.z = 1;
  185. latHelper.add(positionHelper);
  186. const lonFudge = Math.PI * .5;
  187. const latFudge = Math.PI * -0.135;
  188. data.forEach((row, latNdx) =&gt; {
  189. row.forEach((value, lonNdx) =&gt; {
  190. if (value === undefined) {
  191. return;
  192. }
  193. const amount = (value - min) / range;
  194. const material = new THREE.MeshBasicMaterial();
  195. const hue = THREE.MathUtils.lerp(0.7, 0.3, amount);
  196. const saturation = 1;
  197. const lightness = THREE.MathUtils.lerp(0.1, 1.0, amount);
  198. material.color.setHSL(hue, saturation, lightness);
  199. const mesh = new THREE.Mesh(geometry, material);
  200. scene.add(mesh);
  201. // 헬퍼들을 특정 위도와 경도로 이동시킵니다.
  202. lonHelper.rotation.y = THREE.MathUtils.degToRad(lonNdx + file.xllcorner) + lonFudge;
  203. latHelper.rotation.x = THREE.MathUtils.degToRad(latNdx + file.yllcorner) + latFudge;
  204. // positionHelper의 위치를 해당 mesh의 위치로 지정합니다.
  205. positionHelper.updateWorldMatrix(true, false);
  206. mesh.applyMatrix4(positionHelper.matrixWorld);
  207. mesh.scale.set(0.005, 0.005, THREE.MathUtils.lerp(0.01, 0.5, amount));
  208. });
  209. });
  210. }
  211. </pre>
  212. <p>위 코드는 아까 만들었던 테스트 코드의 구조를 그대로 사용한 것입니다.</p>
  213. <p>각 육면체를 양의 Z축으로 커지게 만든 건 지구본 위에 그래프가 올라와야 하기 때문입니다. 이 설정이 없다면 그래프가 지구본 안쪽으로 파고들어 가겠죠.</p>
  214. <div class="spread">
  215. <div>
  216. <div data-diagram="scaleCenter" style="height: 250px"></div>
  217. <div class="code">기본값</div>
  218. </div>
  219. <div>
  220. <div data-diagram="scalePositiveZ" style="height: 250px"></div>
  221. <div class="code">Z축을 조정한 결과</div>
  222. </div>
  223. </div>
  224. <p><a href="scenegraph.html">씬 그래프에 관한 글</a>에서 배웠듯 육면체를 다른 <a href="/docs/#api/ko/core/Object3D"><code class="notranslate" translate="no">THREE.Object3D</code></a>의 자식으로 두는 것도 한 가지 해결 방법이지만, 씬 그래프 요소가 많아지만 그만큼 성능이 떨어집니다.</p>
  225. <p><code class="notranslate" translate="no">lonHelper</code>, <code class="notranslate" translate="no">latHelper</code>, <code class="notranslate" translate="no">positionHelper</code>를 계층 구조로 만든 건 구체 주위에 육면체를 배치할 좌표를 찾기 위해서입니다.</p>
  226. <div class="spread">
  227. <div data-diagram="lonLatPos" style="width: 600px; height: 400px;"></div>
  228. </div>
  229. <p>위 예제의 <span style="color:green;">초록색 막대</span>는 <code class="notranslate" translate="no">lonHelper</code>를 상징합니다. 자전축을 중심으로 경도(longitude)를 찾는 역할을 하죠. <span style="color:blue">파란색 막대</span>는 <code class="notranslate" translate="no">latHelper</code>입니다. <code class="notranslate" translate="no">latHelper</code>는 적도 위 아래로 위도(latitude)를 찾는 역할을 합니다. <span style="color:red;">빨간 구체</span>는 <code class="notranslate" translate="no">positionHelper</code>로, 육면체의 좌표값을 나타냅니다.</p>
  230. <p>물론 좌표를 계산할 때 수학적으로 접근할 수도 있지만, 이렇게 라이브러리가 대신 계산하도록 하면 복잡하게 머리를 쥐어짜야할 필요가 없습니다.</p>
  231. <p>위 코드에서는 각 데이터 좌표마다 <a href="/docs/#api/ko/materials/MeshBasicMaterial"><code class="notranslate" translate="no">MeshBasicMaterial</code></a>와 <a href="/docs/#api/ko/objects/Mesh"><code class="notranslate" translate="no">Mesh</code></a>를 생성했습니다. 그리고 <code class="notranslate" translate="no">positionHelper</code>의 전역 좌표를 구해 <a href="/docs/#api/ko/objects/Mesh"><code class="notranslate" translate="no">Mesh</code></a>에 적용하고, 데이터의 양만큼 이 mesh를 키웠죠.</p>
  232. <p>아까와 마찬가지로 각 데이터마다 <code class="notranslate" translate="no">lonHelper</code>, <code class="notranslate" translate="no">latHelper</code>, <code class="notranslate" translate="no">positionHelper</code>를 따로 생성할 수도 있지만, 그렇게 하면 성능이 훨씬 느려질 겁니다.</p>
  233. <p>이러면 육면체를 최대 360x145개, 거의 최대 52000개를 만드는 셈입니다. "NO_DATA"라고 표시된 곳도 있기에 그걸 제외하면 육면체의 개수는 대략 19000개가 될 겁니다. 그런데 여기에 각 육면체에 따로 3개씩 헬퍼를 생성한다면 Three.js는 거의 80000개의 씬 그래프 요소를 계산하게 되죠. 대신 헬퍼를 공통으로 사용하면 연산 요청을 약 60000번 정도 줄일 수 있습니다.</p>
  234. <p><code class="notranslate" translate="no">lonFudge</code>와 <code class="notranslate" translate="no">latFudge</code>에 대해 짧게 언급하겠습니다. <code class="notranslate" translate="no">lonFudge</code>는 π/2, 90도입니다. 이건 크게 신경쓸 게 없네요. 그냥 텍스처나 텍스처 좌표가 다른 각도에서 시작한다는 소리니까요. 하지만 <code class="notranslate" translate="no">latFudge</code>의 경우는 왜 π * -0.135가 필요한지 모르겠습니다. 그냥 좌표가 저 축을 기준으로 정렬되어 있습니다.</p>
  235. <p>이제 만든 함수를 호출합니다.</p>
  236. <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')
  237. .then(parseData)
  238. - .then(drawData)
  239. + .then(addBoxes)
  240. + .then(render);
  241. </pre><p><a href="rendering-on-demand.html">필요할 때만 렌더링 함수를 호출</a>하게 해놨으므로 지구본과 육면체들을 추가한 뒤 <code class="notranslate" translate="no">render</code> 함수를 직접 호출해야 합니다.</p>
  242. <p></p><div translate="no" class="threejs_example_container notranslate">
  243. <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>
  244. <a class="threejs_center" href="/manual/examples/lots-of-objects-slow.html" target="_blank">새 탭에서 보기</a>
  245. </div>
  246. <p></p>
  247. <p>위 예제를 드래그해 지구본을 돌려보면 뭔가 버벅임을 느낄 수 있을 겁니다.</p>
  248. <p><a href="debugging-javascript.html">개발자 도구를 열어</a> 브라우저의 FPS 미터를 켜면 프레임율을 확인할 수 있습니다.</p>
  249. <div class="threejs_center"><img src="../resources/images/bring-up-fps-meter.gif"></div>
  250. <p>제 환경에서는 평균 프레임이 20fps보다 낮네요.</p>
  251. <div class="threejs_center"><img src="../resources/images/fps-meter.gif"></div>
  252. <p>아마 더 안 좋은 컴퓨터에서는 이보다 더 심할 겁니다. 최적화할 방법을 찾아봐야겠네요.</p>
  253. <p>예제의 경우 모든 정육면체를 하나의 geometry로 합치는 방법을 적용할 수 있습니다. 현재 거의 육면체를 거의 19000개 정도 렌더링했는데, 이를 하나로 합치면 연산 요청을 18999회 정도 줄일 수 있습니다.</p>
  254. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">function addBoxes(file) {
  255. const {min, max, data} = file;
  256. const range = max - min;
  257. - // 육면체 geometry를 만듭니다.
  258. - const boxWidth = 1;
  259. - const boxHeight = 1;
  260. - const boxDepth = 1;
  261. - const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth);
  262. - // 중심이 아닌 양의 z축 방향으로 커지게끔 만듭니다.
  263. - geometry.applyMatrix4(new THREE.Matrix4().makeTranslation(0, 0, 0.5));
  264. // 아래 헬퍼 Object3D는 육면체들의 위치 변화를 간단하게 만들어줍니다.
  265. // lonHelper를 Y축으로 돌려 경도(longitude)를 맞출 수 있습니다.
  266. const lonHelper = new THREE.Object3D();
  267. scene.add(lonHelper);
  268. // latHelper를 X축으로 돌려 위도(latitude)를 맞출 수 있습니다.
  269. const latHelper = new THREE.Object3D();
  270. lonHelper.add(latHelper);
  271. // positionHelper는 다른 요소의 기준축을 구체의 끝에 맞추는 역할을 합니다.
  272. const positionHelper = new THREE.Object3D();
  273. positionHelper.position.z = 1;
  274. latHelper.add(positionHelper);
  275. + // 육면체의 중심을 옮겨 양의 Z축 방향으로 커지게 합니다.
  276. + const originHelper = new THREE.Object3D();
  277. + originHelper.position.z = 0.5;
  278. + positionHelper.add(originHelper);
  279. const lonFudge = Math.PI * .5;
  280. const latFudge = Math.PI * -0.135;
  281. + const geometries = [];
  282. data.forEach((row, latNdx) =&gt; {
  283. row.forEach((value, lonNdx) =&gt; {
  284. if (value === undefined) {
  285. return;
  286. }
  287. const amount = (value - min) / range;
  288. - const material = new THREE.MeshBasicMaterial();
  289. - const hue = THREE.MathUtils.lerp(0.7, 0.3, amount);
  290. - const saturation = 1;
  291. - const lightness = THREE.MathUtils.lerp(0.1, 1.0, amount);
  292. - material.color.setHSL(hue, saturation, lightness);
  293. - const mesh = new THREE.Mesh(geometry, material);
  294. - scene.add(mesh);
  295. + const boxWidth = 1;
  296. + const boxHeight = 1;
  297. + const boxDepth = 1;
  298. + const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth);
  299. // 헬퍼들을 특정 위도와 경도로 이동시킵니다.
  300. lonHelper.rotation.y = THREE.MathUtils.degToRad(lonNdx + file.xllcorner) + lonFudge;
  301. latHelper.rotation.x = THREE.MathUtils.degToRad(latNdx + file.yllcorner) + latFudge;
  302. - // positionHelper의 위치를 해당 mesh의 위치로 지정합니다.
  303. - positionHelper.updateWorldMatrix(true, false);
  304. - mesh.applyMatrix4(positionHelper.matrixWorld);
  305. -
  306. - mesh.scale.set(0.005, 0.005, THREE.MathUtils.lerp(0.01, 0.5, amount));
  307. + // originHelper의 위치를 해당 geometry의 위치로 지정합니다.
  308. + positionHelper.scale.set(0.005, 0.005, THREE.MathUtils.lerp(0.01, 0.5, amount));
  309. + originHelper.updateWorldMatrix(true, false);
  310. + geometry.applyMatrix4(originHelper.matrixWorld);
  311. +
  312. + geometries.push(geometry);
  313. });
  314. });
  315. + // 생성한 geometry를 전부 합칩니다.
  316. + const mergedGeometry = BufferGeometryUtils.mergeGeometries(
  317. + geometries, false);
  318. + const material = new THREE.MeshBasicMaterial({ color:'red' });
  319. + const mesh = new THREE.Mesh(mergedGeometry, material);
  320. + scene.add(mesh);
  321. }
  322. </pre>
  323. <p>위 코드에서는 육면체의 중심을 옮기는 대신 <code class="notranslate" translate="no">originHelper</code>를 새로 만들어 중심축을 옮겼습니다. 이전에는 같은 geometry를 19000번 재활용했지만, 이번에는 데이터마다 geometry를 새로 생성했죠. 또한 <code class="notranslate" translate="no">applyMatrix</code>를 이용해 육면체 자체의 정점을 이동시키므로 메서드를 두 번 쓰는 대신 한 번만 썼습니다.</p>
  324. <p>그리고 생성한 육면체를 전부 배열에 저장한 뒤 이 배열을 <code class="notranslate" translate="no">BufferGeometryUtils.mergeGeometries</code>에 넘겨 하나의 geometry로 합쳤습니다.</p>
  325. <p>물론 <code class="notranslate" translate="no">BufferGeometryUtils</code>을 불러와야죠.</p>
  326. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">import { BufferGeometryUtils } from 'three/addons/utils/BufferGeometryUtils.js';
  327. </pre>
  328. <p>이제 제 컴퓨터에서는 적어도 60 프레임 이상이 나오네요.</p>
  329. <p></p><div translate="no" class="threejs_example_container notranslate">
  330. <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>
  331. <a class="threejs_center" href="/manual/examples/lots-of-objects-merged.html" target="_blank">새 탭에서 보기</a>
  332. </div>
  333. <p></p>
  334. <p>성능 문제는 해결했지만 육면체가 하나의 mesh이기에 이전과 달리 육면체의 색이 전부 같습니다. 여기서 색을 따로 지정하려면? 여러 방법이 있겠지만 정점 색(vertex color)을 쓰는 방법이 제일 간단할 겁니다.</p>
  335. <p>정점 색은 정점마다 색을 지정합니다. 각 육면체의 각 정점을 다른 색으로 지정하면 육면체의 색을 다르게 지정할 수 있겠죠.</p>
  336. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">+const color = new THREE.Color();
  337. const lonFudge = Math.PI * .5;
  338. const latFudge = Math.PI * -0.135;
  339. const geometries = [];
  340. data.forEach((row, latNdx) =&gt; {
  341. row.forEach((value, lonNdx) =&gt; {
  342. if (value === undefined) {
  343. return;
  344. }
  345. const amount = (value - min) / range;
  346. const boxWidth = 1;
  347. const boxHeight = 1;
  348. const boxDepth = 1;
  349. const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth);
  350. // 헬퍼들을 특정 위도와 경도로 이동시킵니다.
  351. lonHelper.rotation.y = THREE.MathUtils.degToRad(lonNdx + file.xllcorner) + lonFudge;
  352. latHelper.rotation.x = THREE.MathUtils.degToRad(latNdx + file.yllcorner) + latFudge;
  353. // originHelper의 위치를 해당 geometry의 위치로 지정합니다.
  354. positionHelper.scale.set(0.005, 0.005, THREE.MathUtils.lerp(0.01, 0.5, amount));
  355. originHelper.updateWorldMatrix(true, false);
  356. geometry.applyMatrix4(originHelper.matrixWorld);
  357. + // 색상값을 계산합니다.
  358. + const hue = THREE.MathUtils.lerp(0.7, 0.3, amount);
  359. + const saturation = 1;
  360. + const lightness = THREE.MathUtils.lerp(0.4, 1.0, amount);
  361. + color.setHSL(hue, saturation, lightness);
  362. + // RGB 색상값을 0부터 255까지의 배열로 변환합니다.
  363. + const rgb = color.toArray().map(v =&gt; v * 255);
  364. +
  365. + // 각 정점의 색을 배열로 저장합니다.
  366. + const numVerts = geometry.getAttribute('position').count;
  367. + const itemSize = 3; // r, g, b
  368. + const colors = new Uint8Array(itemSize * numVerts);
  369. +
  370. + // 색상값을 각 정점에 지정할 색상으로 변환합니다.
  371. + colors.forEach((v, ndx) =&gt; {
  372. + colors[ndx] = rgb[ndx % 3];
  373. + });
  374. +
  375. + const normalized = true;
  376. + const colorAttrib = new THREE.BufferAttribute(colors, itemSize, normalized);
  377. + geometry.setAttribute('color', colorAttrib);
  378. geometries.push(geometry);
  379. });
  380. });
  381. </pre>
  382. <p>추가한 코드에서는 먼저 geometry의 <code class="notranslate" translate="no">position</code> 속성을 가져와 정점의 개수를 파악했습니다. 그런 다음 색상을 지정하기 위해 <code class="notranslate" translate="no">Uint8Array</code>로 변환한 뒤, 이를 <code class="notranslate" translate="no">geometry.setAttribute</code> 메서드로 geometry의 <code class="notranslate" translate="no">color</code> 속성에 지정했죠.</p>
  383. <p>마지막으로 재질(material)이 정점 색상을 사용하도록 설정합니다.</p>
  384. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const mergedGeometry = BufferGeometryUtils.mergeGeometries(
  385. geometries, false);
  386. -const material = new THREE.MeshBasicMaterial({color:'red'});
  387. +const material = new THREE.MeshBasicMaterial({
  388. + vertexColors: true,
  389. +});
  390. const mesh = new THREE.Mesh(mergedGeometry, material);
  391. scene.add(mesh);
  392. </pre>
  393. <p>이제 색이 다시 정상적으로 보입니다.</p>
  394. <p></p><div translate="no" class="threejs_example_container notranslate">
  395. <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>
  396. <a class="threejs_center" href="/manual/examples/lots-of-objects-merged-vertexcolors.html" target="_blank">새 탭에서 보기</a>
  397. </div>
  398. <p></p>
  399. <p>geometry를 합치는 건 꽤 자주 사용하는 최적화 기법입니다. 예를 들어 나무 100개를 하나의 geometry로 합치거나, 돌무더기를 하나의 돌 geometry로 합치거나, 울타리의 각 기둥을 하나의 mesh로 합치는 경우가 해당되죠. 마인크래프트의 경우도 모든 타일을 하나하나 다 렌더링하기보다 타일을 하나로 합쳐 보이지 않는 면은 제거하는 기법을 사용할 확률이 높습니다.</p>
  400. <p>하지만 요소를 하나의 mesh로 합쳐버리면 별도의 요소였던 특정 부분을 조작하기가 어렵습니다. 상황에 따라 좋은 방법도 다 다를 테죠. <a href="optimize-lots-of-objects-animated.html">다음 글</a>에서는 그 방법 중 하나를 살펴보겠습니다.</p>
  401. <p><canvas id="c"></canvas></p>
  402. <script type="module" src="../resources/threejs-lots-of-objects.js"></script>
  403. </div>
  404. </div>
  405. </div>
  406. <script src="../resources/prettify.js"></script>
  407. <script src="../resources/lesson.js"></script>
  408. </body></html>