custom-buffergeometry.html 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. <!DOCTYPE html><html lang="ru"><head>
  2. <meta charset="utf-8">
  3. <title>Пользовательская BufferGeometry</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 – Пользовательская BufferGeometry">
  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>Пользовательская BufferGeometry</h1>
  28. </div>
  29. <div class="lesson">
  30. <div class="lesson-main">
  31. <p></p>
  32. <p><a href="/docs/#api/en/core/BufferGeometry"><code class="notranslate" translate="no">BufferGeometry</code></a> с другой стороны использует названный <code class="notranslate" translate="no">BufferAttributes</code>.
  33. Каждый атрибут <a href="/docs/#api/en/core/BufferAttribute"><code class="notranslate" translate="no">BufferAttribute</code></a> представляет собой массив данных одного типа: позиции, нормали, цвета и ультрафиолетовые лучи.
  34. Вместе добавленные атрибуты <code class="notranslate" translate="no">BufferAttributes</code> представляют параллельные массивы всех данных для каждой вершины. </p>
  35. <div class="threejs_center"><img src="../resources/threejs-attributes.svg" style="width: 700px"></div>
  36. <p>Вы можете видеть, что у нас есть 4 атрибута: <code class="notranslate" translate="no">position</code>, <code class="notranslate" translate="no">normal</code>, <code class="notranslate" translate="no">color</code>, <code class="notranslate" translate="no">uv</code>.
  37. Они представляют параллельные массивы, что означает, что N-й набор данных в каждом атрибуте принадлежит одной и той же вершине.
  38. Вершина с индексом = 4 подсвечивается, чтобы показать, что параллельные данные по всем атрибутам определяют одну вершину. </p>
  39. <p>Это поднимает точку, вот схема куба с одним выделенным углом. </p>
  40. <div class="threejs_center"><img src="../resources/cube-faces-vertex.svg" style="width: 500px"></div>
  41. <p>Думая об этом, один угол нуждается в разной нормали для каждой грани куба.
  42. Для каждой стороны тоже нужны разные ультрафиолеты. Это указывает на самую большую разницу между <code class="notranslate" translate="no">Geometry</code> и <a href="/docs/#api/en/core/BufferGeometry"><code class="notranslate" translate="no">BufferGeometry</code></a>. Ничего общего с <a href="/docs/#api/en/core/BufferGeometry"><code class="notranslate" translate="no">BufferGeometry</code></a>.
  43. Одна вершина - это комбинация всех ее частей. Если вершина нуждается в какой-либо части, то она должна быть другой. </p>
  44. <p>Правда в том, что когда вы используете <code class="notranslate" translate="no">Geometry</code> three.js преобразует его в этот формат.
  45. Вот откуда появляется дополнительная память и время при использовании <code class="notranslate" translate="no">Geometry</code>.
  46. Дополнительная память для всех объектов <code class="notranslate" translate="no">Vector3s</code>, <code class="notranslate" translate="no">Vector2s</code>, <code class="notranslate" translate="no">Face3s</code> и массива, а затем дополнительное время для преобразования всех этих данных
  47. в параллельные массивы в форме атрибутов <code class="notranslate" translate="no">BufferAttributes</code>, как указано выше.
  48. Иногда это облегчает использование Geometry. С <a href="/docs/#api/en/core/BufferGeometry"><code class="notranslate" translate="no">BufferGeometry</code></a> мы можем предоставить данные, уже преобразованные в этот формат. </p>
  49. <p>В качестве простого примера давайте сделаем куб, используя <a href="/docs/#api/en/core/BufferGeometry"><code class="notranslate" translate="no">BufferGeometry</code></a>.
  50. Куб интересен тем, что кажется, что он разделяет вершины в углах, но на самом деле это не так. В нашем примере мы перечислим все вершины со всеми их данными,
  51. а затем преобразуем эти данные в параллельные массивы и, наконец, используем их для создания атрибутов <code class="notranslate" translate="no">Buffer</code> и добавления их в <a href="/docs/#api/en/core/BufferGeometry"><code class="notranslate" translate="no">BufferGeometry</code></a>. </p>
  52. <p>Начиная с примера координат текстуры из предыдущей статьи, мы удалили весь код, связанный с настройкой <code class="notranslate" translate="no">Geometry</code>.
  53. Затем мы перечисляем все данные, необходимые для куба. Помните еще раз, что если вершина имеет какие-либо уникальные части, она должна быть отдельной вершиной.
  54. Для создания куба необходимо 36 вершин. 2 треугольника на грань, 3 вершины на треугольник, 6 граней = 36 вершин. </p>
  55. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const vertices = [
  56. // front
  57. { pos: [-1, -1, 1], norm: [ 0, 0, 1], uv: [0, 0], },
  58. { pos: [ 1, -1, 1], norm: [ 0, 0, 1], uv: [1, 0], },
  59. { pos: [-1, 1, 1], norm: [ 0, 0, 1], uv: [0, 1], },
  60. { pos: [-1, 1, 1], norm: [ 0, 0, 1], uv: [0, 1], },
  61. { pos: [ 1, -1, 1], norm: [ 0, 0, 1], uv: [1, 0], },
  62. { pos: [ 1, 1, 1], norm: [ 0, 0, 1], uv: [1, 1], },
  63. // right
  64. { pos: [ 1, -1, 1], norm: [ 1, 0, 0], uv: [0, 0], },
  65. { pos: [ 1, -1, -1], norm: [ 1, 0, 0], uv: [1, 0], },
  66. { pos: [ 1, 1, 1], norm: [ 1, 0, 0], uv: [0, 1], },
  67. { pos: [ 1, 1, 1], norm: [ 1, 0, 0], uv: [0, 1], },
  68. { pos: [ 1, -1, -1], norm: [ 1, 0, 0], uv: [1, 0], },
  69. { pos: [ 1, 1, -1], norm: [ 1, 0, 0], uv: [1, 1], },
  70. // back
  71. { pos: [ 1, -1, -1], norm: [ 0, 0, -1], uv: [0, 0], },
  72. { pos: [-1, -1, -1], norm: [ 0, 0, -1], uv: [1, 0], },
  73. { pos: [ 1, 1, -1], norm: [ 0, 0, -1], uv: [0, 1], },
  74. { pos: [ 1, 1, -1], norm: [ 0, 0, -1], uv: [0, 1], },
  75. { pos: [-1, -1, -1], norm: [ 0, 0, -1], uv: [1, 0], },
  76. { pos: [-1, 1, -1], norm: [ 0, 0, -1], uv: [1, 1], },
  77. // left
  78. { pos: [-1, -1, -1], norm: [-1, 0, 0], uv: [0, 0], },
  79. { pos: [-1, -1, 1], norm: [-1, 0, 0], uv: [1, 0], },
  80. { pos: [-1, 1, -1], norm: [-1, 0, 0], uv: [0, 1], },
  81. { pos: [-1, 1, -1], norm: [-1, 0, 0], uv: [0, 1], },
  82. { pos: [-1, -1, 1], norm: [-1, 0, 0], uv: [1, 0], },
  83. { pos: [-1, 1, 1], norm: [-1, 0, 0], uv: [1, 1], },
  84. // top
  85. { pos: [ 1, 1, -1], norm: [ 0, 1, 0], uv: [0, 0], },
  86. { pos: [-1, 1, -1], norm: [ 0, 1, 0], uv: [1, 0], },
  87. { pos: [ 1, 1, 1], norm: [ 0, 1, 0], uv: [0, 1], },
  88. { pos: [ 1, 1, 1], norm: [ 0, 1, 0], uv: [0, 1], },
  89. { pos: [-1, 1, -1], norm: [ 0, 1, 0], uv: [1, 0], },
  90. { pos: [-1, 1, 1], norm: [ 0, 1, 0], uv: [1, 1], },
  91. // bottom
  92. { pos: [ 1, -1, 1], norm: [ 0, -1, 0], uv: [0, 0], },
  93. { pos: [-1, -1, 1], norm: [ 0, -1, 0], uv: [1, 0], },
  94. { pos: [ 1, -1, -1], norm: [ 0, -1, 0], uv: [0, 1], },
  95. { pos: [ 1, -1, -1], norm: [ 0, -1, 0], uv: [0, 1], },
  96. { pos: [-1, -1, 1], norm: [ 0, -1, 0], uv: [1, 0], },
  97. { pos: [-1, -1, -1], norm: [ 0, -1, 0], uv: [1, 1], },
  98. ];
  99. </pre>
  100. <p>Затем мы можем перевести все это в 3 параллельных массива </p>
  101. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const positions = [];
  102. const normals = [];
  103. const uvs = [];
  104. for (const vertex of vertices) {
  105. positions.push(...vertex.pos);
  106. normals.push(...vertex.norm);
  107. uvs.push(...vertex.uv);
  108. }
  109. </pre>
  110. <p>Наконец, мы можем создать <a href="/docs/#api/en/core/BufferGeometry"><code class="notranslate" translate="no">BufferGeometry</code></a>, а затем <a href="/docs/#api/en/core/BufferAttribute"><code class="notranslate" translate="no">BufferAttribute</code></a> для каждого массива и добавить его в <a href="/docs/#api/en/core/BufferGeometry"><code class="notranslate" translate="no">BufferGeometry</code></a>.</p>
  111. <pre class="prettyprint showlinemods notranslate lang-js" translate="no"> const geometry = new THREE.BufferGeometry();
  112. const positionNumComponents = 3;
  113. const normalNumComponents = 3;
  114. const uvNumComponents = 2;
  115. geometry.setAttribute(
  116. 'position',
  117. new THREE.BufferAttribute(new Float32Array(positions), positionNumComponents));
  118. geometry.setAttribute(
  119. 'normal',
  120. new THREE.BufferAttribute(new Float32Array(normals), normalNumComponents));
  121. geometry.setAttribute(
  122. 'uv',
  123. new THREE.BufferAttribute(new Float32Array(uvs), uvNumComponents));
  124. </pre>
  125. <p>Обратите внимание, что имена являются значительными. Вы должны назвать свои атрибуты именами, которые соответствуют ожиданиям three.js
  126. (если вы не создаете пользовательский шейдер). В этом случае <code class="notranslate" translate="no">position</code>, <code class="notranslate" translate="no">normal</code> и <code class="notranslate" translate="no">uv</code>. Если вы хотите цвета вершин, назовите свой атрибут <code class="notranslate" translate="no">color</code>. </p>
  127. <p>Выше мы создали 3 собственных массива JavaScript, <code class="notranslate" translate="no">positions</code>, <code class="notranslate" translate="no">normals</code> и <code class="notranslate" translate="no">uvs</code> . Затем мы конвертируем их в
  128. <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray">TypedArrays</a>
  129. типа Float32Array. Атрибут <a href="/docs/#api/en/core/BufferAttribute"><code class="notranslate" translate="no">BufferAttribute</code></a> требует TypedArray, а не собственного массива. Атрибут <a href="/docs/#api/en/core/BufferAttribute"><code class="notranslate" translate="no">BufferAttribute</code></a> также требует, чтобы вы указали,
  130. сколько компонентов в каждой вершине. Для позиций и нормалей у нас есть 3 компонента на вершину, x, y и z. Для UV у нас есть 2, u и v. </p>
  131. <p></p><div translate="no" class="threejs_example_container notranslate">
  132. <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/custom-buffergeometry-cube.html"></iframe></div>
  133. <a class="threejs_center" href="/manual/examples/custom-buffergeometry-cube.html" target="_blank">нажмите здесь, чтобы открыть в отдельном окне</a>
  134. </div>
  135. <p></p>
  136. <p>Это много данных. Небольшая вещь, которую мы можем сделать, это использовать индексы для ссылки на вершины.
  137. Оглядываясь назад на данные нашего куба, каждая грань состоит из 2 треугольников с 3 вершинами в каждом, всего 6 вершин, но 2 из этих вершин абсолютно одинаковы;
  138. Та же самая position, та же самая normal, и та же самая uv.
  139. Таким образом, мы можем удалить совпадающие вершины и затем ссылаться на них по индексу. Сначала мы удаляем совпадающие вершины. </p>
  140. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const vertices = [
  141. // front
  142. { pos: [-1, -1, 1], norm: [ 0, 0, 1], uv: [0, 0], }, // 0
  143. { pos: [ 1, -1, 1], norm: [ 0, 0, 1], uv: [1, 0], }, // 1
  144. { pos: [-1, 1, 1], norm: [ 0, 0, 1], uv: [0, 1], }, // 2
  145. -
  146. - { pos: [-1, 1, 1], norm: [ 0, 0, 1], uv: [0, 1], },
  147. - { pos: [ 1, -1, 1], norm: [ 0, 0, 1], uv: [1, 0], },
  148. { pos: [ 1, 1, 1], norm: [ 0, 0, 1], uv: [1, 1], }, // 3
  149. // right
  150. { pos: [ 1, -1, 1], norm: [ 1, 0, 0], uv: [0, 0], }, // 4
  151. { pos: [ 1, -1, -1], norm: [ 1, 0, 0], uv: [1, 0], }, // 5
  152. -
  153. - { pos: [ 1, 1, 1], norm: [ 1, 0, 0], uv: [0, 1], },
  154. - { pos: [ 1, -1, -1], norm: [ 1, 0, 0], uv: [1, 0], },
  155. { pos: [ 1, 1, 1], norm: [ 1, 0, 0], uv: [0, 1], }, // 6
  156. { pos: [ 1, 1, -1], norm: [ 1, 0, 0], uv: [1, 1], }, // 7
  157. // back
  158. { pos: [ 1, -1, -1], norm: [ 0, 0, -1], uv: [0, 0], }, // 8
  159. { pos: [-1, -1, -1], norm: [ 0, 0, -1], uv: [1, 0], }, // 9
  160. -
  161. - { pos: [ 1, 1, -1], norm: [ 0, 0, -1], uv: [0, 1], },
  162. - { pos: [-1, -1, -1], norm: [ 0, 0, -1], uv: [1, 0], },
  163. { pos: [ 1, 1, -1], norm: [ 0, 0, -1], uv: [0, 1], }, // 10
  164. { pos: [-1, 1, -1], norm: [ 0, 0, -1], uv: [1, 1], }, // 11
  165. // left
  166. { pos: [-1, -1, -1], norm: [-1, 0, 0], uv: [0, 0], }, // 12
  167. { pos: [-1, -1, 1], norm: [-1, 0, 0], uv: [1, 0], }, // 13
  168. -
  169. - { pos: [-1, 1, -1], norm: [-1, 0, 0], uv: [0, 1], },
  170. - { pos: [-1, -1, 1], norm: [-1, 0, 0], uv: [1, 0], },
  171. { pos: [-1, 1, -1], norm: [-1, 0, 0], uv: [0, 1], }, // 14
  172. { pos: [-1, 1, 1], norm: [-1, 0, 0], uv: [1, 1], }, // 15
  173. // top
  174. { pos: [ 1, 1, -1], norm: [ 0, 1, 0], uv: [0, 0], }, // 16
  175. { pos: [-1, 1, -1], norm: [ 0, 1, 0], uv: [1, 0], }, // 17
  176. -
  177. - { pos: [ 1, 1, 1], norm: [ 0, 1, 0], uv: [0, 1], },
  178. - { pos: [-1, 1, -1], norm: [ 0, 1, 0], uv: [1, 0], },
  179. { pos: [ 1, 1, 1], norm: [ 0, 1, 0], uv: [0, 1], }, // 18
  180. { pos: [-1, 1, 1], norm: [ 0, 1, 0], uv: [1, 1], }, // 19
  181. // bottom
  182. { pos: [ 1, -1, 1], norm: [ 0, -1, 0], uv: [0, 0], }, // 20
  183. { pos: [-1, -1, 1], norm: [ 0, -1, 0], uv: [1, 0], }, // 21
  184. -
  185. - { pos: [ 1, -1, -1], norm: [ 0, -1, 0], uv: [0, 1], },
  186. - { pos: [-1, -1, 1], norm: [ 0, -1, 0], uv: [1, 0], },
  187. { pos: [ 1, -1, -1], norm: [ 0, -1, 0], uv: [0, 1], }, // 22
  188. { pos: [-1, -1, -1], norm: [ 0, -1, 0], uv: [1, 1], }, // 23
  189. ];
  190. </pre>
  191. <p>Итак, теперь у нас есть 24 уникальные вершины.
  192. Затем мы указываем 36 индексов для 36 вершин, которые нам нужно нарисовать, чтобы сделать 12 треугольников, вызывая <a href="/docs/#api/en/core/BufferGeometry.setIndex"><code class="notranslate" translate="no">BufferGeometry.setIndex</code></a> с массивом индексов. </p>
  193. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">geometry.setAttribute(
  194. 'position',
  195. new THREE.BufferAttribute(positions, positionNumComponents));
  196. geometry.setAttribute(
  197. 'normal',
  198. new THREE.BufferAttribute(normals, normalNumComponents));
  199. geometry.setAttribute(
  200. 'uv',
  201. new THREE.BufferAttribute(uvs, uvNumComponents));
  202. +geometry.setIndex([
  203. + 0, 1, 2, 2, 1, 3, // front
  204. + 4, 5, 6, 6, 5, 7, // right
  205. + 8, 9, 10, 10, 9, 11, // back
  206. + 12, 13, 14, 14, 13, 15, // left
  207. + 16, 17, 18, 18, 17, 19, // top
  208. + 20, 21, 22, 22, 21, 23, // bottom
  209. +]);
  210. </pre>
  211. <p></p><div translate="no" class="threejs_example_container notranslate">
  212. <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/custom-buffergeometry-cube-indexed.html"></iframe></div>
  213. <a class="threejs_center" href="/manual/examples/custom-buffergeometry-cube-indexed.html" target="_blank">нажмите здесь, чтобы открыть в отдельном окне</a>
  214. </div>
  215. <p></p>
  216. <p>Как и в <code class="notranslate" translate="no">Geometry</code>, в <a href="/docs/#api/en/core/BufferGeometry"><code class="notranslate" translate="no">BufferGeometry</code></a> есть метод <a href="/docs/#api/en/core/BufferGeometry#computeVertexNormals"><code class="notranslate" translate="no">computeVertexNormals</code></a> для вычисления нормалей,
  217. если вы их не предоставляете. В отличие от версии <code class="notranslate" translate="no">Geometry</code> той же функции,
  218. поскольку позиции не могут быть общими, если любая другая часть вершины отличается, результаты вызова <code class="notranslate" translate="no">computeVertexNormals</code> будут другими. </p>
  219. <div class="spread">
  220. <div>
  221. <div data-diagram="bufferGeometryCylinder"></div>
  222. <div class="code">BufferGeometry</div>
  223. </div>
  224. <div>
  225. <div data-diagram="geometryCylinder"></div>
  226. <div class="code">Geometry</div>
  227. </div>
  228. </div>
  229. <p>Вот 2 цилиндра, где нормали были созданы с использованием <code class="notranslate" translate="no">computeVertexNormals</code>.
  230. Если вы посмотрите внимательно, на левом цилиндре есть шов. Это связано с тем,
  231. что нет возможности совместно использовать вершины в начале и конце цилиндра, так как они требуют разных UV.
  232. Просто небольшая вещь, чтобы быть в курсе.
  233. Решение состоит в том, чтобы предоставить свои собственные normals. </p>
  234. <p>Мы также можем использовать <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray">TypedArrays</a>
  235. с самого начала вместо собственных массивов JavaScript. Недостатком TypedArrays является то, что вы должны указать их размер заранее.
  236. Конечно, это не так уж сложно, но с помощью собственных массивов мы можем просто <code class="notranslate" translate="no">push</code> значения в них и посмотреть,
  237. какого размера они заканчиваются, проверив их <code class="notranslate" translate="no">length</code> в конце.
  238. В TypedArrays нет функции push, поэтому нам нужно вести собственную бухгалтерию при добавлении значений к ним. </p>
  239. <p>В этом примере узнать длину заранее довольно просто, так как для начала мы используем большой блок статических данных. </p>
  240. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">-const positions = [];
  241. -const normals = [];
  242. -const uvs = [];
  243. +const numVertices = vertices.length;
  244. +const positionNumComponents = 3;
  245. +const normalNumComponents = 3;
  246. +const uvNumComponents = 2;
  247. +const positions = new Float32Array(numVertices * positionNumComponents);
  248. +const normals = new Float32Array(numVertices * normalNumComponents);
  249. +const uvs = new Float32Array(numVertices * uvNumComponents);
  250. +let posNdx = 0;
  251. +let nrmNdx = 0;
  252. +let uvNdx = 0;
  253. for (const vertex of vertices) {
  254. - positions.push(...vertex.pos);
  255. - normals.push(...vertex.norm);
  256. - uvs.push(...vertex.uv);
  257. + positions.set(vertex.pos, posNdx);
  258. + normals.set(vertex.norm, nrmNdx);
  259. + uvs.set(vertex.uv, uvNdx);
  260. + posNdx += positionNumComponents;
  261. + nrmNdx += normalNumComponents;
  262. + uvNdx += uvNumComponents;
  263. }
  264. geometry.setAttribute(
  265. 'position',
  266. - new THREE.BufferAttribute(new Float32Array(positions), positionNumComponents));
  267. + new THREE.BufferAttribute(positions, positionNumComponents));
  268. geometry.setAttribute(
  269. 'normal',
  270. - new THREE.BufferAttribute(new Float32Array(normals), normalNumComponents));
  271. + new THREE.BufferAttribute(normals, normalNumComponents));
  272. geometry.setAttribute(
  273. 'uv',
  274. - new THREE.BufferAttribute(new Float32Array(uvs), uvNumComponents));
  275. + new THREE.BufferAttribute(uvs, uvNumComponents));
  276. geometry.setIndex([
  277. 0, 1, 2, 2, 1, 3, // front
  278. 4, 5, 6, 6, 5, 7, // right
  279. 8, 9, 10, 10, 9, 11, // back
  280. 12, 13, 14, 14, 13, 15, // left
  281. 16, 17, 18, 18, 17, 19, // top
  282. 20, 21, 22, 22, 21, 23, // bottom
  283. ]);
  284. </pre>
  285. <p></p><div translate="no" class="threejs_example_container notranslate">
  286. <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/custom-buffergeometry-cube-typedarrays.html"></iframe></div>
  287. <a class="threejs_center" href="/manual/examples/custom-buffergeometry-cube-typedarrays.html" target="_blank">нажмите здесь, чтобы открыть в отдельном окне</a>
  288. </div>
  289. <p></p>
  290. <p>Хорошая причина использовать typedarrays - если вы хотите динамически обновлять любую часть вершин. </p>
  291. <p>Я не мог придумать действительно хороший пример динамического обновления вершин,
  292. поэтому я решил создать сферу и переместить каждый четырехугольник внутрь и наружу от центра. Надеюсь, это полезный пример. </p>
  293. <p>Вот код для генерации позиций и индексов для сферы. Код разделяет вершины внутри четырехугольника,
  294. но не разделяет вершины между четырьмя, потому что мы хотим иметь возможность перемещать каждый четырёхугольник по отдельности. </p>
  295. <p>Поскольку я ленивый, я использовал небольшую иерархию из 3 объектов Object3D для вычисления точек сферы. Как это работает, объясняется в
  296. <a href="optimize-lots-of-objects.html">статье об оптимизации множества объектов. </a>.</p>
  297. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">function makeSpherePositions(segmentsAround, segmentsDown) {
  298. const numVertices = segmentsAround * segmentsDown * 6;
  299. const numComponents = 3;
  300. const positions = new Float32Array(numVertices * numComponents);
  301. const indices = [];
  302. const longHelper = new THREE.Object3D();
  303. const latHelper = new THREE.Object3D();
  304. const pointHelper = new THREE.Object3D();
  305. longHelper.add(latHelper);
  306. latHelper.add(pointHelper);
  307. pointHelper.position.z = 1;
  308. const temp = new THREE.Vector3();
  309. function getPoint(lat, long) {
  310. latHelper.rotation.x = lat;
  311. longHelper.rotation.y = long;
  312. longHelper.updateMatrixWorld(true);
  313. return pointHelper.getWorldPosition(temp).toArray();
  314. }
  315. let posNdx = 0;
  316. let ndx = 0;
  317. for (let down = 0; down &lt; segmentsDown; ++down) {
  318. const v0 = down / segmentsDown;
  319. const v1 = (down + 1) / segmentsDown;
  320. const lat0 = (v0 - 0.5) * Math.PI;
  321. const lat1 = (v1 - 0.5) * Math.PI;
  322. for (let across = 0; across &lt; segmentsAround; ++across) {
  323. const u0 = across / segmentsAround;
  324. const u1 = (across + 1) / segmentsAround;
  325. const long0 = u0 * Math.PI * 2;
  326. const long1 = u1 * Math.PI * 2;
  327. positions.set(getPoint(lat0, long0), posNdx); posNdx += numComponents;
  328. positions.set(getPoint(lat1, long0), posNdx); posNdx += numComponents;
  329. positions.set(getPoint(lat0, long1), posNdx); posNdx += numComponents;
  330. positions.set(getPoint(lat1, long1), posNdx); posNdx += numComponents;
  331. indices.push(
  332. ndx, ndx + 1, ndx + 2,
  333. ndx + 2, ndx + 1, ndx + 3,
  334. );
  335. ndx += 4;
  336. }
  337. }
  338. return {positions, indices};
  339. }
  340. </pre>
  341. <p>Затем мы можем вызвать это так</p>
  342. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const segmentsAround = 24;
  343. const segmentsDown = 16;
  344. const {positions, indices} = makeSpherePositions(segmentsAround, segmentsDown);
  345. </pre>
  346. <p>Поскольку возвращаемые позиции являются позициями единичных сфер,
  347. они являются точно такими же значениями, которые нам нужны для нормалей, поэтому мы можем просто дублировать их для нормалей. </p>
  348. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const normals = positions.slice();
  349. </pre>
  350. <p>И тогда мы устанавливаем атрибуты, как раньше</p>
  351. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const geometry = new THREE.BufferGeometry();
  352. const positionNumComponents = 3;
  353. const normalNumComponents = 3;
  354. +const positionAttribute = new THREE.BufferAttribute(positions, positionNumComponents);
  355. +positionAttribute.setUsage(THREE.DynamicDrawUsage);
  356. geometry.setAttribute(
  357. 'position',
  358. + positionAttribute);
  359. geometry.setAttribute(
  360. 'normal',
  361. new THREE.BufferAttribute(normals, normalNumComponents));
  362. geometry.setIndex(indices);
  363. </pre>
  364. <p>Я выделил несколько различий. Мы сохраняем ссылку на атрибут позиции.
  365. Мы также отмечаем его как динамический. Это намек на THREE.js, что мы будем часто менять содержимое атрибута. </p>
  366. <p>В нашем цикле рендеринга мы обновляем позиции на основе их нормалей каждый кадр.</p>
  367. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const temp = new THREE.Vector3();
  368. ...
  369. for (let i = 0; i &lt; positions.length; i += 3) {
  370. const quad = (i / 12 | 0);
  371. const ringId = quad / segmentsAround | 0;
  372. const ringQuadId = quad % segmentsAround;
  373. const ringU = ringQuadId / segmentsAround;
  374. const angle = ringU * Math.PI * 2;
  375. temp.fromArray(normals, i);
  376. temp.multiplyScalar(THREE.MathUtils.lerp(1, 1.4, Math.sin(time + ringId + angle) * .5 + .5));
  377. temp.toArray(positions, i);
  378. }
  379. positionAttribute.needsUpdate = true;
  380. </pre>
  381. <p>И мы устанавливаем <code class="notranslate" translate="no">positionAttribute.needsUpdate</code>, чтобы THREE.js указывал использовать наши изменения.</p>
  382. <p></p><div translate="no" class="threejs_example_container notranslate">
  383. <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/custom-buffergeometry-dynamic.html"></iframe></div>
  384. <a class="threejs_center" href="/manual/examples/custom-buffergeometry-dynamic.html" target="_blank">нажмите здесь, чтобы открыть в отдельном окне</a>
  385. </div>
  386. <p></p>
  387. <p>Я надеюсь, что это были полезные примеры того, как использовать
  388. <a href="/docs/#api/en/core/BufferGeometry"><code class="notranslate" translate="no">BufferGeometry</code></a> напрямую для создания собственной геометрии и как динамически
  389. обновлять содержимое <a href="/docs/#api/en/core/BufferAttribute"><code class="notranslate" translate="no">BufferAttribute</code></a>. То, что вы используете, <code class="notranslate" translate="no">Geometry</code> или <a href="/docs/#api/en/core/BufferGeometry"><code class="notranslate" translate="no">BufferGeometry</code></a>,
  390. действительно зависит от ваших потребностей. </p>
  391. <p><canvas id="c"></canvas></p>
  392. <script type="module" src="../resources/threejs-custom-buffergeometry.js"></script>
  393. </div>
  394. </div>
  395. </div>
  396. <script src="../resources/prettify.js"></script>
  397. <script src="../resources/lesson.js"></script>
  398. </body></html>