1
0

billboards.html 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. <!DOCTYPE html><html lang="en"><head>
  2. <meta charset="utf-8">
  3. <title>Billboards</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 – Billboards">
  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. <script type="importmap">
  14. {
  15. "imports": {
  16. "three": "../../build/three.module.js"
  17. }
  18. }
  19. </script>
  20. </head>
  21. <body>
  22. <div class="container">
  23. <div class="lesson-title">
  24. <h1>Billboards</h1>
  25. </div>
  26. <div class="lesson">
  27. <div class="lesson-main">
  28. <p>In <a href="canvas-textures.html">a previous article</a> we used a <a href="/docs/#api/en/textures/CanvasTexture"><code class="notranslate" translate="no">CanvasTexture</code></a>
  29. to make labels / badges on characters. Sometimes we'd like to make labels or
  30. other things that always face the camera. Three.js provides the <a href="/docs/#api/en/objects/Sprite"><code class="notranslate" translate="no">Sprite</code></a> and
  31. <a href="/docs/#api/en/materials/SpriteMaterial"><code class="notranslate" translate="no">SpriteMaterial</code></a> to make this happen.</p>
  32. <p>Let's change the badge example from <a href="canvas-textures.html">the article on canvas textures</a>
  33. to use <a href="/docs/#api/en/objects/Sprite"><code class="notranslate" translate="no">Sprite</code></a> and <a href="/docs/#api/en/materials/SpriteMaterial"><code class="notranslate" translate="no">SpriteMaterial</code></a></p>
  34. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">function makePerson(x, labelWidth, size, name, color) {
  35. const canvas = makeLabelCanvas(labelWidth, size, name);
  36. const texture = new THREE.CanvasTexture(canvas);
  37. // because our canvas is likely not a power of 2
  38. // in both dimensions set the filtering appropriately.
  39. texture.minFilter = THREE.LinearFilter;
  40. texture.wrapS = THREE.ClampToEdgeWrapping;
  41. texture.wrapT = THREE.ClampToEdgeWrapping;
  42. - const labelMaterial = new THREE.MeshBasicMaterial({
  43. + const labelMaterial = new THREE.SpriteMaterial({
  44. map: texture,
  45. - side: THREE.DoubleSide,
  46. transparent: true,
  47. });
  48. const root = new THREE.Object3D();
  49. root.position.x = x;
  50. const body = new THREE.Mesh(bodyGeometry, bodyMaterial);
  51. root.add(body);
  52. body.position.y = bodyHeight / 2;
  53. const head = new THREE.Mesh(headGeometry, bodyMaterial);
  54. root.add(head);
  55. head.position.y = bodyHeight + headRadius * 1.1;
  56. - const label = new THREE.Mesh(labelGeometry, labelMaterial);
  57. + const label = new THREE.Sprite(labelMaterial);
  58. root.add(label);
  59. label.position.y = bodyHeight * 4 / 5;
  60. label.position.z = bodyRadiusTop * 1.01;
  61. </pre>
  62. <p>and the labels now always face the camera</p>
  63. <p></p><div translate="no" class="threejs_example_container notranslate">
  64. <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/billboard-labels-w-sprites.html"></iframe></div>
  65. <a class="threejs_center" href="/manual/examples/billboard-labels-w-sprites.html" target="_blank">click here to open in a separate window</a>
  66. </div>
  67. <p></p>
  68. <p>One problem is from certain angles the labels now intersect the
  69. characters. </p>
  70. <div class="threejs_center"><img src="../resources/images/billboard-label-z-issue.png" style="width: 455px;"></div>
  71. <p>We can move the position of the labels to fix.</p>
  72. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">+// if units are meters then 0.01 here makes size
  73. +// of the label into centimeters.
  74. +const labelBaseScale = 0.01;
  75. const label = new THREE.Sprite(labelMaterial);
  76. root.add(label);
  77. -label.position.y = bodyHeight * 4 / 5;
  78. -label.position.z = bodyRadiusTop * 1.01;
  79. +label.position.y = head.position.y + headRadius + size * labelBaseScale;
  80. -// if units are meters then 0.01 here makes size
  81. -// of the label into centimeters.
  82. -const labelBaseScale = 0.01;
  83. label.scale.x = canvas.width * labelBaseScale;
  84. label.scale.y = canvas.height * labelBaseScale;
  85. </pre>
  86. <p></p><div translate="no" class="threejs_example_container notranslate">
  87. <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/billboard-labels-w-sprites-adjust-height.html"></iframe></div>
  88. <a class="threejs_center" href="/manual/examples/billboard-labels-w-sprites-adjust-height.html" target="_blank">click here to open in a separate window</a>
  89. </div>
  90. <p></p>
  91. <p>Another thing we can do with billboards is draw facades.</p>
  92. <p>Instead of drawing 3D objects we draw 2D planes with an image
  93. of 3D objects. This is often faster than drawing 3D objects.</p>
  94. <p>For example let's make a scene with grid of trees. We'll make each
  95. tree from a cylinder for the base and a cone for the top.</p>
  96. <p>First we make the cone and cylinder geometry and materials that
  97. all the trees will share</p>
  98. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const trunkRadius = .2;
  99. const trunkHeight = 1;
  100. const trunkRadialSegments = 12;
  101. const trunkGeometry = new THREE.CylinderGeometry(
  102. trunkRadius, trunkRadius, trunkHeight, trunkRadialSegments);
  103. const topRadius = trunkRadius * 4;
  104. const topHeight = trunkHeight * 2;
  105. const topSegments = 12;
  106. const topGeometry = new THREE.ConeGeometry(
  107. topRadius, topHeight, topSegments);
  108. const trunkMaterial = new THREE.MeshPhongMaterial({color: 'brown'});
  109. const topMaterial = new THREE.MeshPhongMaterial({color: 'green'});
  110. </pre>
  111. <p>Then we'll make a function that makes a <a href="/docs/#api/en/objects/Mesh"><code class="notranslate" translate="no">Mesh</code></a> each for the trunk and top
  112. of a tree and parents both to an <a href="/docs/#api/en/core/Object3D"><code class="notranslate" translate="no">Object3D</code></a>.</p>
  113. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">function makeTree(x, z) {
  114. const root = new THREE.Object3D();
  115. const trunk = new THREE.Mesh(trunkGeometry, trunkMaterial);
  116. trunk.position.y = trunkHeight / 2;
  117. root.add(trunk);
  118. const top = new THREE.Mesh(topGeometry, topMaterial);
  119. top.position.y = trunkHeight + topHeight / 2;
  120. root.add(top);
  121. root.position.set(x, 0, z);
  122. scene.add(root);
  123. return root;
  124. }
  125. </pre>
  126. <p>Then we'll make a loop to place a grid of trees.</p>
  127. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">for (let z = -50; z &lt;= 50; z += 10) {
  128. for (let x = -50; x &lt;= 50; x += 10) {
  129. makeTree(x, z);
  130. }
  131. }
  132. </pre>
  133. <p>Let's also add a ground plane while we're at it</p>
  134. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">// add ground
  135. {
  136. const size = 400;
  137. const geometry = new THREE.PlaneGeometry(size, size);
  138. const material = new THREE.MeshPhongMaterial({color: 'gray'});
  139. const mesh = new THREE.Mesh(geometry, material);
  140. mesh.rotation.x = Math.PI * -0.5;
  141. scene.add(mesh);
  142. }
  143. </pre>
  144. <p>and change the background to light blue</p>
  145. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const scene = new THREE.Scene();
  146. -scene.background = new THREE.Color('white');
  147. +scene.background = new THREE.Color('lightblue');
  148. </pre>
  149. <p>and we get a grid of trees</p>
  150. <p></p><div translate="no" class="threejs_example_container notranslate">
  151. <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/billboard-trees-no-billboards.html"></iframe></div>
  152. <a class="threejs_center" href="/manual/examples/billboard-trees-no-billboards.html" target="_blank">click here to open in a separate window</a>
  153. </div>
  154. <p></p>
  155. <p>There are 11x11 or 121 trees. Each tree is made from a 12 polygon
  156. cone and a 48 polygon trunk so each tree is 60 polygons. 121 * 60
  157. is 7260 polygons. That's not that many but of course a more detailed
  158. 3D tree might be 1000-3000 polygons. If they were 3000 polygons each
  159. then 121 trees would be 363000 polygons to draw.</p>
  160. <p>Using facades we can bring that number down.</p>
  161. <p>We could manually create a facade in some painting program but let's write
  162. some code to try to generate one.</p>
  163. <p>Let's write some code to render an object to a texture
  164. using a <code class="notranslate" translate="no">RenderTarget</code>. We covered rendering to a <code class="notranslate" translate="no">RenderTarget</code>
  165. in <a href="rendertargets.html">the article on render targets</a>.</p>
  166. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">function frameArea(sizeToFitOnScreen, boxSize, boxCenter, camera) {
  167. const halfSizeToFitOnScreen = sizeToFitOnScreen * 0.5;
  168. const halfFovY = THREE.MathUtils.degToRad(camera.fov * .5);
  169. const distance = halfSizeToFitOnScreen / Math.tan(halfFovY);
  170. camera.position.copy(boxCenter);
  171. camera.position.z += distance;
  172. // pick some near and far values for the frustum that
  173. // will contain the box.
  174. camera.near = boxSize / 100;
  175. camera.far = boxSize * 100;
  176. camera.updateProjectionMatrix();
  177. }
  178. function makeSpriteTexture(textureSize, obj) {
  179. const rt = new THREE.WebGLRenderTarget(textureSize, textureSize);
  180. const aspect = 1; // because the render target is square
  181. const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
  182. scene.add(obj);
  183. // compute the box that contains obj
  184. const box = new THREE.Box3().setFromObject(obj);
  185. const boxSize = box.getSize(new THREE.Vector3());
  186. const boxCenter = box.getCenter(new THREE.Vector3());
  187. // set the camera to frame the box
  188. const fudge = 1.1;
  189. const size = Math.max(...boxSize.toArray()) * fudge;
  190. frameArea(size, size, boxCenter, camera);
  191. renderer.autoClear = false;
  192. renderer.setRenderTarget(rt);
  193. renderer.render(scene, camera);
  194. renderer.setRenderTarget(null);
  195. renderer.autoClear = true;
  196. scene.remove(obj);
  197. return {
  198. position: boxCenter.multiplyScalar(fudge),
  199. scale: size,
  200. texture: rt.texture,
  201. };
  202. }
  203. </pre>
  204. <p>Some things to note about the code above:</p>
  205. <p>We're using the field of view (<code class="notranslate" translate="no">fov</code>) defined above this code.</p>
  206. <p>We're computing a box that contains the tree the same way
  207. we did in <a href="load-obj.html">the article on loading a .obj file</a>
  208. with a few minor changes.</p>
  209. <p>We call <code class="notranslate" translate="no">frameArea</code> again adapted <a href="load-obj.html">the article on loading a .obj file</a>.
  210. In this case we compute how far the camera needs to be away from the object
  211. given its field of view to contain the object. We then position the camera -z that distance
  212. from the center of the box that contains the object.</p>
  213. <p>We multiply the size we want to fit by 1.1 (<code class="notranslate" translate="no">fudge</code>) to make sure the tree fits
  214. completely in the render target. The issue here is the size we're using to
  215. calculate if the object fits in the camera's view is not taking into account
  216. that the very edges of the object will end up dipping outside area we
  217. calculated. We could compute how to make 100% of the box fit but that would
  218. waste space as well so instead we just <em>fudge</em> it.</p>
  219. <p>Then we render to the render target and remove the object from
  220. the scene. </p>
  221. <p>It's important to note we need the lights in the scene but we
  222. need to make sure nothing else is in the scene.</p>
  223. <p>We also need to not set a background color on the scene</p>
  224. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const scene = new THREE.Scene();
  225. -scene.background = new THREE.Color('lightblue');
  226. </pre>
  227. <p>Finally we've made the texture we return it and the position and scale we
  228. need to make the facade so that it will appear to be in the same place.</p>
  229. <p>We then make a tree and call this code and pass it in</p>
  230. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">// make billboard texture
  231. const tree = makeTree(0, 0);
  232. const facadeSize = 64;
  233. const treeSpriteInfo = makeSpriteTexture(facadeSize, tree);
  234. </pre>
  235. <p>We can then make a grid of facades instead of a grid of tree models</p>
  236. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">+function makeSprite(spriteInfo, x, z) {
  237. + const {texture, offset, scale} = spriteInfo;
  238. + const mat = new THREE.SpriteMaterial({
  239. + map: texture,
  240. + transparent: true,
  241. + });
  242. + const sprite = new THREE.Sprite(mat);
  243. + scene.add(sprite);
  244. + sprite.position.set(
  245. + offset.x + x,
  246. + offset.y,
  247. + offset.z + z);
  248. + sprite.scale.set(scale, scale, scale);
  249. +}
  250. for (let z = -50; z &lt;= 50; z += 10) {
  251. for (let x = -50; x &lt;= 50; x += 10) {
  252. - makeTree(x, z);
  253. + makeSprite(treeSpriteInfo, x, z);
  254. }
  255. }
  256. </pre>
  257. <p>In the code above we apply the offset and scale needed to position the facade so it
  258. appears the same place the original tree would have appeared.</p>
  259. <p>Now that we're done making the tree facade texture we can set the background again</p>
  260. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">scene.background = new THREE.Color('lightblue');
  261. </pre>
  262. <p>and now we get a scene of tree facades</p>
  263. <p></p><div translate="no" class="threejs_example_container notranslate">
  264. <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/billboard-trees-static-billboards.html"></iframe></div>
  265. <a class="threejs_center" href="/manual/examples/billboard-trees-static-billboards.html" target="_blank">click here to open in a separate window</a>
  266. </div>
  267. <p></p>
  268. <p>Compare to the trees models above and you can see it looks fairly similar.
  269. We used a low-res texture, just 64x64 pixels so the facades are blocky.
  270. You could increase the resolution. Often facades are used only in the far
  271. distance when they are fairly small so a low-res texture is enough and
  272. it saves on drawing detailed trees that are only a few pixels big when
  273. far away.</p>
  274. <p>Another issue is we are only viewing the tree from one side. This is often
  275. solved by rendering more facades, say from 8 directions around the object
  276. and then setting which facade to show based on which direction the camera
  277. is looking at the facade.</p>
  278. <p>Whether or not you use facades is up to you but hopefully this article
  279. gave you some ideas and suggested some solutions if you decide to use them.</p>
  280. </div>
  281. </div>
  282. </div>
  283. <script src="../resources/prettify.js"></script>
  284. <script src="../resources/lesson.js"></script>
  285. </body></html>