transparency.html 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. Title: Three.js Transparency
  2. Description: How to deal with transparency issues in THREE.js
  3. TOC: How to Draw Transparent Objects
  4. Transparency in three.js is both easy and hard.
  5. First we'll go over the easy part. Let's make a
  6. scene with 8 cubes placed in a 2x2x2 grid.
  7. We'll start with the example from
  8. [the article on rendering on demand](threejs-rendering-on-demand.html)
  9. which had 3 cubes and modify it to have 8. First
  10. let's change our `makeInstance` function to take
  11. an x, y, and z
  12. ```js
  13. -function makeInstance(geometry, color) {
  14. +function makeInstance(geometry, color, x, y, z) {
  15. const material = new THREE.MeshPhongMaterial({color});
  16. const cube = new THREE.Mesh(geometry, material);
  17. scene.add(cube);
  18. - cube.position.x = x;
  19. + cube.position.set(x, y, z);
  20. return cube;
  21. }
  22. ```
  23. Then we can create 8 cubes
  24. ```js
  25. +function hsl(h, s, l) {
  26. + return (new THREE.Color()).setHSL(h, s, l);
  27. +}
  28. -makeInstance(geometry, 0x44aa88, 0);
  29. -makeInstance(geometry, 0x8844aa, -2);
  30. -makeInstance(geometry, 0xaa8844, 2);
  31. +{
  32. + const d = 0.8;
  33. + makeInstance(geometry, hsl(0 / 8, 1, .5), -d, -d, -d);
  34. + makeInstance(geometry, hsl(1 / 8, 1, .5), d, -d, -d);
  35. + makeInstance(geometry, hsl(2 / 8, 1, .5), -d, d, -d);
  36. + makeInstance(geometry, hsl(3 / 8, 1, .5), d, d, -d);
  37. + makeInstance(geometry, hsl(4 / 8, 1, .5), -d, -d, d);
  38. + makeInstance(geometry, hsl(5 / 8, 1, .5), d, -d, d);
  39. + makeInstance(geometry, hsl(6 / 8, 1, .5), -d, d, d);
  40. + makeInstance(geometry, hsl(7 / 8, 1, .5), d, d, d);
  41. +}
  42. ```
  43. I also adjusted the camera
  44. ```js
  45. const fov = 75;
  46. const aspect = 2; // the canvas default
  47. const near = 0.1;
  48. -const far = 5;
  49. +const far = 25;
  50. const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
  51. -camera.position.z = 4;
  52. +camera.position.z = 2;
  53. ```
  54. Set the background to white
  55. ```js
  56. const scene = new THREE.Scene();
  57. +scene.background = new THREE.Color('white');
  58. ```
  59. And added a second light so all sides of the cubes get some lighting.
  60. ```js
  61. -{
  62. +function addLight(...pos) {
  63. const color = 0xFFFFFF;
  64. const intensity = 1;
  65. const light = new THREE.DirectionalLight(color, intensity);
  66. - light.position.set(-1, 2, 4);
  67. + light.position.set(...pos);
  68. scene.add(light);
  69. }
  70. +addLight(-1, 2, 4);
  71. +addLight( 1, -1, -2);
  72. ```
  73. To make the cubes transparent we just need to set the
  74. [`transparent`](Material.transparent) flag and to set an
  75. [`opacity`](Material.opacity) level with 1 being completely opaque
  76. and 0 being completely transparent.
  77. ```js
  78. function makeInstance(geometry, color, x, y, z) {
  79. - const material = new THREE.MeshPhongMaterial({color});
  80. + const material = new THREE.MeshPhongMaterial({
  81. + color,
  82. + opacity: 0.5,
  83. + transparent: true,
  84. + });
  85. const cube = new THREE.Mesh(geometry, material);
  86. scene.add(cube);
  87. cube.position.set(x, y, z);
  88. return cube;
  89. }
  90. ```
  91. and with that we get 8 transparent cubes
  92. {{{example url="../threejs-transparency.html"}}}
  93. Drag on the example to rotate the view.
  94. So it seems easy but ... look closer. The cubes are
  95. missing their backs.
  96. <div class="threejs_center"><img src="resources/images/transparency-cubes-no-backs.png" style="width: 416px;"></div>
  97. <div class="threejs_center">no backs</div>
  98. We learned about the [`side`](Material.side) material property in
  99. [the article on materials](threejs-materials.html).
  100. So, let's set it to `THREE.DoubleSide` to get both sides of each cube to be drawn.
  101. ```js
  102. const material = new THREE.MeshPhongMaterial({
  103. color,
  104. map: loader.load(url),
  105. opacity: 0.5,
  106. transparent: true,
  107. + side: THREE.DoubleSide,
  108. });
  109. ```
  110. And we get
  111. {{{example url="../threejs-transparency-doubleside.html" }}}
  112. Give it a spin. It kind of looks like it's working as we can see backs
  113. except on closer inspection sometimes we can't.
  114. <div class="threejs_center"><img src="resources/images/transparency-cubes-some-backs.png" style="width: 368px;"></div>
  115. <div class="threejs_center">the left back face of each cube is missing</div>
  116. This happens because of the way 3D objects are generally drawn. For each geometry
  117. each triangle is drawn one at a time. When each pixel of the triangle is drawn
  118. 2 things are recorded. One, the color for that pixel and two, the depth of that pixel.
  119. When the next triangle is drawn, for each pixel if the depth is deeper than the
  120. previously recorded depth no pixel is drawn.
  121. This works great for opaque things but it fails for transparent things.
  122. The solution is to sort transparent things and draw the stuff in back before
  123. drawing the stuff in front. THREE.js does this for objects like `Mesh` otherwise
  124. the very first example would have failed between cubes with some cubes blocking
  125. out others. Unfortunately for individual triangles shorting would be extremely slow.
  126. The cube has 12 triangles, 2 for each face, and the order they are drawn is
  127. [the same order they are built in the geometry](threejs-custom-buffergeometry.html)
  128. so depending on which direction we are looking the triangles closer to the camera
  129. might get drawn first. In that case the triangles in the back aren't drawn.
  130. This is why sometimes we don't see the backs.
  131. For a convex object like a sphere or a cube one kind of solution is to add
  132. every cube to the scene twice. Once with a material that draws
  133. only the back facing triangles and another with a material that only
  134. draws the front facing triangles.
  135. ```js
  136. function makeInstance(geometry, color, x, y, z) {
  137. + [THREE.BackSide, THREE.FrontSide].forEach((side) => {
  138. const material = new THREE.MeshPhongMaterial({
  139. color,
  140. opacity: 0.5,
  141. transparent: true,
  142. + side,
  143. });
  144. const cube = new THREE.Mesh(geometry, material);
  145. scene.add(cube);
  146. cube.position.set(x, y, z);
  147. + });
  148. }
  149. ```
  150. Any with that it *seems* to work.
  151. {{{example url="../threejs-transparency-doubleside-hack.html" }}}
  152. It assumes that the three.js's sorting is stable. Meaning that because we
  153. added the `side: THREE.BackSide` mesh first and because it's at the exact same
  154. position that it will be drawn before the `side: THREE.FrontSide` mesh.
  155. Let's make 2 intersecting planes (after deleting all the code related to cubes).
  156. We'll [add a texture](threejs-textures.html) to each plane.
  157. ```js
  158. const planeWidth = 1;
  159. const planeHeight = 1;
  160. const geometry = new THREE.PlaneGeometry(planeWidth, planeHeight);
  161. const loader = new THREE.TextureLoader();
  162. function makeInstance(geometry, color, rotY, url) {
  163. const texture = loader.load(url, render);
  164. const material = new THREE.MeshPhongMaterial({
  165. color,
  166. map: texture,
  167. opacity: 0.5,
  168. transparent: true,
  169. side: THREE.DoubleSide,
  170. });
  171. const mesh = new THREE.Mesh(geometry, material);
  172. scene.add(mesh);
  173. mesh.rotation.y = rotY;
  174. }
  175. makeInstance(geometry, 'pink', 0, 'resources/images/happyface.png');
  176. makeInstance(geometry, 'lightblue', Math.PI * 0.5, 'resources/images/hmmmface.png');
  177. ```
  178. This time we can use `side: THREE.DoubleSide` since we can only ever see one
  179. side of a plane at a time. Also note we pass our `render` function to the texture
  180. loading function so that when the texture finishes loading we re-render the scene.
  181. This is because this sample is [rendering on demand](threejs-rendering-on-demand.html)
  182. instead of rendering continuously.
  183. {{{example url="../threejs-transparency-intersecting-planes.html"}}}
  184. And again we see a similar issue.
  185. <div class="threejs_center"><img src="resources/images/transparency-planes.png" style="width: 408px;"></div>
  186. <div class="threejs_center">half a face is missing</div>
  187. The solution here is to manually split the each pane into 2 panes
  188. so that there really is no intersection.
  189. ```js
  190. function makeInstance(geometry, color, rotY, url) {
  191. + const base = new THREE.Object3D();
  192. + scene.add(base);
  193. + base.rotation.y = rotY;
  194. + [-1, 1].forEach((x) => {
  195. const texture = loader.load(url, render);
  196. + texture.offset.x = x < 0 ? 0 : 0.5;
  197. + texture.repeat.x = .5;
  198. const material = new THREE.MeshPhongMaterial({
  199. color,
  200. map: texture,
  201. opacity: 0.5,
  202. transparent: true,
  203. side: THREE.DoubleSide,
  204. });
  205. const mesh = new THREE.Mesh(geometry, material);
  206. - scene.add(mesh);
  207. + base.add(mesh);
  208. - mesh.rotation.y = rotY;
  209. + mesh.position.x = x * .25;
  210. });
  211. }
  212. ```
  213. How you accomplish that is up to you. If I was using modeling package like
  214. [Blender](https://blender.org) I'd probably do this manually by adjusting
  215. texture coordinates. Here though we're using `PlaneGeometry` which by
  216. default stretches the texture across the plane. Like we [covered
  217. before](threejs-textures.html) By setting the [`texture.repeat`](Texture.repeat)
  218. and [`texture.offset`](Texture.offset) we can scale and move the texture to get
  219. the correct half of the face texture on each plane.
  220. The code above also makes a `Object3D` and parents the 2 planes to it.
  221. It seemed easier to rotate a parent `Object3D` than to do the math
  222. required do it without.
  223. {{{example url="../threejs-transparency-intersecting-planes-fixed.html"}}}
  224. This solution really only works for simple things like 2 planes that
  225. are not changing their intersection position.
  226. For textured objects one more solution is to set an alpha test.
  227. An alpha test is a level of *alpha* below which three.js will not
  228. draw the pixel. If we don't draw a pixel at all then the depth
  229. issues mentioned above disappear. For relatively sharp edged textures
  230. this works pretty well. Examples include leaf textures on a plant or tree
  231. or often a patch of grass.
  232. Let's try on the 2 planes. First let's use different textures.
  233. The textures above were 100% opaque. These 2 use transparency.
  234. <div class="spread">
  235. <div><img class="checkerboard" src="../resources/images/tree-01.png"></div>
  236. <div><img class="checkerboard" src="../resources/images/tree-02.png"></div>
  237. </div>
  238. Going back to the 2 planes that intersect (before we split them) let's
  239. use these textures and set an [`alphaTest`](Material.alphaTest).
  240. ```js
  241. function makeInstance(geometry, color, rotY, url) {
  242. const texture = loader.load(url, render);
  243. const material = new THREE.MeshPhongMaterial({
  244. color,
  245. map: texture,
  246. - opacity: 0.5,
  247. transparent: true,
  248. + alphaTest: 0.5,
  249. side: THREE.DoubleSide,
  250. });
  251. const mesh = new THREE.Mesh(geometry, material);
  252. scene.add(mesh);
  253. mesh.rotation.y = rotY;
  254. }
  255. -makeInstance(geometry, 'pink', 0, 'resources/images/happyface.png');
  256. -makeInstance(geometry, 'lightblue', Math.PI * 0.5, 'resources/images/hmmmface.png');
  257. +makeInstance(geometry, 'white', 0, 'resources/images/tree-01.png');
  258. +makeInstance(geometry, 'white', Math.PI * 0.5, 'resources/images/tree-02.png');
  259. ```
  260. Before we run this let's add a small UI so we can more easily play with the `alphaTest`
  261. and `transparent` settings. We'll use dat.gui like we introduced
  262. in the [article on three.js's scenegraph](threejs-scenegraph.html).
  263. First we'll make a helper for dat.gui that sets every material in the scene
  264. to a value
  265. ```js
  266. class AllMaterialPropertyGUIHelper {
  267. constructor(prop, scene) {
  268. this.prop = prop;
  269. this.scene = scene;
  270. }
  271. get value() {
  272. const {scene, prop} = this;
  273. let v;
  274. scene.traverse((obj) => {
  275. if (obj.material && obj.material[prop] !== undefined) {
  276. v = obj.material[prop];
  277. }
  278. });
  279. return v;
  280. }
  281. set value(v) {
  282. const {scene, prop} = this;
  283. scene.traverse((obj) => {
  284. if (obj.material && obj.material[prop] !== undefined) {
  285. obj.material[prop] = v;
  286. obj.material.needsUpdate = true;
  287. }
  288. });
  289. }
  290. }
  291. ```
  292. Then we'll add the gui
  293. ```js
  294. const gui = new GUI();
  295. gui.add(new AllMaterialPropertyGUIHelper('alphaTest', scene), 'value', 0, 1)
  296. .name('alphaTest')
  297. .onChange(requestRenderIfNotRequested);
  298. gui.add(new AllMaterialPropertyGUIHelper('transparent', scene), 'value')
  299. .name('transparent')
  300. .onChange(requestRenderIfNotRequested);
  301. ```
  302. and of course we need to include dat.gui
  303. ```js
  304. import * as THREE from './resources/three/r132/build/three.module.js';
  305. import {OrbitControls} from './resources/threejs/r132/examples/jsm/controls/OrbitControls.js';
  306. +import {GUI} from '../3rdparty/dat.gui.module.js';
  307. ```
  308. and here's the results
  309. {{{example url="../threejs-transparency-intersecting-planes-alphatest.html"}}}
  310. You can see it works but zoom in and you'll see one plane has white lines.
  311. <div class="threejs_center"><img src="resources/images/transparency-alphatest-issues.png" style="width: 532px;"></div>
  312. This is the same depth issue from before. That plane was drawn first
  313. so the plane behind is not drawn. There is no perfect solution.
  314. Adjust the `alphaTest` and/or turn off `transparent` to find a solution
  315. that fits your use case.
  316. The take way from this article is perfect transparency is hard.
  317. There are issues and trade offs and workarounds.
  318. For example say you have a car.
  319. Cars usually have windshields on all 4 sides. If you want to avoid the sorting issues
  320. above you'd have to make each window its own object so that three.js can
  321. sort the windows and draw them in the correct order.
  322. If you are making some plants or grass the alpha test solution is common.
  323. Which solution you pick depends on your needs.