language
stringclasses
1 value
owner
stringlengths
2
15
repo
stringlengths
2
21
sha
stringlengths
45
45
message
stringlengths
7
36.3k
path
stringlengths
1
199
patch
stringlengths
15
102k
is_multipart
bool
2 classes
Other
mrdoob
three.js
941f0233db0d0dc42ddc0c5900abadbaa247769d.json
Fix typos in setup article
threejs/lessons/threejs-setup.md
@@ -7,16 +7,16 @@ If you haven't read that yet you might want to start there. Before we go any further we need to talk about setting up your computer to do developement. In particular, for security reasons, -WebGL can not use images from your hard drive directly. That means +WebGL cannot use images from your hard drive directly. That means in order to do development you need to use a web server. Fortunately -development webservers are super easy to setup and use. +development web servers are super easy to setup and use. First off if you'd like you can download this entire site from [this link](https://github.com/greggman/threejsfundamentals/archive/gh-pages.zip). Once downloaded double click the zip file to unpack the files. -Next download one of these simple web servers +Next download one of these simple web servers. -If you'd prefer a web server with a user interface there's +If you'd prefer a web server with a user interface there's [Servez](https://greggman.github.io/servez) {{{image url="resources/servez.gif" className="border" }}} @@ -50,7 +50,7 @@ Then in your browser go to [`http://localhost:8080/`](http://localhost:8080/). If you don't specify a path then http-server will serve the current folder. -If either of those options are not to your liking +If either of those options are not to your liking [there are many other simple servers to choose from](https://stackoverflow.com/questions/12905426/what-is-a-faster-alternative-to-pythons-http-server-or-simplehttpserver). Now that you have a server setup we can move on to [textures](threejs-textures.html).
false
Other
mrdoob
three.js
eb6e93e132a47998171c5e2caf9b03ea001fcf15.json
Fix typos in materials article
threejs/lessons/threejs-materials.md
@@ -5,8 +5,8 @@ This article is part of a series of articles about three.js. The first article is [three.js fundamentals](threejs-fundamentals.html). If you haven't read that yet and you're new to three.js you might want to consider starting there. - -Three.js provides several types of materials. + +Three.js provides several types of materials. They define how objects will appear in the scene. Which materials you use really depends on what you're trying to accomplish. @@ -33,12 +33,12 @@ note that properties of type `THREE.Color` have multiple ways to be set. ```js material.color.set(0x00FFFF); // same as CSS's #RRGGBB style -material.color.set(cssString); // any CSS color, eg 'purple', '#F32', +material.color.set(cssString); // any CSS color, eg 'purple', '#F32', // 'rgb(255, 127, 64)', // 'hsl(180, 50%, 25%)' material.color.set(someColor) // some other THREE.Color material.color.setHSL(h, s, l) // where h, s, and l are 0 to 1 -material.color.setRGB(r, g, b) // where r, g, and b are 0 to 1 +material.color.setRGB(r, g, b) // where r, g, and b are 0 to 1 ``` And at creation time you can pass either a hex number or a CSS string @@ -53,7 +53,7 @@ const m5 = new THREE.MeshBasicMaterial({color: 'hsl(0,100%,50%)'); // red So let's go over three.js's set of materials. -The `MeshBasicMaterial` is not affected by lights. +The `MeshBasicMaterial` is not affected by lights. The `MeshLambertMaterial` computes lighting only at the vertices vs the `MeshPhongMaterial` which computes lighting at every pixel. The `MeshPhongMaterial` also supports specular highlights. @@ -101,7 +101,7 @@ The `shininess` setting of the `MeshPhongMaterial` determines the *shininess* of </div> </div> -Note that setting the `emissive` property to a color on either a +Note that setting the `emissive` property to a color on either a `MeshLambertMaterial` or a `MeshPhongMaterial` and setting the `color` to black (and `shininess` to 0 for phong) ends up looking just like the `MeshBasicMaterial`. @@ -141,7 +141,7 @@ don't need the extra features then use the simplest material. If you don't need the lighting and the specular highlight then use the `MeshBasicMaterial`. The `MeshToonMaterial` is similar to the `MeshPhongMaterial` -with one big difference. Rather than shading smoothly it uses a gradient map +with one big difference. Rather than shading smoothly it uses a gradient map (an X by 1 texture) to decide how to shade. The default uses a gradient map that is 70% brightness for the first 70% and 100% after but you can supply your own gradient map. This ends up giving a 2 tone look that looks like a cartoon. @@ -163,8 +163,8 @@ The first one is `MeshStandardMaterial`. The biggest difference between settings `roughness` and `metalness`. At a basic level [`roughness`](MeshStandardMaterial.roughness) is the opposite -of `shininess`. Something that has a high roughness, like a baseball doesn't -have hard reflections where as something that's not rough, like a billiard ball +of `shininess`. Something that has a high roughness, like a baseball doesn't +have hard reflections whereas something that's not rough, like a billiard ball, is very shiny. Roughness goes from 0 to 1. The other setting, [`metalness`](MeshStandardMaterial.metalness), says @@ -177,7 +177,7 @@ across and `metalness` from 0 to 1 down. <div data-diagram="MeshStandardMaterial" style="min-height: 400px"></div> The `MeshPhysicalMaterial` is same as the `MeshStandardMaterial` but it -adds a `clearCoat` parameter that goes from 0 to 1 for how much to +adds a `clearCoat` parameter that goes from 0 to 1 for how much to apply a clearcoat gloss layer and a `clearCoatRoughness` parameter that specifies how rough the gloss layer is. @@ -187,15 +187,15 @@ Here's the same grid of `roughness` by `metalness` as above but with <div data-diagram="MeshPhysicalMaterial" style="min-height: 400px"></div> The various standard materials progress from fastest to slowest -`MeshBasicMaterial` ➡ `MeshLambertMaterial` ➡ `MeshPhongMaterial` ➡ +`MeshBasicMaterial` ➡ `MeshLambertMaterial` ➡ `MeshPhongMaterial` ➡ `MeshStandardMaterial` ➡ `MeshPhysicalMaterial`. The slower materials can make more realistic looking scenes but you might need to design your code to use the faster materials on low powered or mobile machines. There are 3 materials that have special uses. `ShadowMaterial` is used to get the data created from shadows. We haven't covered shadows yet. When we do we'll use this material -to take a peak at what's happening behind the scenes. +to take a peek at what's happening behind the scenes. The `MeshDepthMaterial` renders the depth of each pixel where pixels at negative [`near`](PerspectiveCamera.near) of the camera are 0 and negative [`far`](PerspectiveCamera.far) are 1. Certain special effects can use this data which we'll @@ -208,8 +208,8 @@ get into at another time. </div> The `MeshNormalMaterial` will show you the *normals* of geometry. -*Normals* are the direction a particular triangle or pixel faces. -`MeshNormalMaterial` draws the view space normals. (the normals relative to the camera). +*Normals* are the direction a particular triangle or pixel faces. +`MeshNormalMaterial` draws the view space normals (the normals relative to the camera). <span class="color:red;">x is red</span>, <span class="color:green;">y is green</span>, and <span class="color:blue;">z is blue</span> so things facing @@ -221,7 +221,7 @@ to the right will be red, up will be green, and toward the screen will be blue. </div> </div> -`ShaderMaterial` is for making custom materials using three.js shader +`ShaderMaterial` is for making custom materials using the three.js shader system. `RawShaderMaterial` is for making entirely custom shaders with no help from three.js. Both of these topics are large and will be covered later. @@ -231,7 +231,7 @@ Most materials share a bunch of settings all defined by `Material`. for all of them but let's go over two of the most commonly used properties. -[`flatShading`](Material.flatShading): +[`flatShading`](Material.flatShading): whether or not the object looks faceted or smooth. default = `false`. <div class="spread"> @@ -268,14 +268,14 @@ Here are 6 planes drawn with `THREE.FrontSide` and `THREE.DoubleSide`. There's really a lot to consider with materials and we actually still have a bunch more to go. In particular we've mostly ignored textures which open up a whole slew of options. Before we cover textures though -we need to take a break and cover +we need to take a break and cover [setting up your development environment](threejs-setup.html) <div class="threejs_bottombar"> <h3>material.needsUpdate</h3> <p> This topic rarely affects most three.js apps but just as an FYI... -Three.js applies material settings when a material is used where "used" +Three.js applies material settings when a material is used where "used" means "something is rendered that uses the material". Some material settings are only applied once as changing them requires lots of work by three.js. In those cases you need to set <code>material.needsUpdate = true</code> to tell @@ -285,10 +285,10 @@ using the material are: </p> <ul> <li><code>flatShading</code></li> - <li>adding or removing a texture. + <li>adding or removing a texture <p> - Changing a texture is ok, but if want switch from using no texture - to using a texture or from using a texture to using no texture + Changing a texture is ok, but if want to switch from using no texture + to using a texture or from using a texture to using no texture then you need to set <code>needsUpdate = true</code>. </p> <p>In the case of going from texture to no-texture it is often
false
Other
mrdoob
three.js
393bb5838e519dca89e1f9c9c67163db99a7d826.json
Fix typos in scene graph article
threejs/lessons/threejs-scenegraph.md
@@ -1,9 +1,9 @@ -Title: Three.js Scenegraph +Title: Three.js Scene Graph Description: What's a scene graph? This article is part of a series of articles about three.js. The first article is [three.js fundamentals](threejs-fundamentals.html). If -you haven't read yet you might want to consider starting there. +you haven't read that yet you might want to consider starting there. Three.js's core is arguably its scene graph. A scene graph in a 3D engine is a hierarchy of nodes in a graph where each node represents @@ -34,18 +34,18 @@ in the Earth's "local space" even though relative to the sun you are spinning around the earth at around 1000 miles per hour and around the sun at around 67,000 miles per hour. Your position in the solar system is similar to that of the moon above but you don't have to concern -yourself. You just worry about your position relative to the earth its +yourself. You just worry about your position relative to the earth in its "local space". Let's take it one step at a time. Imagine we want to make a diagram of the sun, earth, and moon. We'll start with the sun by just making a sphere and putting it at the origin. Note: We're using -sun, earth, moon as a demonstration of how to use a scenegraph. Of course +sun, earth, moon as a demonstration of how to use a scene graph. Of course the real sun, earth, and moon use physics but for our purposes we'll -fake it with a scenegraph. +fake it with a scene graph. ```js -// an array of objects who's rotation to update +// an array of objects whose rotation to update const objects = []; // use just one sphere for everything @@ -86,11 +86,11 @@ represents light that eminates from a single point. ``` To make it easy to see we're going to put the camera directly above the origin -looking down. The easist way to do that us to use the `lookAt` function. The `lookAt` -function will orient the camera from its position to "lookAt the position +looking down. The easist way to do that is to use the `lookAt` function. The `lookAt` +function will orient the camera from its position to "look at" the position we pass to `lookAt`. Before we do that though we need to tell the camera which way the top of the camera is facing or rather which way is "up" for the -camera. For most situations positive Y being up is good enough but since +camera. For most situations positive Y being up is good enough but since we are looking straight down we need to tell the camera that positive Z is up. ```js @@ -139,7 +139,7 @@ going around the sun. Let's make the earth a child of the sun ```js -scene.add(earthMesh); +sunMesh.add(earthMesh); -``` +``` and... @@ -182,7 +182,7 @@ earthMesh.position.x = 10; objects.push(earthMesh); ``` -Here we made a `Object3D`. Like a `Mesh` it is also a node in the scene graph +Here we made an `Object3D`. Like a `Mesh` it is also a node in the scene graph but unlike a `Mesh` it has no material or geometry. It just represents a local space. Our new scene graph looks like this @@ -223,7 +223,7 @@ objects.push(earthMesh); +objects.push(moonMesh); ``` -Again we added another invisible scene graph node, a `Object3D` called `earthOrbit` +Again we added another invisible scene graph node, an `Object3D` called `earthOrbit` and added both the `earthMesh` and the `moonMesh` to it. The new scene graph looks like this. @@ -264,7 +264,7 @@ all the spheres. Otherwise a sphere might draw over them and cover them up. {{{example url="../threejs-scenegraph-sun-earth-moon-axes.html" }}} -We can see the +We can see the <span style="color:red">x (red)</span> and <span style="color:blue">z (blue)</span> axes. Since we are looking straight down and each of our objects is only rotating around its @@ -273,7 +273,7 @@ y axis we don't see much of the <span style="color:green">y (green)</span> axes. It might be hard to see some of them as there are 2 pairs of overlapping axes. Both the `sunMesh` and the `solarSystem` are at the same position. Similarly the `earthMesh` and `earthOrbit` are at the same position. Let's add some simple controls to allow us -to turn them on/off for each node. +to turn them on/off for each node. While we're at it let's also add another helper called the `GridHelper`. It makes a 2D grid on the X,Z plane. By default the grid is 10x10 units. @@ -307,7 +307,7 @@ some function to add the helpers for each node +makeAxisGrid(moonMesh, 'moonMesh'); ``` -`makeAxisGrid` makes a `AxisGridHelper` which is class we'll create +`makeAxisGrid` makes an `AxisGridHelper` which is a class we'll create to make dat.GUI happy. Like it says above dat.GUI will automagically make a UI that manipulates the named property of some object. It will create a different UI depending on the type @@ -322,7 +322,7 @@ the visible property of both the `AxesHelper` and `GridHelper` for a node. // Turns both axes and grid visible on/off // dat.GUI requires a property that returns a bool // to decide to make a checkbox so we make a setter -// can getter for `visible` which we can tell dat.GUI +// and getter for `visible` which we can tell dat.GUI // to look at. class AxisGridHelper { constructor(node, units = 10) { @@ -377,15 +377,15 @@ Another example is a human in a game world. You can see the scene graph gets pretty complex for a human. In fact that scene graph above is simplified. For example you might extend it -to cover the every finger (at least another 28 nodes) and every toe -(yet another 28 nodes) plus ones for the and jaw, the eyes and maybe more. +to cover every finger (at least another 28 nodes) and every toe +(yet another 28 nodes) plus ones for the face and jaw, the eyes and maybe more. -Let's make one semi-complex scenegraph. We'll make a tank. The tank will have +Let's make one semi-complex scene graph. We'll make a tank. The tank will have 6 wheels and a turret. The tank will follow a path. There will be a sphere that moves around and the tank will target the sphere. Here's the scene graph. The meshes are colored in green, the `Object3D`s in blue, -and the lights in gold, and the cameras in purple. One camera has not been added +the lights in gold, and the cameras in purple. One camera has not been added to the scene graph. <div class="threejs_center"><img src="resources/images/scenegraph-tank.svg" style="width: 800px;"></div> @@ -410,7 +410,7 @@ targetMaterial.emissive.setHSL(time * 10 % 1, 1, .25); targetMaterial.color.setHSL(time * 10 % 1, 1, .25); ``` -For the tank there's an `Object3D` called `tank` which used to move everything +For the tank there's an `Object3D` called `tank` which is used to move everything below it around. The code uses a `SplineCurve` which it can ask for positions along that curve. 0.0 is the start of the curve. 1.0 is the end of the curve. It asks for the current position where it puts the tank. It then asks for a @@ -461,7 +461,7 @@ a child of `targetBob` and just aimed the camera itself it would be inside the target. ```js -// make the targetCameraPivot look at the at the tank +// make the targetCameraPivot look at the tank tank.getWorldPosition(targetPosition); targetCameraPivot.lookAt(targetPosition); ```
false
Other
mrdoob
three.js
db03724dabebb84107fa85bc392d57212f5672aa.json
Fix typos in primitives article
threejs/lessons/threejs-primitives.md
@@ -10,9 +10,9 @@ are generally 3D shapes that are generated at runtime with a bunch of parameters. It's common to use primitives for things like a sphere -for globe or a bunch of boxes to draw a 3D graph. It's +for a globe or a bunch of boxes to draw a 3D graph. It's especially common to use primitives to experiment -and get started with 3D. For the majority if 3D apps +and get started with 3D. For the majority of 3D apps it's more common to have an artist make 3D models in a 3D modeling program. Later in this series we'll cover making and loading data from several 3D modeling @@ -30,19 +30,19 @@ for <code>TextBufferGeometry</code> and <code>TextGeometry</code> respectively.< <div data-primitive="IcosahedronBufferGeometry">An icosahedron (20 sides)</div> <div data-primitive="LatheBufferGeometry">A shape generated by spinning a line. Examples would lamps, bowling pins, candles, candle holders, wine glasses, drinking glasses, etc... You provide the 2d silhouette as series of points and then tell three.js how many subdivisions to make as it spins the silhouette around an axis.</div> <div data-primitive="OctahedronBufferGeometry">An Octahedron (8 sides)</div> -<div data-primitive="ParametricBufferGeometry">A surface generated by providing a function that takes a 2d point from a grid and returns the corresponding 3d point.</div> +<div data-primitive="ParametricBufferGeometry">A surface generated by providing a function that takes a 2D point from a grid and returns the corresponding 3d point.</div> <div data-primitive="PlaneBufferGeometry">A 2D plane</div> <div data-primitive="PolyhedronBufferGeometry">Takes a set of triangles centered around a point and projects them onto a sphere</div> <div data-primitive="RingBufferGeometry">A 2D disc with a hole in the center</div> -<div data-primitive="ShapeBufferGeometry">A 2d outline that gets triangulated</div> +<div data-primitive="ShapeBufferGeometry">A 2D outline that gets triangulated</div> <div data-primitive="SphereBufferGeometry">A sphere</div> -<div data-primitive="TetrahedronBufferGeometry">A terahedron (4 sides)</div> -<div data-primitive="TextBufferGeometry">3D Text generated from a 3D font and a string</div> +<div data-primitive="TetrahedronBufferGeometry">A tetrahedron (4 sides)</div> +<div data-primitive="TextBufferGeometry">3D text generated from a 3D font and a string</div> <div data-primitive="TorusBufferGeometry">A torus (donut)</div> <div data-primitive="TorusKnotBufferGeometry">A torus knot</div> <div data-primitive="TubeBufferGeometry">A circle traced down a path</div> -<div data-primitive="EdgesGeometry">A helper object that takes another geometry as input and generates edges only if the angle between faces is greater than some threshold. For example if you look at the box at the top it shows a line going through each face showing every triangle that makes the box. Using an EdgesGeometry instead the middle lines are removed.</div> -<div data-primitive="WireframeGeometry">Generates geometry that contains one line segment (2 points) per edge in the given geometry. With out this you'd often be missing edges or get extra edges since WebGL generally requires 2 points per line segment. For example if all you had was a single triangle there would only be 3 points. If you tried to draw it using a material with <code>wireframe: true</code> you would only get a single line. Passing that triangle geometry to a <code>WireframeGeometry</code> will generate a new Geometry that has 3 lines segments using 6 points..</div> +<div data-primitive="EdgesGeometry">A helper object that takes another geometry as input and generates edges only if the angle between faces is greater than some threshold. For example if you look at the box at the top it shows a line going through each face showing every triangle that makes the box. Using an <code>EdgesGeometry</code> instead the middle lines are removed.</div> +<div data-primitive="WireframeGeometry">Generates geometry that contains one line segment (2 points) per edge in the given geometry. Without this you'd often be missing edges or get extra edges since WebGL generally requires 2 points per line segment. For example if all you had was a single triangle there would only be 3 points. If you tried to draw it using a material with <code>wireframe: true</code> you would only get a single line. Passing that triangle geometry to a <code>WireframeGeometry</code> will generate a new geometry that has 3 lines segments using 6 points..</div> You might notice of most of them come in pairs of `Geometry` or `BufferGeometry`. The difference between the 2 types is effectively flexibility @@ -72,7 +72,7 @@ based primitives easier to deal with. As an simple example a `BufferGeometry` can not have new vertices easily added. The number of vertices used is decided at creation time, storage is created, and then data for vertices -are filled in. Where as for `Geometry` you can add vertices as you go. +are filled in. Whereas for `Geometry` you can add vertices as you go. We'll go over creating custom geometry in another article. For now let's make an example creating each type of primitive. We'll start @@ -236,7 +236,7 @@ is on the left edge. To work around this we can ask three.js to compute the boun box of the geometry. We can then call the `getCenter` method of the bounding box and pass it our mesh's position object. `getCenter` copies the center of the box into the position. -It also returns the position object so we can call `multiplyScaler(-1)` +It also returns the position object so we can call `multiplyScalar(-1)` to position the entire object such that its center of rotation is at the center of the object. @@ -249,15 +249,15 @@ works in another article](threejs-scenegraph.html). For now it's enough to know that like DOM nodes, children are drawn relative to their parent. By making an `Object3D` and making our mesh a child of that -we can position the `Object3D` where ever we want and still -keep the center offset we set earilier. +we can position the `Object3D` wherever we want and still +keep the center offset we set earlier. If we didn't do this the text would spin off center. {{{example url="../threejs-primitives-text.html" }}} Notice the one on the left is not spinning around its center -where as the one on the right is. +whereas the one on the right is. The other exceptions are the 2 line based examples for `EdgesGeometry` and `WireframeGeometry`. Instead of calling `addSolidGeometry` they call @@ -311,7 +311,7 @@ If you're only drawing a few spheres, like say a single globe for a map of the earth, then a single 10000 triangle sphere is not a bad choice. If on the otherhand you're trying to draw 1000 spheres then 1000 spheres times 10000 triangles each is 10 million triangles. -To animate smoothly you need the browser to draw at 60 frames a +To animate smoothly you need the browser to draw at 60 frames per second so you'd be asking the browser to draw 600 million triangles per second. That's a lot of computing.
false
Other
mrdoob
three.js
4b441cc01d7ca92d99a304ce4a30470ec6048e51.json
Fix typos in responsive design article
threejs/lessons/threejs-responsive.md
@@ -11,18 +11,18 @@ to the page displaying well on different sized displays from desktops to tablets to phones. For three.js there are even more situations to consider. For -example a 3D editor with controls on the left, right, top, or +example, a 3D editor with controls on the left, right, top, or bottom is something we might want to handle. A live diagram in the middle of a document is another example. -The last sample we had used a plain canvas with no css and +The last sample we had used a plain canvas with no CSS and no size ```html <canvas id="c"></canvas> ``` -That canvas defaults to 300x150 css pixels in size. +That canvas defaults to 300x150 CSS pixels in size. In the web platform the recommended way to set the size of something is to use CSS. @@ -43,7 +43,7 @@ html, body { </style> ``` -In HTML the body has a margin of 5px pixels by default so setting the +In HTML the body has a margin of 5 pixels by default so setting the margin to 0 removes the margin. Setting the html and body height to 100% makes them fill the window. Otherwise they are only as large as the content that fills them. @@ -109,7 +109,7 @@ Canvas elements have 2 sizes. One size is the size the canvas is displayed on the page. That's what we set with CSS. The other size is the number of pixels in the canvas itself. This is no different than an image. For example we might have a 128x64 pixel image and using -css we might display as 400x200 pixels. +CSS we might display as 400x200 pixels. ```html <img src="some128x64image.jpg" style="width:400px; height:200px"> @@ -194,13 +194,13 @@ changed. ## Handling HD-DPI displays HD-DPI stands for high-density dot per inch displays. -That's most Mac's now a days and many windows machines +That's most Macs nowadays and many Windows machines as well as pretty much all smartphones. The way this works in the browser is they use -CSS pixels to set the sizes which are suppose to be the same +CSS pixels to set the sizes which are supposed to be the same regardless of how high res the display is. The browser -will the just render text with more detail but the +will just render text with more detail but the same physical size. There are various ways to handle HD-DPI with three.js. @@ -210,7 +210,7 @@ is arguably the most common. Rendering 3D graphics takes a lot of GPU processing power. Mobile GPUs have less power than desktops, at least as of 2018, and yet mobile phones often have very high resolution displays. -The current top of the line phones have a HD-DPI ratio +The current top of the line phones have an HD-DPI ratio of 3x meaning for every one pixel from a non-HD-DPI display those phones have 9 pixels. That means they have to do 9x the rendering. @@ -259,7 +259,7 @@ a screenshot, or reading pixels for GPU picking, for drawing into a 2D canvas, etc... There many many cases where if we use `setPixelRatio` then our actual size will be different than the size we requested and we'll have to guess when to use the size we asked for and when to use the size three.js is actually using. -By doing it oursevles we always know the size being used is the size we requested. +By doing it ourselves we always know the size being used is the size we requested. There is no special case where magic is happening behind the scenes. Here's an example using the code above.
false
Other
mrdoob
three.js
23a43c854d5e8c2f76d8291d1f69ef43ca9831eb.json
Fix typos in fundamentals article
threejs/lessons/threejs-fundamentals.md
@@ -7,15 +7,15 @@ it as easy as possible to get 3D content on a webpage. Three.js is often confused with WebGL since more often than not, but not always, three.js uses WebGL to draw 3D. -[WebGL is a very low-level system that only draws points, lines, and triangles](https://webglfundamentals.org). +[WebGL is a very low-level system that only draws points, lines, and triangles](https://webglfundamentals.org). To do anything useful with WebGL generally requires quite a bit of code and that is where three.js comes in. It handles stuff like scenes, lights, shadows, materials, textures, 3d math, all things that you'd have to write yourself if you were to use WebGL directly. These tutorials assume you already know JavaScript and, for the most part they will use ES6 style. [See here for a -terse list of things you're expected to already know](threejs-prerequisites.html). +terse list of things you're expected to already know](threejs-prerequisites.html). Most browsers that support three.js are auto-updated so most users should be able to run this code. If you'd like to make this code run on really old browsers look into a transpiler like [Babel](http://babel.io). @@ -25,7 +25,7 @@ that can't run three.js. When learning most programming languages the first thing people do is make the computer print `"Hello World!"`. For 3D one of the most common first things to do is to make a 3D cube. -so let's start with "Hello Cube!" +So let's start with "Hello Cube!" The first thing we need is a `<canvas>` tag so @@ -170,7 +170,7 @@ and passing it the scene and the camera renderer.render(scene, camera); ``` -Here's a working exmaple +Here's a working example {{{example url="../threejs-fundamentals.html" }}}
false
Other
mrdoob
three.js
2a8973489f88b80a42988ed9801de9e16126aa6b.json
handle css urls better
threejs/resources/editor.js
@@ -50,17 +50,19 @@ function getPrefix(url) { } function fixCSSLinks(url, source) { - const cssUrlRE = /(url\()(.*?)(\))/g; + const cssUrlRE1 = /(url\(')(.*?)('\))/g; + const cssUrlRE2 = /(url\()(.*?)(\))/g; const prefix = getPrefix(url); function addPrefix(url) { - return url.indexOf('://') < 0 ? (prefix + url) : url; + return url.indexOf('://') < 0 ? `${prefix}/${url}` : url; } function makeFQ(match, prefix, url, suffix) { return `${prefix}${addPrefix(url)}${suffix}`; } - source = source.replace(cssUrlRE, makeFQ); + source = source.replace(cssUrlRE1, makeFQ); + source = source.replace(cssUrlRE2, makeFQ); return source; }
false
Other
mrdoob
three.js
d0c06efc03bfcf0e2286d2b72e80355f5a1ef5b0.json
add react eslint support
.eslintrc.js
@@ -5,8 +5,12 @@ module.exports = { }, "parserOptions": { "ecmaVersion": 8, + "ecmaFeatures": { + "jsx": true + }, }, "plugins": [ + "eslint-plugin-react", "eslint-plugin-html", "eslint-plugin-optional-comma-spacing", "eslint-plugin-one-variable-per-var",
false
Other
mrdoob
three.js
ee56e3f2eee08e59fe02d4640125e754547ecd72.json
add cleanup article
threejs/lessons/threejs-cleanup.md
@@ -0,0 +1,467 @@ +Title: Three.js Cleanup +Description: How to use free memory used by Three.js + +Three.js apps often use lots of memory. A 3D model +might be 1 to 20 meg memory for all of its vertices. +A model might use many textures that even if they are +compressed into jpg files they have to be expanded +to their uncompressed form to use. Each 1024x1024 +texture takes 4 to 6meg of memory. + +Most three.js apps load resources at init time and +then use those resources forever until the page is +closed. But, what if you want to load and change resources +over time? + +Unlike most JavaScript, three.js can not automatically +clean these resources up. The browser will clean them +up if you switch pages but otherwise it's up to you +to manage them. This is an issue of how WebGL is designed +and so three.js has no recourse but to pass on the +responsibility to free resources back to you. + +You free three.js resource this by calling the `dispose` function on +[textures](threejs-textures.html), +[geometries](threejs-primitives.html), and +[materials](threejs-materials.html). + +You could do this manually. At the start you might create +some of these resources + +```js +const boxGeometry = new THREE.BoxBufferGeometry(...); +const boxTexture = textureLoader.load(...); +const boxMaterial = new THREE.MeshPhongMaterial({map: texture}); +``` + +and then when you're done with them you'd free them + +```js +boxGeometry.dispose(); +boxTexture.dispose(); +boxMaterial.dispose(); +``` + +As you use more and more resources that would get more and +more tedious. + +To help remove some of the tedium let's make a class to track +the resources. We'll then ask that class to do the cleanup +for us. + +Here's a first pass at such a class + +```js +class ResourceTracker { + constructor() { + this.resources = new Set(); + } + track(resource) { + if (resource.dispose) { + this.resources.add(resource); + } + return resource; + } + untrack(resource) { + this.resources.delete(resource); + } + dispose() { + for (const resource of this.resources) { + resource.dispose(); + } + this.resources.clear(); + } +} +``` + +Let's use this class with the first example from [the article on textures](threejs-textures.html). +We can create an instance of this class + +```js +const resTracker = new ResourceTracker(); +``` + +and then just to make it easier to use let's create a bound function for the `track` method + +```js +const resTracker = new ResourceTracker(); ++const track = resTracker.track.bind(resTracker); +``` + +Now to use it we just need to call `track` with for each geometry, texture, and material +we create + +```js +const boxWidth = 1; +const boxHeight = 1; +const boxDepth = 1; +-const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth); ++const geometry = track(new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth)); + +const cubes = []; // an array we can use to rotate the cubes +const loader = new THREE.TextureLoader(); + +-const material = new THREE.MeshBasicMaterial({ +- map: loader.load('resources/images/wall.jpg'), +-}); ++const material = track(new THREE.MeshBasicMaterial({ ++ map: track(loader.load('resources/images/wall.jpg')), ++})); +const cube = new THREE.Mesh(geometry, material); +scene.add(cube); +cubes.push(cube); // add to our list of cubes to rotate +``` + +And then to free them we'd want to remove the cubes from the scene +and then call `resTracker.dispose` + +```js +for (const cube of cubes) { + scene.remove(cube); +} +cubes.length = 0; // clears the cubes array +resTracker.dispose(); +``` + +That would work but I find having to remove the cubes from the +scene kind of tedious. Let's add that functionality to the `ResourceTracker`. + +```js +class ResourceTracker { + constructor() { + this.resources = new Set(); + } + track(resource) { +- if (resource.dispose) { ++ if (resource.dispose || resource instanceof THREE.Object3D) { + this.resources.add(resource); + } + return resource; + } + untrack(resource) { + this.resources.delete(resource); + } + dispose() { + for (const resource of this.resources) { +- resource.dispose(); ++ if (resource instanceof THREE.Object3D) { ++ if (resource.parent) { ++ resource.parent.remove(resource); ++ } ++ } ++ if (resource.dispose) { ++ resource.dispose(); ++ } ++ } + this.resources.clear(); + } +} +``` + +And now we can track the cubes + +```js +const material = track(new THREE.MeshBasicMaterial({ + map: track(loader.load('resources/images/wall.jpg')), +})); +const cube = track(new THREE.Mesh(geometry, material)); +scene.add(cube); +cubes.push(cube); // add to our list of cubes to rotate +``` + +We no longer need the code to remove the cubes from the scene. + +```js +-for (const cube of cubes) { +- scene.remove(cube); +-} +cubes.length = 0; // clears the cube array +resTracker.dispose(); +``` + +Let's arrange this code so that we can re-add the cube, +texture, and material. + +```js +const scene = new THREE.Scene(); +*const cubes = []; // just an array we can use to rotate the cubes + ++function addStuffToScene() { + const resTracker = new ResourceTracker(); + const track = resTracker.track.bind(resTracker); + + const boxWidth = 1; + const boxHeight = 1; + const boxDepth = 1; + const geometry = track(new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth)); + + const loader = new THREE.TextureLoader(); + + const material = track(new THREE.MeshBasicMaterial({ + map: track(loader.load('resources/images/wall.jpg')), + })); + const cube = track(new THREE.Mesh(geometry, material)); + scene.add(cube); + cubes.push(cube); // add to our list of cubes to rotate ++ return resTracker; ++} +``` + +And then let's write some code to add and remove things over time. + +```js +function waitSeconds(seconds = 0) { + return new Promise(resolve => setTimeout(resolve, seconds * 1000)); +} + +async function process() { + for (;;) { + const resTracker = addStuffToScene(); + await wait(2); + cubes.length = 0; // remove the cubes + resTracker.dispose(); + await wait(1); + } +} +process(); +``` + +This code will create the cube, texture and material, wait for 2 seconds, then dispose of them and wait for 1 second +and repeat. + +{{{example url="../threejs-cleanup-simple.html" }}} + +So that seems to work. + +For a loaded file though it's a little more work. Most loaders only return an `Object3D` +as a root of the hierarchy of objects they load so we need to discover what all the resources +are. + +Let's update our `ResourceTracker` to try to do that. + +First we'll check if the object is an `Object3D` then track its geometry, material, and children + +```js +class ResourceTracker { + constructor() { + this.resources = new Set(); + } + track(resource) { + if (resource.dispose || resource instanceof THREE.Object3D) { + this.resources.add(resource); + } ++ if (resource instanceof THREE.Object3D) { ++ this.track(resource.geometry); ++ this.track(resource.material); ++ this.track(resource.children); ++ } + return resource; + } + ... +} +``` + +Now, because any of `resource.geometry`, `resource.material`, and `resource.children` +might be null or undefined we'll check at the top of `track`. + +```js +class ResourceTracker { + constructor() { + this.resources = new Set(); + } + track(resource) { ++ if (!resource) { ++ return resource; ++ } + + if (resource.dispose || resource instanceof THREE.Object3D) { + this.resources.add(resource); + } + if (resource instanceof THREE.Object3D) { + this.track(resource.geometry); + this.track(resource.material); + this.track(resource.children); + } + return resource; + } + ... +} +``` + +Also because `resource.children` is an array and because `resource.material` can be +an array let's check for arrays + +```js +class ResourceTracker { + constructor() { + this.resources = new Set(); + } + track(resource) { + if (!resource) { + return resource; + } + ++ // handle children and when material is an array of materials. ++ if (Array.isArray(resource)) { ++ resource.forEach(resource => this.track(resource)); ++ return resource; ++ } + + if (resource.dispose || resource instanceof THREE.Object3D) { + this.resources.add(resource); + } + if (resource instanceof THREE.Object3D) { + this.track(resource.geometry); + this.track(resource.material); + this.track(resource.children); + } + return resource; + } + ... +} +``` + +And finally we need to walk the properties and uniforms +of a material looking for textures. + +```js +class ResourceTracker { + constructor() { + this.resources = new Set(); + } + track(resource) { + if (!resource) { + return resource; + } + +* // handle children and when material is an array of materials or +* // uniform is array of textures + if (Array.isArray(resource)) { + resource.forEach(resource => this.track(resource)); + return resource; + } + + if (resource.dispose || resource instanceof THREE.Object3D) { + this.resources.add(resource); + } + if (resource instanceof THREE.Object3D) { + this.track(resource.geometry); + this.track(resource.material); + this.track(resource.children); +- } ++ } else if (resource instanceof THREE.Material) { ++ // We have to check if there are any textures on the material ++ for (const value of Object.values(resource)) { ++ if (value instanceof THREE.Texture) { ++ this.track(value); ++ } ++ } ++ // We also have to check if any uniforms reference textures or arrays of textures ++ if (resource.uniforms) { ++ for (const value of Object.values(resource.uniforms)) { ++ if (value) { ++ const uniformValue = value.value; ++ if (uniformValue instanceof THREE.Texture || ++ Array.isArray(uniformValue)) { ++ this.track(uniformValue); ++ } ++ } ++ } ++ } ++ } + return resource; + } + ... +} +``` + +And with that let's take an example from [the article on loading gltf files](threejs-load-glft.html) +and make it load and free files. + +```js +const gltfLoader = new THREE.GLTFLoader(); +function loadGLTF(url) { + return new Promise((resolve, reject) => { + gltfLoader.load(url, resolve, undefined, reject); + }); +} + +function waitSeconds(seconds = 0) { + return new Promise(resolve => setTimeout(resolve, seconds * 1000)); +} + +const fileURLs = [ + 'resources/models/cartoon_lowpoly_small_city_free_pack/scene.gltf', + 'resources/models/3dbustchallange_submission/scene.gltf', + 'resources/models/mountain_landscape/scene.gltf', + 'resources/models/simple_house_scene/scene.gltf', +]; + +async function loadFiles() { + for (;;) { + for (const url of fileURLs) { + const resMgr = new ResourceTracker(); + const track = resMgr.track.bind(resMgr); + const gltf = await loadGLTF(url); + const root = track(gltf.scene); + scene.add(root); + + // compute the box that contains all the stuff + // from root and below + const box = new THREE.Box3().setFromObject(root); + + const boxSize = box.getSize(new THREE.Vector3()).length(); + const boxCenter = box.getCenter(new THREE.Vector3()); + + // set the camera to frame the box + frameArea(boxSize * 1.1, boxSize, boxCenter, camera); + + await waitSeconds(2); + renderer.render(scene, camera); + + resMgr.dispose(); + + await waitSeconds(1); + + } + } +} +loadFiles(); +``` + +and we get + +{{{example url="../threejs-cleanup-loaded-files.html"}}} + +Some notes about the code. + +If we wanted to load 2 or more files at once and free them at +anytime we would use one `ResourceTracker` per file. + +Above we are only tracking `gltf.scene` right after loading. +Based on our current implementation of `ResourceTracker` that +will track all the resources just loaded. If we added more +things to the scene we need to decide whether or not to track them. + +For example let's say after we loaded a character we put a tool +in their hand by making the tool a child of their hand. As it is +that tool will not be freed. I'm guessing more often than not +this is what we want. + +That brings up a point. Originally when I first wrote the `ResourceTracker` +above I walked through everything inside the `dispose` method instead of `track`. +It was only later as I thought about the tool as a child of hand case above +that it became clear that tracking exactly what to free in `track` was more +flexible and arguably more correct since we could then track what was loaded +from the file rather than just freeing the state of the scene graph later. + +I honestly am not 100% happy with `ResourceTracker`. Doing things this +way is not common in 3D engines. We shouldn't have to guess what +resources were loaded, we should know. It would be nice if three.js +changed so that all file loaders returned some standard object with +references to all the resources loaded. At least at the moment, +three.js doesn't give us any more info when loading a scene so this +solution seems to work. + +I hope you find this example useful or at least a good reference for what is +required to free resources in three.js
true
Other
mrdoob
three.js
ee56e3f2eee08e59fe02d4640125e754547ecd72.json
add cleanup article
threejs/lessons/toc.html
@@ -21,6 +21,7 @@ <li><a href="/threejs/lessons/threejs-indexed-textures.html">Using Indexed Textures for Picking and Color</a></li> <li><a href="/threejs/lessons/threejs-canvas-textures.html">Using A Canvas for Dynamic Textures</a></li> <li><a href="/threejs/lessons/threejs-billboards.html">Billboards and Facades</a></li> + <li><a href="/threejs/lessons/threejs-cleanup.html">Freeing Resources</a></li> </ul> <li>WebVR</li> <ul>
true
Other
mrdoob
three.js
ee56e3f2eee08e59fe02d4640125e754547ecd72.json
add cleanup article
threejs/threejs-cleanup-loaded-files.html
@@ -0,0 +1,225 @@ +<!-- Licensed under a BSD license. See license.html for license --> +<!DOCTYPE html> +<html> + <head> + <meta charset="utf-8"> + <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes"> + <title>Three.js - Cleanup Loaded Files</title> + <style> + body { + margin: 0; + } + #c { + width: 100vw; + height: 100vh; + display: block; + } + #root { + position: absolute; + left: 0; + top: 0; + } + </style> + </head> + <body> + <canvas id="c"></canvas> + </body> +<script src="resources/threejs/r105/three.min.js"></script> +<script src="resources/threejs/r105/js/loaders/GLTFLoader.js"></script> +<script> + +'use strict'; + +/* global THREE */ + +class ResourceTracker { + constructor() { + this.resources = new Set(); + } + track(resource) { + if (!resource) { + return resource; + } + + // handle children and when material is an array of materials or + // uniform is array of textures + if (Array.isArray(resource)) { + resource.forEach(resource => this.track(resource)); + return resource; + } + + if (resource.dispose || resource instanceof THREE.Object3D) { + this.resources.add(resource); + } + if (resource instanceof THREE.Object3D) { + this.track(resource.geometry); + this.track(resource.material); + this.track(resource.children); + } else if (resource instanceof THREE.Material) { + // We have to check if there are any textures on the material + for (const value of Object.values(resource)) { + if (value instanceof THREE.Texture) { + this.track(value); + } + } + // We also have to check if any uniforms reference textures or arrays of textures + if (resource.uniforms) { + for (const value of Object.values(resource.uniforms)) { + if (value) { + const uniformValue = value.value; + if (uniformValue instanceof THREE.Texture || + Array.isArray(uniformValue)) { + this.track(uniformValue); + } + } + } + } + } + return resource; + } + untrack(resource) { + this.resources.delete(resource); + } + dispose() { + for (const resource of this.resources) { + if (resource instanceof THREE.Object3D) { + if (resource.parent) { + resource.parent.remove(resource); + } + } + if (resource.dispose) { + resource.dispose(); + } + } + this.resources.clear(); + } +} + +function main() { + const canvas = document.querySelector('#c'); + const renderer = new THREE.WebGLRenderer({canvas}); + + const fov = 75; + const aspect = 2; // the canvas default + const near = 0.1; + const far = 5; + const camera = new THREE.PerspectiveCamera(fov, aspect, near, far); + camera.position.z = 2; + + const scene = new THREE.Scene(); + scene.background = new THREE.Color('lightblue'); + + function addLight(...pos) { + const color = 0xFFFFFF; + const intensity = 1; + const light = new THREE.DirectionalLight(color, intensity); + light.position.set(...pos); + scene.add(light); + } + addLight(-1, 2, 4); + addLight( 2, -2, 3); + + function frameArea(sizeToFitOnScreen, boxSize, boxCenter, camera) { + const halfSizeToFitOnScreen = sizeToFitOnScreen * 0.5; + const halfFovY = THREE.Math.degToRad(camera.fov * .5); + const distance = halfSizeToFitOnScreen / Math.tan(halfFovY); + // compute a unit vector that points in the direction the camera is now + // in the xz plane from the center of the box + const direction = (new THREE.Vector3()) + .subVectors(camera.position, boxCenter) + .multiply(new THREE.Vector3(1, 0, 1)) + .normalize(); + + // move the camera to a position distance units way from the center + // in whatever direction the camera was from the center already + camera.position.copy(direction.multiplyScalar(distance).add(boxCenter)); + + // pick some near and far values for the frustum that + // will contain the box. + camera.near = boxSize / 100; + camera.far = boxSize * 100; + + camera.updateProjectionMatrix(); + + // point the camera to look at the center of the box + camera.lookAt(boxCenter.x, boxCenter.y, boxCenter.z); + } + + const gltfLoader = new THREE.GLTFLoader(); + function loadGLTF(url) { + return new Promise((resolve, reject) => { + gltfLoader.load(url, resolve, undefined, reject); + }); + } + + function waitSeconds(seconds = 0) { + return new Promise(resolve => setTimeout(resolve, seconds * 1000)); + } + + const fileURLs = [ + 'resources/models/cartoon_lowpoly_small_city_free_pack/scene.gltf', /* threejsfundamentals: url */ + 'resources/models/3dbustchallange_submission/scene.gltf', /* threejsfundamentals: url */ + 'resources/models/mountain_landscape/scene.gltf', /* threejsfundamentals: url */ + 'resources/models/simple_house_scene/scene.gltf', /* threejsfundamentals: url */ + ]; + + async function loadFiles() { + for (;;) { + for (const url of fileURLs) { + const resMgr = new ResourceTracker(); + const track = resMgr.track.bind(resMgr); + const gltf = await loadGLTF(url); + const root = track(gltf.scene); + scene.add(root); + + // compute the box that contains all the stuff + // from root and below + const box = new THREE.Box3().setFromObject(root); + + const boxSize = box.getSize(new THREE.Vector3()).length(); + const boxCenter = box.getCenter(new THREE.Vector3()); + + // set the camera to frame the box + frameArea(boxSize * 1.1, boxSize, boxCenter, camera); + + await waitSeconds(0); + renderer.render(scene, camera); + + resMgr.dispose(); + + await waitSeconds(0); + + } + } + } + loadFiles(); + + function resizeRendererToDisplaySize(renderer) { + const canvas = renderer.domElement; + const width = canvas.clientWidth; + const height = canvas.clientHeight; + const needResize = canvas.width !== width || canvas.height !== height; + if (needResize) { + renderer.setSize(width, height, false); + } + return needResize; + } + + function render() { + if (resizeRendererToDisplaySize(renderer)) { + const canvas = renderer.domElement; + camera.aspect = canvas.clientWidth / canvas.clientHeight; + camera.updateProjectionMatrix(); + } + + renderer.render(scene, camera); + + requestAnimationFrame(render); + } + + requestAnimationFrame(render); +} + +main(); +</script> +</html>
true
Other
mrdoob
three.js
ee56e3f2eee08e59fe02d4640125e754547ecd72.json
add cleanup article
threejs/threejs-cleanup-simple.html
@@ -0,0 +1,149 @@ +<!-- Licensed under a BSD license. See license.html for license --> +<!DOCTYPE html> +<html> + <head> + <meta charset="utf-8"> + <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes"> + <title>Three.js - Cleanup</title> + <style> + body { + margin: 0; + } + #c { + width: 100vw; + height: 100vh; + display: block; + } + #root { + position: absolute; + left: 0; + top: 0; + } + </style> + </head> + <body> + <canvas id="c"></canvas> + </body> +<script src="resources/threejs/r105/three.min.js"></script> +<script src="resources/threejs/r105/js/loaders/GLTFLoader.js"></script> +<script> + +'use strict'; + +/* global THREE */ + +class ResourceTracker { + constructor() { + this.resources = new Set(); + } + track(resource) { + if (resource.dispose || resource instanceof THREE.Object3D) { + this.resources.add(resource); + } + return resource; + } + untrack(resource) { + this.resources.delete(resource); + } + dispose() { + for (const resource of this.resources) { + if (resource instanceof THREE.Object3D) { + if (resource.parent) { + resource.parent.remove(resource); + } + } + if (resource.dispose) { + resource.dispose(); + } + } + this.resources.clear(); + } +} + +function main() { + const canvas = document.querySelector('#c'); + const renderer = new THREE.WebGLRenderer({canvas}); + + const fov = 75; + const aspect = 2; // the canvas default + const near = 0.1; + const far = 5; + const camera = new THREE.PerspectiveCamera(fov, aspect, near, far); + camera.position.z = 2; + + const scene = new THREE.Scene(); + const cubes = []; // an array we can use to rotate the cubes + + function addStuffToScene() { + const resTracker = new ResourceTracker(); + const track = resTracker.track.bind(resTracker); + + const boxWidth = 1; + const boxHeight = 1; + const boxDepth = 1; + const geometry = track(new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth)); + + const loader = new THREE.TextureLoader(); + + const material = track(new THREE.MeshBasicMaterial({ + map: track(loader.load('resources/images/wall.jpg')), + })); + const cube = track(new THREE.Mesh(geometry, material)); + scene.add(cube); + cubes.push(cube); // add to our list of cubes to rotate + return resTracker; + } + + function waitSeconds(seconds = 0) { + return new Promise(resolve => setTimeout(resolve, seconds * 1000)); + } + + async function process() { + for (;;) { + const resTracker = addStuffToScene(); + await waitSeconds(2); + cubes.length = 0; // remove the cubes + resTracker.dispose(); + await waitSeconds(1); + } + } + process(); + + function resizeRendererToDisplaySize(renderer) { + const canvas = renderer.domElement; + const width = canvas.clientWidth; + const height = canvas.clientHeight; + const needResize = canvas.width !== width || canvas.height !== height; + if (needResize) { + renderer.setSize(width, height, false); + } + return needResize; + } + + function render(time) { + time *= 0.001; + + if (resizeRendererToDisplaySize(renderer)) { + const canvas = renderer.domElement; + camera.aspect = canvas.clientWidth / canvas.clientHeight; + camera.updateProjectionMatrix(); + } + + cubes.forEach((cube, ndx) => { + const speed = .2 + ndx * .1; + const rot = time * speed; + cube.rotation.x = rot; + cube.rotation.y = rot; + }); + + renderer.render(scene, camera); + + requestAnimationFrame(render); + } + + requestAnimationFrame(render); +} + +main(); +</script> +</html>
true
Other
mrdoob
three.js
d31e2a9e40e4e2f121f687980ab33a715ad742b4.json
add leading space for h1,h2 ... lower-contrast for dark mode text
threejs/lessons/resources/lesson.css
@@ -81,6 +81,22 @@ div[data-diagram] { max-width: 700px; width: calc(100% - 40px); } +.lesson-main>h1, +.lesson-main>h2, +.lesson-main>h3, +.lesson-main>h4, +.lesson-main>h5, +.lesson-main>h6 { + margin-top: 1.66em; +} +.lesson-main>h1:first-child, +.lesson-main>h2:first-child, +.lesson-main>h3:first-child, +.lesson-main>h4:first-child, +.lesson-main>h5:first-child, +.lesson-main>h6:first-child { + margin-top: 0.83em; +} .lesson-main>.threejs_example_container { max-width: 90%; } @@ -479,7 +495,7 @@ pre.prettyprint.lighttheme .fun { color: #900; } /* function name */ @media (prefers-color-scheme: dark) { body { background: #333; - color: #EEE; + color: #CCC; } a { color: #56d3fd; @@ -489,7 +505,7 @@ pre.prettyprint.lighttheme .fun { color: #900; } /* function name */ } code { background: #666; - color: #fff; + color: #CCC; } img { background: #DDD;
false
Other
mrdoob
three.js
5032300239fca07d213a48e44a1670ba9112e3a4.json
add offscreencanvas article
threejs/lessons/threejs-offscreencanvas.md
@@ -0,0 +1,1133 @@ +Title: Three.js OffscreenCanvas +Description: How to use three.js in a web worker + +[`OffscreenCanvas`](https://developer.mozilla.org/en-US/docs/Web/API/OffscreenCanvas) +is a relatively new browser feature currently only available in Chrome but apparently +coming to other browsers. `OffscreenCanvas` allows a web worker to render +to a canvas. This is a way to offload heavy work, like rendering a complex 3D scene, +to a web worker so as not to slow down the responsiveness of the browser. It +also means data is loaded and parsed in the worker so possibly less jank while +the page loads. + +Getting *started* using it is pretty straight forward. Let's port the 3 spinning cube +example from [the article on responsiveness](threejs-responsive.html). + +Workers generally have their code separated +into another script file. Most of the examples on this site have had +their scripts embedded into the HTML file of the page they are on. + +In our case we'll make a file called `offscreencanvas-cubes.js` and +copy all the JavaScript from [the responsive example](threejs-responsive.html) into it. We'll then +make the changes needed for it to run in a worker. + +We still need some JavaScript in our HTML file. The first thing +we do there is look up the canvas and then transfer control of that +canvas to be offscreen by calling `canvas.transferControlToOffscreen`. + +```js +function main() { + const canvas = document.querySelector('#c'); + const offscreen = canvas.transferControlToOffscreen(); + + ... +``` + +We can then start our worker with `new Worker(pathToScript)`. +We then pass the `offscreen` object to the worker. + +```js +function main() { + const canvas = document.querySelector('#c'); + const offscreen = canvas.transferControlToOffscreen(); + const worker = new Worker('offscreencanvas-cubes.js'); + worker.postMessage({type: 'main', canvas: offscreen}, [offscreen]); +} +main(); +``` + +It's important to note that workers can't access the `DOM`. They +can't look at HTML elements nor can they receive mouse events or +keyboard events. The only thing they can generally do is respond +to messages sent to them. + +To send a message to a worker we call [`worker.postMessage`](https://developer.mozilla.org/en-US/docs/Web/API/Worker/postMessage) and +pass it 1 or 2 arguments. The first argument is a JavaScript object +that will be [cloned](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm) +and sent to the worker. The second argument is an optional array +of objects that are part of the first object that we want *transferred* +to the worker. These objects will not be cloned. Instead they will be *transferred* +and will cease to exist in the main page. Cease to exist is the probably +the wrong description, rather they are neutered. Only certain types of +objects can be transferred instead of cloned. They include `OffscreenCanvas` +so once transferred the `offscreen` object back in the main page is useless. + +Workers receive messages from their `onmessage` handler. The object +we passed to `postMessage` arrives on `event.data` passed to the `onmessage` +handler on the worker. The code above declares a `type: 'main'` in the object it passes +to the worker. We'll make a handler that based on `type` calls +a different function in the worker. Then we can add functions as +needed and easily call them from the main page. + +```js +const handlers = { + main, +}; + +self.onmessage = function(e) { + const fn = handlers[e.data.type]; + if (!fn) { + throw new Error('no handler for type: ' + e.data.type); + } + fn(e.data); +}; +``` + +You can see above we just look up the handler based on the `type` pass it the `data` +that was sent from the main page. + +So now we just need to start changing the `main` we pasted into +`offscreencanvas-cubes.js` from [the responsive article](threejs-responsive.html). + +The first thing we need to do is include THREE.js into our worker. + +```js +importScripts('https://threejsfundamentals.org/threejs/resources/threejs/r103/three.min.js'); +``` + +Then instead of looking up the canvas from the DOM we'll receive it from the +event data. + +```js +-function main() { +- const canvas = document.querySelector('#c'); ++function main(data) { ++ const {canvas} = data; + const renderer = new THREE.WebGLRenderer({canvas}); + + ... + +``` + +Remembering that workers can't see the DOM at all the first problem +we run into is `resizeRendererToDisplaySize` can't look at `canvas.clientWidth` +and `canvas.clientHeight` as those are DOM values. Here's the original code + +```js +function resizeRendererToDisplaySize(renderer) { + const canvas = renderer.domElement; + const width = canvas.clientWidth; + const height = canvas.clientHeight; + const needResize = canvas.width !== width || canvas.height !== height; + if (needResize) { + renderer.setSize(width, height, false); + } + return needResize; +} +``` + +Instead we'll need to send sizes as they change to the worker. +So, let's add some global state and keep the width and height there. + +```js +const state = { + width: 300, // canvas default + height: 150, // canvas default +}; +``` + +Then let's add a `'size'` handler to update those values. + +```js ++function size(data) { ++ state.width = data.width; ++ state.height = data.height; ++} + +const handlers = { + main, ++ size, +}; +``` + +Now we can change `resizeRendererToDisplaySize` to use `state.width` and `state.height` + +```js +function resizeRendererToDisplaySize(renderer) { + const canvas = renderer.domElement; +- const width = canvas.clientWidth; +- const height = canvas.clientHeight; ++ const width = state.width; ++ const height = state.height; + const needResize = canvas.width !== width || canvas.height !== height; + if (needResize) { + renderer.setSize(width, height, false); + } + return needResize; +} +``` + +and where we compute the aspect we need similar changes + +```js +function render(time) { + time *= 0.001; + + if (resizeRendererToDisplaySize(renderer)) { +- camera.aspect = canvas.clientWidth / canvas.clientHeight; ++ camera.aspect = state.width / state.height; + camera.updateProjectionMatrix(); + } + + ... +``` + +Back in the main page we'll send a `size` event anytime the page changes size. + +```js +const worker = new Worker('offscreencanvas-picking.js'); +worker.postMessage({type: 'main', canvas: offscreen}, [offscreen]); + ++function sendSize() { ++ worker.postMessage({ ++ type: 'size', ++ width: canvas.clientWidth, ++ height: canvas.clientHeight, ++ }); ++} ++ ++window.addEventListener('resize', sendSize); ++sendSize(); +``` + +We also call it once to send the initial size. + +And with just those few changes, assuming your browser fully supports `OffscreenCanvas` +it should work. Before we run it though let's check if the browser actually supports +`OffscreenCanvas` and if not display an error. First let's add some HTML to display the error. + +```html +<body> + <canvas id="c"></canvas> ++ <div id="noOffscreenCanvas" style="display:none;"> ++ <div>no OffscreenCanvas support</div> ++ </div> +</body> +``` + +and some CSS for that + +```css +#noOffscreenCanvas { + display: flex; + width: 100vw; + height: 100vh; + align-items: center; + justify-content: center; + background: red; + color: white; +} +``` + +and then we can check for the existence of `transferControlToOffscreen` to see +if the browser supports `OffscreenCanvas` + +```js +function main() { + const canvas = document.querySelector('#c'); ++ if (!canvas.transferControlToOffscreen) { ++ canvas.style.display = 'none'; ++ document.querySelector('#noOffscreenCanvas').style.display = ''; ++ return; ++ } + const offscreen = canvas.transferControlToOffscreen(); + const worker = new Worker('offscreencanvas-picking.js'); + worker.postMessage({type: 'main', canvas: offscreen}, [offscreen]); + + ... +``` + +and with that, if your browser supports `OffscreenCanvas` this example should work + +{{{example url="../threejs-offscreencanvas.html" }}} + +So that's great but since not every browser supports `OffscreenCanvas` at the moment +let's change the code to work with both `OffscreenCanvas` and if not then fallback to using +the canvas in the main page like normal. + +> As an aside, if you need OffscreenCanvas to make your page responsive then +> it's not clear what the point of having a fallback is. Maybe based on if +> you end up running on the main page or in a worker you might adjust the amount +> of work done so that when running in a worker you can do more than when +> running in the main page. What you do is really up to you. + +The first thing we should probably do is separate out the three.js +code from the code that is specific to the worker. That we we can +use the same code on both the main page and the worker. In other words +we will now have 3 files + +1. our html file. + + `threejs-offscreencanvas-w-fallback.html` + +2. a JavaScript the contains our three.js code. + + `shared-cubes.js` + +3. our worker support code + + `offscreencanvas-worker-cubes.js` + +`shared-cubes.js` and `offscreencanvas-worker-cubes.js` are basically +the split of our previous `offscreencanvas-cubes.js` file. +We renamed `main` to `init` since we already have a `main` in our +HTML file. + +`offscreencanvas-worker-cubes.js` is just + +```js +'use strict'; + +/* global importScripts, init, state */ + +importScripts('resources/threejs/r103/three.min.js'); ++importScripts('shared-cubes.js'); + +function size(data) { + state.width = data.width; + state.height = data.height; +} + +const handlers = { +- main, ++ init, + size, +}; + +self.onmessage = function(e) { + const fn = handlers[e.data.type]; + if (!fn) { + throw new Error('no handler for type: ' + e.data.type); + } + fn(e.data); +}; +``` + +note we include `shared-cubes.js` which is all our three.js code + +Similarly we need to include `shared-cubes.js` in the main page + +```html +<script src="resources/threejs/r103/three.min.js"></script> ++<script src="shared-cubes.js"></script> +``` +We can remove the HTML and CSS we added previously + +```html +<body> + <canvas id="c"></canvas> +- <div id="noOffscreenCanvas" style="display:none;"> +- <div>no OffscreenCanvas support</div> +- </div> +</body> +``` + +and some CSS for that + +```css +-#noOffscreenCanvas { +- display: flex; +- width: 100vw; +- height: 100vh; +- align-items: center; +- justify-content: center; +- background: red; +- color: white; +-} +``` + +Then let's change the code in the main page to call one start +function or another depending on if the browser supports `OffscreenCanvas`. + +```js +function main() { + const canvas = document.querySelector('#c'); +- if (!canvas.transferControlToOffscreen) { +- canvas.style.display = 'none'; +- document.querySelector('#noOffscreenCanvas').style.display = ''; +- return; +- } +- const offscreen = canvas.transferControlToOffscreen(); +- const worker = new Worker('offscreencanvas-picking.js'); +- worker.postMessage({type: 'main', canvas: offscreen}, [offscreen]); ++ if (canvas.transferControlToOffscreen) { ++ startWorker(canvas); ++ } else { ++ startMainPage(canvas); ++ } + ... +``` + +We'll move all the code we had to setup the worker inside `startWorker` + +```js +function startWorker(canvas) { + const offscreen = canvas.transferControlToOffscreen(); + const worker = new Worker('offscreencanvas-worker-cubes.js'); + worker.postMessage({type: 'init', canvas: offscreen}, [offscreen]); + + function sendSize() { + worker.postMessage({ + type: 'size', + width: canvas.clientWidth, + height: canvas.clientHeight, + }); + } + + window.addEventListener('resize', sendSize); + sendSize(); + + console.log('using OffscreenCanvas'); +} +``` + +for starting in the main page we can do this + +```js +function startMainPage(canvas) { + init({canvas}); + + function sendSize() { + state.width = canvas.clientWidth; + state.height = canvas.clientHeight; + } + window.addEventListener('resize', sendSize); + sendSize(); + + console.log('using regular canvas'); +} +``` + +and with that our example will run either in an OffscreenCanvas or +fallback to running in the main page. + +{{{example url="../threejs-offscreencanvas-w-fallback.html" }}} + +So that was relatively easy. Let's try picking. We'll take some code from +the `RayCaster` example from [the article on picking](threejs-picking.html) +and make it work offscreen. + +Let's copy the `shared-cube.js` to `shared-picking.js` and add the +picking parts. We copy in the `PickHelper` + +```js +class PickHelper { + constructor() { + this.raycaster = new THREE.Raycaster(); + this.pickedObject = null; + this.pickedObjectSavedColor = 0; + } + pick(normalizedPosition, scene, camera, time) { + // restore the color if there is a picked object + if (this.pickedObject) { + this.pickedObject.material.emissive.setHex(this.pickedObjectSavedColor); + this.pickedObject = undefined; + } + + // cast a ray through the frustum + this.raycaster.setFromCamera(normalizedPosition, camera); + // get the list of objects the ray intersected + const intersectedObjects = this.raycaster.intersectObjects(scene.children); + if (intersectedObjects.length) { + // pick the first object. It's the closest one + this.pickedObject = intersectedObjects[0].object; + // save its color + this.pickedObjectSavedColor = this.pickedObject.material.emissive.getHex(); + // set its emissive color to flashing red/yellow + this.pickedObject.material.emissive.setHex((time * 8) % 2 > 1 ? 0xFFFF00 : 0xFF0000); + } + } +} + +const pickPosition = {x: 0, y: 0}; +const pickHelper = new PickHelper(); +``` + +We updated `pickPosition` from the mouse like this + +```js +function setPickPosition(event) { + pickPosition.x = (event.clientX / canvas.clientWidth ) * 2 - 1; + pickPosition.y = (event.clientY / canvas.clientHeight) * -2 + 1; // note we flip Y +} +window.addEventListener('mousemove', setPickPosition); +``` + +A worker can't read the mouse position directly so just like the size code +let's send a message with the mouse position. Like the size code we'll +send the mouse position and update `pickPosition` + +```js +function size(data) { + state.width = data.width; + state.height = data.height; +} + ++function mouse(data) { ++ pickPosition.x = data.x; ++ pickPosition.y = data.y; ++} + +const handlers = { + init, ++ mouse, + size, +}; + +self.onmessage = function(e) { + const fn = handlers[e.data.type]; + if (!fn) { + throw new Error('no handler for type: ' + e.data.type); + } + fn(e.data); +}; +``` + +Back in our main page we need to add code to pass the mouse +to the worker or the main page. + +```js ++let sendMouse; + +function startWorker(canvas) { + const offscreen = canvas.transferControlToOffscreen(); + const worker = new Worker('offscreencanvas-worker-picking.js'); + worker.postMessage({type: 'init', canvas: offscreen}, [offscreen]); + ++ sendMouse = (x, y) => { ++ worker.postMessage({ ++ type: 'mouse', ++ x, ++ y, ++ }); ++ }; + + function sendSize() { + worker.postMessage({ + type: 'size', + width: canvas.clientWidth, + height: canvas.clientHeight, + }); + } + + window.addEventListener('resize', sendSize); + sendSize(); + + console.log('using OffscreenCanvas'); /* eslint-disable-line no-console */ +} + +function startMainPage(canvas) { + init({canvas}); + ++ sendMouse = (x, y) => { ++ pickPosition.x = x; ++ pickPosition.y = y; ++ }; + + function sendSize() { + state.width = canvas.clientWidth; + state.height = canvas.clientHeight; + } + window.addEventListener('resize', sendSize); + sendSize(); + + console.log('using regular canvas'); /* eslint-disable-line no-console */ +} + +``` + +Then we can copy in all the mouse handling code to the main page and +make just minor changes to use `sendMouse` + +```js +function setPickPosition(event) { +- pickPosition.x = (event.clientX / canvas.clientWidth ) * 2 - 1; +- pickPosition.y = (event.clientY / canvas.clientHeight) * -2 + 1; // note we flip Y ++ sendMouse( ++ (event.clientX / canvas.clientWidth ) * 2 - 1, ++ (event.clientY / canvas.clientHeight) * -2 + 1); // note we flip Y +} + +function clearPickPosition() { + // unlike the mouse which always has a position + // if the user stops touching the screen we want + // to stop picking. For now we just pick a value + // unlikely to pick something +- pickPosition.x = -100000; +- pickPosition.y = -100000; ++ sendMouse(-100000, -100000); +} +window.addEventListener('mousemove', setPickPosition); +window.addEventListener('mouseout', clearPickPosition); +window.addEventListener('mouseleave', clearPickPosition); + +window.addEventListener('touchstart', (event) => { + // prevent the window from scrolling + event.preventDefault(); + setPickPosition(event.touches[0]); +}, {passive: false}); + +window.addEventListener('touchmove', (event) => { + setPickPosition(event.touches[0]); +}); + +window.addEventListener('touchend', clearPickPosition); +``` + +and with that picking should be working with `OffscreenCanvas`. + +{{{example url="../threejs-offscreencanvas-w-picking.html" }}} + +Let's take it one more step and add in the `OrbitControls`. +This will be little more involved. The `OrbitControls` use +the DOM pretty extensively checking the mouse, touch events, +and the keyboard. + +Unlike our code so far we can't really use a global `state` object +without re-writing all the OrbitControls code to work with it. +The OrbitControls take an element to which they attach most +of the DOM events they use. Maybe we could pass in our own +object that has the same API surface as a DOM element. +We only need to support the features the OrbitControls need. + +Digging through the [OrbitControls source code](https://github.com/greggman/threejsfundamentals/blob/master/threejs/resources/threejs/r103/js/controls/OrbitControls.js) +it looks like we need to handle the following events. + +* contextmenu +* mousedown +* mousemove +* mouseup +* touchstart +* touchmove +* touchend +* wheel +* keydown + +For the mouse events we need the `ctrlKey`, `metaKey`, `shiftKey`, +`button`, `clientX`, `clientY`, `pageX`, and `pageY`, properties + +For the keydown events we need the `ctrlKey`, `metaKey`, `shiftKey`, +and `keyCode` properties. + +For the wheel event we only need the `deltaY` property + +And for the touch events we only need `pageX` and `pageY` from +the `touches` property. + +So, let's make a proxy object pair. One part will run in the main page, +get all those events, and pass on the relevant property values +to the worker. The other part will run in the worker, receive those +events and pass them on using events that have the same structure +as the original DOM events so the OrbitControls won't be able to +tell the difference. + +Here's the code for the worker part. + +```js +class ElementProxyReceiver extends THREE.EventDispatcher { + constructor() { + super(); + } + handleEvent(data) { + this.dispatchEvent(data); + } +} +``` + +All it does is if it receives a message it dispatches it. +It inherits from `EventDispatcher` which provides methods like +`addEventListener` and `removeEventListener` just like a DOM +element so if we pass it to the OrbitControls it should work. + +`ElementProxyReceiver` handles 1 element. In our case we only need +one but it's best to think head so lets make a manager to manage +more than one of them. + +```js +class ProxyManager { + constructor() { + this.targets = {}; + this.handleEvent = this.handleEvent.bind(this); + } + makeProxy(data) { + const {id} = data; + const proxy = new ElementProxyReceiver(); + this.targets[id] = proxy; + } + getProxy(id) { + return this.targets[id]; + } + handleEvent(data) { + this.targets[data.id].handleEvent(data.data); + } +} +``` + +We can make a instance of `ProxyManager` and call its `makeProxy` +method with an id which will make an `ElementProxyReceiver` that +responds to messages with that id. + +Let's hook it up to our worker's message handler. + +```js +const proxyManager = new ProxyManager(); + +function start(data) { + const proxy = proxyManager.getProxy(data.canvasId); + init({ + canvas: data.canvas, + inputElement: proxy, + }); +} + +function makeProxy(data) { + proxyManager.makeProxy(data); +} + +... + +const handlers = { +- init, +- mouse, ++ start, ++ makeProxy, ++ event: proxyManager.handleEvent, + size, +}; + +self.onmessage = function(e) { + const fn = handlers[e.data.type]; + if (!fn) { + throw new Error('no handler for type: ' + e.data.type); + } + fn(e.data); +}; +``` + +We also need to actually add the `OrbitControls` to the top of +the script + +```js +importScripts('resources/threejs/r103/three.js'); ++importScripts('resources/threejs/r103/js/controls/OrbitControls.js'); +*importScripts('shared-orbitcontrols.js'); +``` + +and in our shared three.js code we need to set them up + +```js +function init(data) { +- const {canvas} = data; ++ const {canvas, inputElement} = data; + const renderer = new THREE.WebGLRenderer({canvas}); + ++ const controls = new THREE.OrbitControls(camera, inputElement); ++ controls.target.set(0, 0, 0); ++ controls.update(); +``` + +Notice we're passing the OrbitControls our proxy via `inputElement` +instead of passing in the canvas like we do in other non-OffscreenCanvas +examples. + +Next we can move all the picking event code from the HTML file +to the shared three.js code as well while changing +`canvas` to `inputElement`. + +```js +function setPickPosition(event) { +- sendMouse( +- (event.clientX / canvas.clientWidth ) * 2 - 1, +- (event.clientY / canvas.clientHeight) * -2 + 1); // note we flip Y ++ pickPosition.x = (event.clientX / inputElement.clientWidth ) * 2 - 1; ++ pickPosition.y = (event.clientY / inputElement.clientHeight) * -2 + 1; // note we flip Y +} + +function clearPickPosition() { + // unlike the mouse which always has a position + // if the user stops touching the screen we want + // to stop picking. For now we just pick a value + // unlikely to pick something +- sendMouse(-100000, -100000); ++ pickPosition.x = -100000; ++ pickPosition.y = -100000; +} + +*inputElement.addEventListener('mousemove', setPickPosition); +*inputElement.addEventListener('mouseout', clearPickPosition); +*inputElement.addEventListener('mouseleave', clearPickPosition); + +*inputElement.addEventListener('touchstart', (event) => { + // prevent the window from scrolling + event.preventDefault(); + setPickPosition(event.touches[0]); +}, {passive: false}); + +*inputElement.addEventListener('touchmove', (event) => { + setPickPosition(event.touches[0]); +}); + +*inputElement.addEventListener('touchend', clearPickPosition); +``` + +Back in the main page we need code to send messages for +all the events we enumerated above. + +```js +let nextProxyId = 0; +class ElementProxy { + constructor(element, worker, eventHandlers) { + this.id = nextProxyId++; + this.worker = worker; + const sendEvent = (data) => { + this.worker.postMessage({ + type: 'event', + id: this.id, + data, + }); + }; + + // register an id + worker.postMessage({ + type: 'makeProxy', + id: this.id, + }); + for (const [eventName, handler] of Object.entries(eventHandlers)) { + element.addEventListener(eventName, function(event) { + handler(event, sendEvent); + }); + } + } +} +``` + +`ElementProxy` takes the element who's events we want to proxy. It +then registers an id with the worker by picking one and sending it +via the `makeProxy` message we setup earlier. The worker will make +an `ElementProxyReceiver` and register it to that id. + +We then have an object of event handlers to register. This way +we can pass handlers only for these events we want to forward to +the worker. + +When we start the worker we first make a proxy and pass in our event handlers. + +```js +function startWorker(canvas) { + const offscreen = canvas.transferControlToOffscreen(); + const worker = new Worker('offscreencanvas-worker-orbitcontrols.js'); + ++ const eventHandlers = { ++ contextmenu: preventDefaultHandler, ++ mousedown: mouseEventHandler, ++ mousemove: mouseEventHandler, ++ mouseup: mouseEventHandler, ++ touchstart: touchEventHandler, ++ touchmove: touchEventHandler, ++ touchend: touchEventHandler, ++ wheel: wheelEventHandler, ++ keydown: filteredKeydownEventHandler, ++ }; ++ const proxy = new ElementProxy(canvas, worker, eventHandlers); + worker.postMessage({ + type: 'start', + canvas: offscreen, ++ canvasId: proxy.id, + }, [offscreen]); + console.log('using OffscreenCanvas'); /* eslint-disable-line no-console */ +} +``` + +And here are the event handlers. All they do is copy a list of properties +from the event they receive. They are passed a `sendEvent` function to which they pass the data +they make. That function will add the correct id and send it to the worker. + +```js +const mouseEventHandler = makeSendPropertiesHandler([ + 'ctrlKey', + 'metaKey', + 'shiftKey', + 'button', + 'clientX', + 'clientY', + 'pageX', + 'pageY', +]); +const wheelEventHandlerImpl = makeSendPropertiesHandler([ + 'deltaX', + 'deltaY', +]); +const keydownEventHandler = makeSendPropertiesHandler([ + 'ctrlKey', + 'metaKey', + 'shiftKey', + 'keyCode', +]); + +function wheelEventHandler(event, sendFn) { + event.preventDefault(); + wheelEventHandlerImpl(event, sendFn); +} + +function preventDefaultHandler(event) { + event.preventDefault(); +} + +function copyProperties(src, properties, dst) { + for (const name of properties) { + dst[name] = src[name]; + } +} + +function makeSendPropertiesHandler(properties) { + return function sendProperties(event, sendFn) { + const data = {type: event.type}; + copyProperties(event, properties, data); + sendFn(data); + }; +} + +function touchEventHandler(event, sendFn) { + const touches = []; + const data = {type: event.type, touches}; + for (let i = 0; i < event.touches.length; ++i) { + const touch = event.touches[i]; + touches.push({ + pageX: touch.pageX, + pageY: touch.pageY, + }); + } + sendFn(data); +} + +// The four arrow keys +const orbitKeys = { + '37': true, // left + '38': true, // up + '39': true, // right + '40': true, // down +}; +function filteredKeydownEventHandler(event, sendFn) { + const {keyCode} = event; + if (orbitKeys[keyCode]) { + event.preventDefault(); + keydownEventHandler(event, sendFn); + } +} +``` + +This seems close to running but if we actually try it we'll see +that the `OrbitControls` need a few more things. + +One is they call `element.focus`. We don't need that to happen +in the worker so let's just add a stub. + +```js +class ElementProxyReceiver extends THREE.EventDispatcher { + constructor() { + super(); + } + handleEvent(data) { + this.dispatchEvent(data); + } ++ focus() { ++ // no-op ++ } +} +``` + +Another is they call `event.preventDefault` and `event.stopPropagation`. +We're already handling that in the main page so those can also be a noop. + +```js ++function noop() { ++} + +class ElementProxyReceiver extends THREE.EventDispatcher { + constructor() { + super(); + } + handleEvent(data) { ++ data.preventDefault = noop; ++ data.stopPropagation = noop; + this.dispatchEvent(data); + } + focus() { + // no-op + } +} +``` + +Another is they look at `clientWidth` and `clientHeight`. We +were passing the size before but we can update the proxy pair +to pass that as well. + +In the worker... + +```js +class ElementProxyReceiver extends THREE.EventDispatcher { + constructor() { + super(); + } ++ get clientWidth() { ++ return this.width; ++ } ++ get clientHeight() { ++ return this.height; ++ } + handleEvent(data) { ++ if (data.type === 'size') { ++ this.width = data.width; ++ this.height = data.height; ++ return; ++ } + data.preventDefault = noop; + data.stopPropagation = noop; + this.dispatchEvent(data); + } + focus() { + // no-op + } +} +``` + +back in the main page we need to send the size + +```js +class ElementProxy { + constructor(element, worker, eventHandlers) { + this.id = nextProxyId++; + this.worker = worker; + const sendEvent = (data) => { + this.worker.postMessage({ + type: 'event', + id: this.id, + data, + }); + }; + + // register an id + worker.postMessage({ + type: 'makeProxy', + id: this.id, + }); ++ sendSize(); + for (const [eventName, handler] of Object.entries(eventHandlers)) { + element.addEventListener(eventName, function(event) { + handler(event, sendEvent); + }); + } + ++ function sendSize() { ++ sendEvent({ ++ type: 'size', ++ width: element.clientWidth, ++ height: element.clientHeight, ++ }); ++ } ++ ++ window.addEventListener('resize', sendSize); + } +} +``` + +and in our shared three.js code we no longer need `state` + +```js +-const state = { +- width: 300, // canvas default +- height: 150, // canvas default +-}; + +... + +function resizeRendererToDisplaySize(renderer) { + const canvas = renderer.domElement; +- const width = state.width; +- const height = state.height; ++ const width = inputElement.clientWidth; ++ const height = inputElement.clientHeight; + const needResize = canvas.width !== width || canvas.height !== height; + if (needResize) { + renderer.setSize(width, height, false); + } + return needResize; +} + +function render(time) { + time *= 0.001; + + if (resizeRendererToDisplaySize(renderer)) { +- camera.aspect = state.width / state.height; ++ camera.aspect = inputElement.clientWidth / inputElement.clientHeight; + camera.updateProjectionMatrix(); + } + + ... +``` + +A few more hacks. The OrbitControls attach event handlers to `window` to +get keyboard events. Not sure that's the right place to attach them but that's beyond our control +unless we fork the OrbitControls. In any case `window` doesn't exist in a worker. + +They also also add `mousemove` and `mouseup` events to the `document` +to handle mouse capture (when the mouse goes outside the window) but +like `window` there is no `document` in a worker. + +Finally they look at `document.body`. + +We can solve all of these with a few quick hacks. In our worker +code we'll re-use our proxy for all 3 problems. + +```js +function start(data) { + const proxy = proxyManager.getProxy(data.canvasId); ++ proxy.body = proxy; // HACK! ++ self.window = proxy; // HACK! ++ self.document = proxy; // HACK! + init({ + canvas: data.canvas, + inputElement: proxy, + }); +} +``` + +This will give the `OrbitControls` something to inspect which +matches their expectations. + +I know that was kind of hard to follow. The short version is: +`ElementProxy` runs on the main page and forwards DOM events +to `ElementProxyReceiver` in the worker which +masquerades as an `HTMLElement` that we can use both with the +`OrbitControls` and with our own. + +The final thing is our fallback when we are not using OffscreenCanvas. +All we have to do is pass the canvas itself as our `inputElement`. + +```js +function startMainPage(canvas) { +- init({canvas}); ++ init({canvas, inputElement: canvas}); + console.log('using regular canvas'); +} +``` + +and now we should have OrbitControls working with OffscreenCanvas + +{{{example url="../threejs-offscreencanvas-w-orbitcontrols.html" }}} + +This is probably the most complicated example on this site. It's a +little hard to follow because there are 3 files involved for each +sample. The HTML file, the worker file, the shared three.js code. + +I hope it wasn't too difficult to understand and that it provided some +useful examples of working with three.js, OffscreenCanvas and web workers.
true
Other
mrdoob
three.js
5032300239fca07d213a48e44a1670ba9112e3a4.json
add offscreencanvas article
threejs/lessons/toc.html
@@ -31,6 +31,7 @@ <ul> <li><a href="/threejs/lessons/threejs-optimize-lots-of-objects.html">Optimizing Lots of Objects</a></li> <li><a href="/threejs/lessons/threejs-optimize-lots-of-objects-animated.html">Optimizing Lots of Objects Animated</a></li> + <li><a href="/threejs/lessons/threejs-offscreencanvas.html">Using OffscreenCanvas in a Web Worker</a></li> </ul> <li>Tips</li> <ul>
true
Other
mrdoob
three.js
5032300239fca07d213a48e44a1670ba9112e3a4.json
add offscreencanvas article
threejs/offscreencanvas-cubes.js
@@ -0,0 +1,110 @@ +'use strict'; + +/* global importScripts, THREE */ + +importScripts('resources/threejs/r103/three.min.js'); + +const state = { + width: 300, // canvas default + height: 150, // canvas default +}; + +function main(data) { + const {canvas} = data; + const renderer = new THREE.WebGLRenderer({canvas}); + + state.width = canvas.width; + state.height = canvas.height; + + const fov = 75; + const aspect = 2; // the canvas default + const near = 0.1; + const far = 100; + const camera = new THREE.PerspectiveCamera(fov, aspect, near, far); + camera.position.z = 4; + + const scene = new THREE.Scene(); + + { + const color = 0xFFFFFF; + const intensity = 1; + const light = new THREE.DirectionalLight(color, intensity); + light.position.set(-1, 2, 4); + scene.add(light); + } + + const boxWidth = 1; + const boxHeight = 1; + const boxDepth = 1; + const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth); + + function makeInstance(geometry, color, x) { + const material = new THREE.MeshPhongMaterial({ + color, + }); + + const cube = new THREE.Mesh(geometry, material); + scene.add(cube); + + cube.position.x = x; + + return cube; + } + + const cubes = [ + makeInstance(geometry, 0x44aa88, 0), + makeInstance(geometry, 0x8844aa, -2), + makeInstance(geometry, 0xaa8844, 2), + ]; + + function resizeRendererToDisplaySize(renderer) { + const canvas = renderer.domElement; + const width = state.width; + const height = state.height; + const needResize = canvas.width !== width || canvas.height !== height; + if (needResize) { + renderer.setSize(width, height, false); + } + return needResize; + } + + function render(time) { + time *= 0.001; + + if (resizeRendererToDisplaySize(renderer)) { + camera.aspect = state.width / state.height; + camera.updateProjectionMatrix(); + } + + cubes.forEach((cube, ndx) => { + const speed = 1 + ndx * .1; + const rot = time * speed; + cube.rotation.x = rot; + cube.rotation.y = rot; + }); + + renderer.render(scene, camera); + + requestAnimationFrame(render); + } + + requestAnimationFrame(render); +} + +function size(data) { + state.width = data.width; + state.height = data.height; +} + +const handlers = { + main, + size, +}; + +self.onmessage = function(e) { + const fn = handlers[e.data.type]; + if (!fn) { + throw new Error('no handler for type: ' + e.data.type); + } + fn(e.data); +};
true
Other
mrdoob
three.js
5032300239fca07d213a48e44a1670ba9112e3a4.json
add offscreencanvas article
threejs/offscreencanvas-worker-cubes.js
@@ -0,0 +1,24 @@ +'use strict'; + +/* global importScripts, init, state */ + +importScripts('resources/threejs/r103/three.min.js'); +importScripts('shared-cubes.js'); + +function size(data) { + state.width = data.width; + state.height = data.height; +} + +const handlers = { + init, + size, +}; + +self.onmessage = function(e) { + const fn = handlers[e.data.type]; + if (!fn) { + throw new Error('no handler for type: ' + e.data.type); + } + fn(e.data); +}; \ No newline at end of file
true
Other
mrdoob
three.js
5032300239fca07d213a48e44a1670ba9112e3a4.json
add offscreencanvas article
threejs/offscreencanvas-worker-orbitcontrols.js
@@ -0,0 +1,84 @@ +'use strict'; + +/* global importScripts, init, THREE */ + +importScripts('resources/threejs/r103/three.js'); +importScripts('resources/threejs/r103/js/controls/OrbitControls.js'); +importScripts('shared-orbitcontrols.js'); + +function noop() { +} + +class ElementProxyReceiver extends THREE.EventDispatcher { + constructor() { + super(); + } + get clientWidth() { + return this.width; + } + get clientHeight() { + return this.height; + } + handleEvent(data) { + if (data.type === 'size') { + this.width = data.width; + this.height = data.height; + return; + } + data.preventDefault = noop; + data.stopPropagation = noop; + this.dispatchEvent(data); + } + focus() { + // no-op + } +} + +class ProxyManager { + constructor() { + this.targets = {}; + this.handleEvent = this.handleEvent.bind(this); + } + makeProxy(data) { + const {id} = data; + const proxy = new ElementProxyReceiver(); + this.targets[id] = proxy; + } + getProxy(id) { + return this.targets[id]; + } + handleEvent(data) { + this.targets[data.id].handleEvent(data.data); + } +} + +const proxyManager = new ProxyManager(); + +function start(data) { + const proxy = proxyManager.getProxy(data.canvasId); + proxy.body = proxy; // HACK! + self.window = proxy; + self.document = proxy; + init({ + canvas: data.canvas, + inputElement: proxy, + }); +} + +function makeProxy(data) { + proxyManager.makeProxy(data); +} + +const handlers = { + start, + makeProxy, + event: proxyManager.handleEvent, +}; + +self.onmessage = function(e) { + const fn = handlers[e.data.type]; + if (!fn) { + throw new Error('no handler for type: ' + e.data.type); + } + fn(e.data); +}; \ No newline at end of file
true
Other
mrdoob
three.js
5032300239fca07d213a48e44a1670ba9112e3a4.json
add offscreencanvas article
threejs/offscreencanvas-worker-picking.js
@@ -0,0 +1,30 @@ +'use strict'; + +/* global importScripts, init, state, pickPosition */ + +importScripts('resources/threejs/r103/three.min.js'); +importScripts('shared-picking.js'); + +function size(data) { + state.width = data.width; + state.height = data.height; +} + +function mouse(data) { + pickPosition.x = data.x; + pickPosition.y = data.y; +} + +const handlers = { + init, + mouse, + size, +}; + +self.onmessage = function(e) { + const fn = handlers[e.data.type]; + if (!fn) { + throw new Error('no handler for type: ' + e.data.type); + } + fn(e.data); +}; \ No newline at end of file
true
Other
mrdoob
three.js
5032300239fca07d213a48e44a1670ba9112e3a4.json
add offscreencanvas article
threejs/resources/lessons-helper.js
@@ -370,15 +370,12 @@ * Gets a WebGL context. * makes its backing store the size it is displayed. * @param {HTMLCanvasElement} canvas a canvas element. - * @param {module:webgl-utils.GetWebGLContextOptions} [opt_options] options * @memberOf module:webgl-utils */ - let setupLesson = function(canvas, opt_options) { + let setupLesson = function(canvas) { // only once setupLesson = function() {}; - const options = opt_options || {}; - if (canvas) { canvas.addEventListener('webglcontextlost', function(e) { // the default is to do nothing. Preventing the default
true
Other
mrdoob
three.js
5032300239fca07d213a48e44a1670ba9112e3a4.json
add offscreencanvas article
threejs/shared-cubes.js
@@ -0,0 +1,91 @@ +'use strict'; + +/* global THREE */ + +const state = { + width: 300, // canvas default + height: 150, // canvas default +}; + +function init(data) { /* eslint-disable-line no-unused-vars */ + const {canvas} = data; + const renderer = new THREE.WebGLRenderer({canvas}); + + state.width = canvas.width; + state.height = canvas.height; + + const fov = 75; + const aspect = 2; // the canvas default + const near = 0.1; + const far = 100; + const camera = new THREE.PerspectiveCamera(fov, aspect, near, far); + camera.position.z = 4; + + const scene = new THREE.Scene(); + + { + const color = 0xFFFFFF; + const intensity = 1; + const light = new THREE.DirectionalLight(color, intensity); + light.position.set(-1, 2, 4); + scene.add(light); + } + + const boxWidth = 1; + const boxHeight = 1; + const boxDepth = 1; + const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth); + + function makeInstance(geometry, color, x) { + const material = new THREE.MeshPhongMaterial({ + color, + }); + + const cube = new THREE.Mesh(geometry, material); + scene.add(cube); + + cube.position.x = x; + + return cube; + } + + const cubes = [ + makeInstance(geometry, 0x44aa88, 0), + makeInstance(geometry, 0x8844aa, -2), + makeInstance(geometry, 0xaa8844, 2), + ]; + + function resizeRendererToDisplaySize(renderer) { + const canvas = renderer.domElement; + const width = state.width; + const height = state.height; + const needResize = canvas.width !== width || canvas.height !== height; + if (needResize) { + renderer.setSize(width, height, false); + } + return needResize; + } + + function render(time) { + time *= 0.001; + + if (resizeRendererToDisplaySize(renderer)) { + camera.aspect = state.width / state.height; + camera.updateProjectionMatrix(); + } + + cubes.forEach((cube, ndx) => { + const speed = 1 + ndx * .1; + const rot = time * speed; + cube.rotation.x = rot; + cube.rotation.y = rot; + }); + + renderer.render(scene, camera); + + requestAnimationFrame(render); + } + + requestAnimationFrame(render); +} +
true
Other
mrdoob
three.js
5032300239fca07d213a48e44a1670ba9112e3a4.json
add offscreencanvas article
threejs/shared-orbitcontrols.js
@@ -0,0 +1,151 @@ +'use strict'; + +/* global THREE */ + +function init(data) { /* eslint-disable-line no-unused-vars */ + const {canvas, inputElement} = data; + const renderer = new THREE.WebGLRenderer({canvas}); + + const fov = 75; + const aspect = 2; // the canvas default + const near = 0.1; + const far = 100; + const camera = new THREE.PerspectiveCamera(fov, aspect, near, far); + camera.position.z = 4; + + const controls = new THREE.OrbitControls(camera, inputElement); + controls.target.set(0, 0, 0); + controls.update(); + + const scene = new THREE.Scene(); + + { + const color = 0xFFFFFF; + const intensity = 1; + const light = new THREE.DirectionalLight(color, intensity); + light.position.set(-1, 2, 4); + scene.add(light); + } + + const boxWidth = 1; + const boxHeight = 1; + const boxDepth = 1; + const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth); + + function makeInstance(geometry, color, x) { + const material = new THREE.MeshPhongMaterial({ + color, + }); + + const cube = new THREE.Mesh(geometry, material); + scene.add(cube); + + cube.position.x = x; + + return cube; + } + + const cubes = [ + makeInstance(geometry, 0x44aa88, 0), + makeInstance(geometry, 0x8844aa, -2), + makeInstance(geometry, 0xaa8844, 2), + ]; + + class PickHelper { + constructor() { + this.raycaster = new THREE.Raycaster(); + this.pickedObject = null; + this.pickedObjectSavedColor = 0; + } + pick(normalizedPosition, scene, camera, time) { + // restore the color if there is a picked object + if (this.pickedObject) { + this.pickedObject.material.emissive.setHex(this.pickedObjectSavedColor); + this.pickedObject = undefined; + } + + // cast a ray through the frustum + this.raycaster.setFromCamera(normalizedPosition, camera); + // get the list of objects the ray intersected + const intersectedObjects = this.raycaster.intersectObjects(scene.children); + if (intersectedObjects.length) { + // pick the first object. It's the closest one + this.pickedObject = intersectedObjects[0].object; + // save its color + this.pickedObjectSavedColor = this.pickedObject.material.emissive.getHex(); + // set its emissive color to flashing red/yellow + this.pickedObject.material.emissive.setHex((time * 8) % 2 > 1 ? 0xFFFF00 : 0xFF0000); + } + } + } + + const pickPosition = {x: -2, y: -2}; + const pickHelper = new PickHelper(); + clearPickPosition(); + + function resizeRendererToDisplaySize(renderer) { + const canvas = renderer.domElement; + const width = inputElement.clientWidth; + const height = inputElement.clientHeight; + const needResize = canvas.width !== width || canvas.height !== height; + if (needResize) { + renderer.setSize(width, height, false); + } + return needResize; + } + + function render(time) { + time *= 0.001; + + if (resizeRendererToDisplaySize(renderer)) { + camera.aspect = inputElement.clientWidth / inputElement.clientHeight; + camera.updateProjectionMatrix(); + } + + cubes.forEach((cube, ndx) => { + const speed = 1 + ndx * .1; + const rot = time * speed; + cube.rotation.x = rot; + cube.rotation.y = rot; + }); + + pickHelper.pick(pickPosition, scene, camera, time); + + renderer.render(scene, camera); + + requestAnimationFrame(render); + } + + requestAnimationFrame(render); + + function setPickPosition(event) { + pickPosition.x = (event.clientX / inputElement.clientWidth ) * 2 - 1; + pickPosition.y = (event.clientY / inputElement.clientHeight) * -2 + 1; // note we flip Y + } + + function clearPickPosition() { + // unlike the mouse which always has a position + // if the user stops touching the screen we want + // to stop picking. For now we just pick a value + // unlikely to pick something + pickPosition.x = -100000; + pickPosition.y = -100000; + } + + inputElement.addEventListener('mousemove', setPickPosition); + inputElement.addEventListener('mouseout', clearPickPosition); + inputElement.addEventListener('mouseleave', clearPickPosition); + + inputElement.addEventListener('touchstart', (event) => { + // prevent the window from scrolling + event.preventDefault(); + setPickPosition(event.touches[0]); + }, {passive: false}); + + inputElement.addEventListener('touchmove', (event) => { + setPickPosition(event.touches[0]); + }); + + inputElement.addEventListener('touchend', clearPickPosition); +} +
true
Other
mrdoob
three.js
5032300239fca07d213a48e44a1670ba9112e3a4.json
add offscreencanvas article
threejs/shared-picking.js
@@ -0,0 +1,125 @@ +'use strict'; + +/* global THREE */ + +const state = { + width: 300, // canvas default + height: 150, // canvas default +}; + +const pickPosition = {x: 0, y: 0}; + +function init(data) { // eslint-disable-line no-unused-vars + const {canvas} = data; + const renderer = new THREE.WebGLRenderer({canvas}); + + state.width = canvas.width; + state.height = canvas.height; + + const fov = 75; + const aspect = 2; // the canvas default + const near = 0.1; + const far = 100; + const camera = new THREE.PerspectiveCamera(fov, aspect, near, far); + camera.position.z = 4; + + const scene = new THREE.Scene(); + + { + const color = 0xFFFFFF; + const intensity = 1; + const light = new THREE.DirectionalLight(color, intensity); + light.position.set(-1, 2, 4); + scene.add(light); + } + + const boxWidth = 1; + const boxHeight = 1; + const boxDepth = 1; + const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth); + + function makeInstance(geometry, color, x) { + const material = new THREE.MeshPhongMaterial({ + color, + }); + + const cube = new THREE.Mesh(geometry, material); + scene.add(cube); + + cube.position.x = x; + + return cube; + } + + const cubes = [ + makeInstance(geometry, 0x44aa88, 0), + makeInstance(geometry, 0x8844aa, -2), + makeInstance(geometry, 0xaa8844, 2), + ]; + + class PickHelper { + constructor() { + this.raycaster = new THREE.Raycaster(); + this.pickedObject = null; + this.pickedObjectSavedColor = 0; + } + pick(normalizedPosition, scene, camera, time) { + // restore the color if there is a picked object + if (this.pickedObject) { + this.pickedObject.material.emissive.setHex(this.pickedObjectSavedColor); + this.pickedObject = undefined; + } + + // cast a ray through the frustum + this.raycaster.setFromCamera(normalizedPosition, camera); + // get the list of objects the ray intersected + const intersectedObjects = this.raycaster.intersectObjects(scene.children); + if (intersectedObjects.length) { + // pick the first object. It's the closest one + this.pickedObject = intersectedObjects[0].object; + // save its color + this.pickedObjectSavedColor = this.pickedObject.material.emissive.getHex(); + // set its emissive color to flashing red/yellow + this.pickedObject.material.emissive.setHex((time * 8) % 2 > 1 ? 0xFFFF00 : 0xFF0000); + } + } + } + + const pickHelper = new PickHelper(); + + function resizeRendererToDisplaySize(renderer) { + const canvas = renderer.domElement; + const width = state.width; + const height = state.height; + const needResize = canvas.width !== width || canvas.height !== height; + if (needResize) { + renderer.setSize(width, height, false); + } + return needResize; + } + + function render(time) { + time *= 0.001; + + if (resizeRendererToDisplaySize(renderer)) { + camera.aspect = state.width / state.height; + camera.updateProjectionMatrix(); + } + + cubes.forEach((cube, ndx) => { + const speed = 1 + ndx * .1; + const rot = time * speed; + cube.rotation.x = rot; + cube.rotation.y = rot; + }); + + pickHelper.pick(pickPosition, scene, camera, time); + + renderer.render(scene, camera); + + requestAnimationFrame(render); + } + + requestAnimationFrame(render); +} +
true
Other
mrdoob
three.js
5032300239fca07d213a48e44a1670ba9112e3a4.json
add offscreencanvas article
threejs/threejs-offscreencanvas-w-fallback.html
@@ -0,0 +1,73 @@ +<!-- Licensed under a BSD license. See license.html for license --> +<!DOCTYPE html> +<html> + <head> + <meta charset="utf-8"> + <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes"> + <title>Three.js - OffscreenCanvas w/Fallback</title> + <style> + body { + margin: 0; + } + #c { + width: 100vw; + height: 100vh; + display: block; + } + </style> + </head> + <body> + <canvas id="c"></canvas> + </body> +<script src="resources/threejs/r103/three.min.js"></script> +<script src="shared-cubes.js"></script> +<script> +'use strict'; + +/* global state, init */ + +function startWorker(canvas) { + const offscreen = canvas.transferControlToOffscreen(); + const worker = new Worker('offscreencanvas-worker-cubes.js'); + worker.postMessage({type: 'init', canvas: offscreen}, [offscreen]); + + function sendSize() { + worker.postMessage({ + type: 'size', + width: canvas.clientWidth, + height: canvas.clientHeight, + }); + } + + window.addEventListener('resize', sendSize); + sendSize(); + + console.log('using OffscreenCanvas'); /* eslint-disable-line no-console */ +} + +function startMainPage(canvas) { + init({canvas}); + + function sendSize() { + state.width = canvas.clientWidth; + state.height = canvas.clientHeight; + } + window.addEventListener('resize', sendSize); + sendSize(); + + console.log('using regular canvas'); /* eslint-disable-line no-console */ +} + +function main() { /* eslint consistent-return: 0 */ + const canvas = document.querySelector('#c'); + if (canvas.transferControlToOffscreen) { + startWorker(canvas); + } else { + startMainPage(canvas); + } +} + +main(); +</script> +</html> +
true
Other
mrdoob
three.js
5032300239fca07d213a48e44a1670ba9112e3a4.json
add offscreencanvas article
threejs/threejs-offscreencanvas-w-orbitcontrols.html
@@ -0,0 +1,185 @@ +<!-- Licensed under a BSD license. See license.html for license --> +<!DOCTYPE html> +<html> + <head> + <meta charset="utf-8"> + <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes"> + <title>Three.js - Offscreen Canvas</title> + <style> + body { + margin: 0; + } + #c { + width: 100vw; + height: 100vh; + display: block; + } + #c:focus { + outline: none; + } + </style> + </head> + <body> + <canvas id="c" tabindex="1"></canvas> + </body> +<script src="resources/threejs/r103/three.min.js"></script> +<script src="resources/threejs/r103/js/controls/OrbitControls.js"></script> +<script src="shared-orbitcontrols.js"></script> +<script> +'use strict'; + +/* global init */ + +const mouseEventHandler = makeSendPropertiesHandler([ + 'ctrlKey', + 'metaKey', + 'shiftKey', + 'button', + 'clientX', + 'clientY', + 'pageX', + 'pageY', +]); +const wheelEventHandlerImpl = makeSendPropertiesHandler([ + 'deltaX', + 'deltaY', +]); +const keydownEventHandler = makeSendPropertiesHandler([ + 'ctrlKey', + 'metaKey', + 'shiftKey', + 'keyCode', +]); + +function wheelEventHandler(event, sendFn) { + event.preventDefault(); + wheelEventHandlerImpl(event, sendFn); +} + +function preventDefaultHandler(event) { + event.preventDefault(); +} + +function copyProperties(src, properties, dst) { + for (const name of properties) { + dst[name] = src[name]; + } +} + +function makeSendPropertiesHandler(properties) { + return function sendProperties(event, sendFn) { + const data = {type: event.type}; + copyProperties(event, properties, data); + sendFn(data); + }; +} + +function touchEventHandler(event, sendFn) { + const touches = []; + const data = {type: event.type, touches}; + for (let i = 0; i < event.touches.length; ++i) { + const touch = event.touches[i]; + touches.push({ + pageX: touch.pageX, + pageY: touch.pageY, + }); + } + sendFn(data); +} + +// The four arrow keys +const orbitKeys = { + '37': true, // left + '38': true, // up + '39': true, // right + '40': true, // down +}; +function filteredKeydownEventHandler(event, sendFn) { + const {keyCode} = event; + if (orbitKeys[keyCode]) { + event.preventDefault(); + keydownEventHandler(event, sendFn); + } +} + +let nextProxyId = 0; +class ElementProxy { + constructor(element, worker, eventHandlers) { + this.id = nextProxyId++; + this.worker = worker; + const sendEvent = (data) => { + this.worker.postMessage({ + type: 'event', + id: this.id, + data, + }); + }; + + // register an id + worker.postMessage({ + type: 'makeProxy', + id: this.id, + }); + sendSize(); + for (const [eventName, handler] of Object.entries(eventHandlers)) { + element.addEventListener(eventName, function(event) { + handler(event, sendEvent); + }); + } + + function sendSize() { + sendEvent({ + type: 'size', + width: element.clientWidth, + height: element.clientHeight, + }); + } + + // really need to use ResizeObserver + window.addEventListener('resize', sendSize); + } +} + +function startWorker(canvas) { + canvas.focus(); + const offscreen = canvas.transferControlToOffscreen(); + const worker = new Worker('offscreencanvas-worker-orbitcontrols.js'); + + const eventHandlers = { + contextmenu: preventDefaultHandler, + mousedown: mouseEventHandler, + mousemove: mouseEventHandler, + mouseup: mouseEventHandler, + touchstart: touchEventHandler, + touchmove: touchEventHandler, + touchend: touchEventHandler, + wheel: wheelEventHandler, + keydown: filteredKeydownEventHandler, + }; + const proxy = new ElementProxy(canvas, worker, eventHandlers); + worker.postMessage({ + type: 'start', + canvas: offscreen, + canvasId: proxy.id, + }, [offscreen]); + console.log('using OffscreenCanvas'); /* eslint-disable-line no-console */ +} + +function startMainPage(canvas) { + init({canvas, inputElement: canvas}); + console.log('using regular canvas'); /* eslint-disable-line no-console */ +} + +function main() { /* eslint consistent-return: 0 */ + const canvas = document.querySelector('#c'); + if (canvas.transferControlToOffscreen) { + startWorker(canvas); + } else { + startMainPage(canvas); + } +} + +main(); +</script> +</html> +
true
Other
mrdoob
three.js
5032300239fca07d213a48e44a1670ba9112e3a4.json
add offscreencanvas article
threejs/threejs-offscreencanvas-w-picking.html
@@ -0,0 +1,117 @@ +<!-- Licensed under a BSD license. See license.html for license --> +<!DOCTYPE html> +<html> + <head> + <meta charset="utf-8"> + <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes"> + <title>Three.js - OffscreenCanvas Picking</title> + <style> + body { + margin: 0; + } + #c { + width: 100vw; + height: 100vh; + display: block; + } + </style> + </head> + <body> + <canvas id="c"></canvas> + </body> +<script src="resources/threejs/r103/three.min.js"></script> +<script src="shared-picking.js"></script> +<script> +'use strict'; + +/* global state, init, pickPosition */ + +let sendMouse; + +function startWorker(canvas) { + const offscreen = canvas.transferControlToOffscreen(); + const worker = new Worker('offscreencanvas-worker-picking.js'); + worker.postMessage({type: 'init', canvas: offscreen}, [offscreen]); + + sendMouse = (x, y) => { + worker.postMessage({ + type: 'mouse', + x, + y, + }); + }; + + function sendSize() { + worker.postMessage({ + type: 'size', + width: canvas.clientWidth, + height: canvas.clientHeight, + }); + } + + window.addEventListener('resize', sendSize); + sendSize(); + + console.log('using OffscreenCanvas'); /* eslint-disable-line no-console */ +} + +function startMainPage(canvas) { + init({canvas}); + + sendMouse = (x, y) => { + pickPosition.x = x; + pickPosition.y = y; + }; + + function sendSize() { + state.width = canvas.clientWidth; + state.height = canvas.clientHeight; + } + window.addEventListener('resize', sendSize); + sendSize(); + + console.log('using regular canvas'); /* eslint-disable-line no-console */ +} + +function main() { /* eslint consistent-return: 0 */ + const canvas = document.querySelector('#c'); + if (canvas.transferControlToOffscreen) { + startWorker(canvas); + } else { + startMainPage(canvas); + } + + function setPickPosition(event) { + sendMouse( + (event.clientX / canvas.clientWidth ) * 2 - 1, + (event.clientY / canvas.clientHeight) * -2 + 1); // note we flip Y + } + + function clearPickPosition() { + // unlike the mouse which always has a position + // if the user stops touching the screen we want + // to stop picking. For now we just pick a value + // unlikely to pick something + sendMouse(-100000, -100000); + } + window.addEventListener('mousemove', setPickPosition); + window.addEventListener('mouseout', clearPickPosition); + window.addEventListener('mouseleave', clearPickPosition); + + window.addEventListener('touchstart', (event) => { + // prevent the window from scrolling + event.preventDefault(); + setPickPosition(event.touches[0]); + }, {passive: false}); + + window.addEventListener('touchmove', (event) => { + setPickPosition(event.touches[0]); + }); + + window.addEventListener('touchend', clearPickPosition); +} +main(); + +</script> +</html> +
true
Other
mrdoob
three.js
5032300239fca07d213a48e44a1670ba9112e3a4.json
add offscreencanvas article
threejs/threejs-offscreencanvas.html
@@ -0,0 +1,63 @@ +<!-- Licensed under a BSD license. See license.html for license --> +<!DOCTYPE html> +<html> + <head> + <meta charset="utf-8"> + <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes"> + <title>Three.js - OffscreenCanvas</title> + <style> + body { + margin: 0; + } + #c { + width: 100vw; + height: 100vh; + display: block; + } + #noOffscreenCanvas { + display: flex; + width: 100vw; + height: 100vh; + align-items: center; + justify-content: center; + background: red; + color: white; + } + </style> + </head> + <body> + <canvas id="c"></canvas> + <div id="noOffscreenCanvas" style="display:none;"> + <div>no OffscreenCanvas support</div> + </div> + </body> +<script> +'use strict'; + +function main() { /* eslint consistent-return: 0 */ + const canvas = document.querySelector('#c'); + if (!canvas.transferControlToOffscreen) { + canvas.style.display = 'none'; + document.querySelector('#noOffscreenCanvas').style.display = ''; + return; + } + const offscreen = canvas.transferControlToOffscreen(); + const worker = new Worker('offscreencanvas-cubes.js'); + worker.postMessage({type: 'main', canvas: offscreen}, [offscreen]); + + function sendSize() { + worker.postMessage({ + type: 'size', + width: canvas.clientWidth, + height: canvas.clientHeight, + }); + } + + window.addEventListener('resize', sendSize); + sendSize(); +} +main(); + +</script> +</html> +
true
Other
mrdoob
three.js
2f7df6f53ad09bc57900f2e71750eb216a6f9163.json
handle workers in editor and use shared editor
threejs/resources/editor-settings.js
@@ -0,0 +1,88 @@ + +(function() { // eslint-disable-line strict +'use strict'; // eslint-disable-line strict + +function dirname(path) { + const ndx = path.lastIndexOf('/'); + return path.substring(0, ndx + 1); +} + +function getPrefix(url) { + const u = new URL(url, window.location.href); + const prefix = u.origin + dirname(u.pathname); + return prefix; +} + +function fixSourceLinks(url, source) { + const srcRE = /(src=)"(.*?)"/g; + const linkRE = /(href=)"(.*?)"/g; + const imageSrcRE = /((?:image|img)\.src = )"(.*?)"/g; + const loaderLoadRE = /(loader\.load[a-z]*\s*\(\s*)('|")(.*?)('|")/ig; + const loaderArrayLoadRE = /(loader\.load[a-z]*\(\[)([\s\S]*?)(\])/ig; + const loadFileRE = /(loadFile\s*\(\s*)('|")(.*?)('|")/ig; + const threejsfundamentalsUrlRE = /(.*?)('|")(.*?)('|")(.*?)(\/\*\s+threejsfundamentals:\s+url\s+\*\/)/ig; + const arrayLineRE = /^(\s*["|'])([\s\S]*?)(["|']*$)/; + const urlPropRE = /(url:\s*)('|")(.*?)('|")/g; + const workerRE = /(new\s+Worker\s*\(\s*)('|")(.*?)('|")/g; + const importScriptsRE = /(importScripts\s*\(\s*)('|")(.*?)('|")/g; + const prefix = getPrefix(url); + + function addPrefix(url) { + return url.indexOf('://') < 0 && url[0] !== '?' ? (prefix + url) : url; + } + function makeLinkFQed(match, p1, url) { + return p1 + '"' + addPrefix(url) + '"'; + } + function makeLinkFDedQuotes(match, fn, q1, url, q2) { + return fn + q1 + addPrefix(url) + q2; + } + function makeTaggedFDedQuotes(match, start, q1, url, q2, suffix) { + return start + q1 + addPrefix(url) + q2 + suffix; + } + function makeArrayLinksFDed(match, prefix, arrayStr, suffix) { + const lines = arrayStr.split(',').map((line) => { + const m = arrayLineRE.exec(line); + return m + ? `${m[1]}${addPrefix(m[2])}${m[3]}` + : line; + }); + return `${prefix}${lines.join(',')}${suffix}`; + } + + source = source.replace(srcRE, makeLinkFQed); + source = source.replace(linkRE, makeLinkFQed); + source = source.replace(imageSrcRE, makeLinkFQed); + source = source.replace(urlPropRE, makeLinkFDedQuotes); + source = source.replace(loadFileRE, makeLinkFDedQuotes); + source = source.replace(loaderLoadRE, makeLinkFDedQuotes); + source = source.replace(workerRE, makeLinkFDedQuotes); + source = source.replace(importScriptsRE, makeLinkFDedQuotes); + source = source.replace(loaderArrayLoadRE, makeArrayLinksFDed); + source = source.replace(threejsfundamentalsUrlRE, makeTaggedFDedQuotes); + + return source; +} + +function extraHTMLParsing(html /* , htmlParts */) { + return html; +} + +function fixJSForCodeSite(js) { + // not yet needed for three.js + return js; +} + +window.lessonEditorSettings = { + extraHTMLParsing, + fixSourceLinks, + fixJSForCodeSite, + runOnResize: false, + lessonSettings: { + glDebug: false, + }, + tags: ['three.js', 'threejsfundamentals.org'], + name: 'threejsfundamentals', + icon: '/threejs/lessons/resources/threejsfundamentals-icon-256.png', +}; + +}()); \ No newline at end of file
true
Other
mrdoob
three.js
2f7df6f53ad09bc57900f2e71750eb216a6f9163.json
handle workers in editor and use shared editor
threejs/resources/editor.html
@@ -44,15 +44,39 @@ .panes>div { display: none; flex: 1 1 50%; - position: relative; - overflow: hidden; + flex-direction: column; + min-width: 0; /* this calc is to get things to work in safari. - but firefox and chrome will let chidren of - the panes go 100% size but not safarai + but firefox and chrome will let children of + the panes go 100% size but not safari */ height: calc(100vh - 2.5em - 5px - 1px); } +.panes .code { + flex: 1 1 auto; + position: relative; + height: 100%; +} +.panes .code > div { + height: 100%; +} +.panes .files { + position: relative; +} +.panes .fileSelected { + color: white; + background: #666; +} +.panes .files > div { + border: 1px solid black; + font-family: monospace; + text-overflow: ellipsis; + overflow: hidden; + width: 100%; + white-space: nowrap; + cursor: pointer; +} .panes>div.other { display: block } @@ -103,6 +127,7 @@ border-bottom: 5px solid black; margin: 0.25em; width: 5em; + cursor: pointer; } .panebuttons>button:focus { outline: none; @@ -166,24 +191,24 @@ <button class="button-fullscreen">&nbsp;</button> </div> <div class="panelogo"> - <div><a href="/">threejsfundamentals&nbsp;</a><a href="/"><img src="/threejs/lessons/resources/threejsfundamentals-icon-256.png" width="32" height="32"/></a></div> + <div><a href="/"><span data-subst="textContent|name"></span>&nbsp;</a><a href="/"><img data-subst="src|icon" width="32" height="32"/></a></div> </div> </div> <div class="panes"> - <div class="js"></div> - <div class="html"></div> - <div class="css"></div> + <div class="js"><div class="files"></div><div class="code"></div></div> + <div class="html"><div class="files"></div><div class="code"></div></div> + <div class="css"><div class="files"></div><div class="code"></div></div> <div class="result"><iframe></iframe></div> <div class="other"> <div> - <div><a href="/">threejsfundamentals&nbsp;</a><a href="/"><img src="/threejs/lessons/resources/threejsfundamentals-icon-256.png" width="64" height="64"/></a></div> - <div class="loading"> - </div> + <div><a href="/"><span data-subst="textContent|name"></span>&nbsp;</a><a href="/"><img data-subst="src|icon" width="64" height="64"/></a></div> + <div class="loading"></div> </div> </div> </div> </div> </body> <script src="/monaco-editor/min/vs/loader.js"></script> +<script src="editor-settings.js"></script> <script src="editor.js"></script>
true
Other
mrdoob
three.js
2f7df6f53ad09bc57900f2e71750eb216a6f9163.json
handle workers in editor and use shared editor
threejs/resources/editor.js
@@ -1,9 +1,17 @@ -(function() { // eslint-disable-line -'use strict'; // eslint-disable-line +(function() { // eslint-disable-line strict +'use strict'; // eslint-disable-line strict -/* global monaco, require */ +/* global monaco, require, lessonEditorSettings */ -const lessonHelperScriptRE = /<script src="[^"]+threejs-lessons-helper\.js"><\/script>/; +const { + fixSourceLinks, + fixJSForCodeSite, + extraHTMLParsing, + runOnResize, + lessonSettings, +} = lessonEditorSettings; + +const lessonHelperScriptRE = /<script src="[^"]+lessons-helper\.js"><\/script>/; function getQuery(s) { s = s === undefined ? window.location.search : s; @@ -24,82 +32,22 @@ function getSearch(url) { return s < 0 ? {} : getQuery(url.substring(s)); } -const getFQUrl = (function() { - const a = document.createElement('a'); - return function getFQUrl(url) { - a.href = url; - return a.href; - }; -}()); +function getFQUrl(path, baseUrl) { + const url = new URL(path, baseUrl || window.location.href); + return url.href; +} -function getHTML(url, callback) { - const req = new XMLHttpRequest(); - req.open('GET', url, true); - req.addEventListener('load', function() { - const success = req.status === 200 || req.status === 0; - callback(success ? null : 'could not load: ' + url, req.responseText); - }); - req.addEventListener('timeout', function() { - callback('timeout get: ' + url); - }); - req.addEventListener('error', function() { - callback('error getting: ' + url); - }); - req.send(''); +async function getHTML(url) { + const req = await fetch(url); + return await req.text(); } function getPrefix(url) { - const u = new URL(window.location.origin + url); + const u = new URL(url, window.location.href); const prefix = u.origin + dirname(u.pathname); return prefix; } -function fixSourceLinks(url, source) { - const srcRE = /(src=)"(.*?)"/g; - const linkRE = /(href=)"(.*?)"/g; - const imageSrcRE = /((?:image|img)\.src = )"(.*?)"/g; - const loaderLoadRE = /(loader\.load[a-z]*\s*\(\s*)('|")(.*?)('|")/ig; - const loaderArrayLoadRE = /(loader\.load[a-z]*\(\[)([\s\S]*?)(\])/ig; - const loadFileRE = /(loadFile\s*\(\s*)('|")(.*?)('|")/ig; - const threejsfundamentalsUrlRE = /(.*?)('|")(.*?)('|")(.*?)(\/\*\s+threejsfundamentals:\s+url\s+\*\/)/ig; - const arrayLineRE = /^(\s*["|'])([\s\S]*?)(["|']*$)/; - const urlPropRE = /(url:\s*)('|")(.*?)('|")/g; - const prefix = getPrefix(url); - - function addPrefix(url) { - return url.indexOf('://') < 0 && url[0] !== '?' ? (prefix + url) : url; - } - function makeLinkFQed(match, p1, url) { - return p1 + '"' + addPrefix(url) + '"'; - } - function makeLinkFDedQuotes(match, fn, q1, url, q2) { - return fn + q1 + addPrefix(url) + q2; - } - function makeTaggedFDedQuotes(match, start, q1, url, q2, suffix) { - return start + q1 + addPrefix(url) + q2 + suffix; - } - function makeArrayLinksFDed(match, prefix, arrayStr, suffix) { - const lines = arrayStr.split(',').map((line) => { - const m = arrayLineRE.exec(line); - return m - ? `${m[1]}${addPrefix(m[2])}${m[3]}` - : line; - }); - return `${prefix}${lines.join(',')}${suffix}`; - } - - source = source.replace(srcRE, makeLinkFQed); - source = source.replace(linkRE, makeLinkFQed); - source = source.replace(imageSrcRE, makeLinkFQed); - source = source.replace(urlPropRE, makeLinkFDedQuotes); - source = source.replace(loadFileRE, makeLinkFDedQuotes); - source = source.replace(loaderLoadRE, makeLinkFDedQuotes); - source = source.replace(loaderArrayLoadRE, makeArrayLinksFDed); - source = source.replace(threejsfundamentalsUrlRE, makeTaggedFDedQuotes); - - return source; -} - function fixCSSLinks(url, source) { const cssUrlRE = /(url\()(.*?)(\))/g; const prefix = getPrefix(url); @@ -115,19 +63,59 @@ function fixCSSLinks(url, source) { return source; } +/** + * @typedef {Object} Globals + * @property {SourceInfo} rootScriptInfo + * @property {Object<string, SourceInfo} scriptInfos + */ + +/** @type {Globals} */ const g = { html: '', }; +/** + * This is what's in the sources array + * @typedef {Object} SourceInfo + * @property {string} source The source text (html, css, js) + * @property {string} name The filename or "main page" + * @property {ScriptInfo} scriptInfo The associated ScriptInfo + * @property {string} fqURL ?? + * @property {Editor} editor in instance of Monaco editor + * + */ + +/** + * @typedef {Object} EditorInfo + * @property {HTMLElement} div The div holding the monaco editor + * @property {Editor} editor an instance of a monaco editor + */ + +/** + * What's under each language + * @typedef {Object} HTMLPart + * @property {string} language Name of language + * @property {SourceInfo} sources array of SourceInfos. Usually 1 for HTML, 1 for CSS, N for JS + * @property {HTMLElement} pane the pane for these editors + * @property {HTMLElement} code the div holding the files + * @property {HTMLElement} files the div holding the divs holding the monaco editors + * @property {HTMLElement} button the element to click to show this pane + * @property {EditorInfo} editors + */ + +/** @type {Object<string, HTMLPart>} */ const htmlParts = { js: { language: 'javascript', + sources: [], }, css: { language: 'css', + sources: [], }, html: { language: 'html', + sources: [], }, }; @@ -138,7 +126,6 @@ function forEachHTMLPart(fn) { }); } - function getHTMLPart(re, obj, tag) { let part = ''; obj.html = obj.html.replace(re, function(p0, p1) { @@ -148,7 +135,86 @@ function getHTMLPart(re, obj, tag) { return part.replace(/\s*/, ''); } -function parseHTML(url, html) { +// doesn't handle multi-line comments or comments with { or } in them +function formatCSS(css) { + let indent = ''; + return css.split('\n').map((line) => { + let currIndent = indent; + if (line.includes('{')) { + indent = indent + ' '; + } else if (line.includes('}')) { + indent = indent.substring(0, indent.length - 2); + currIndent = indent; + } + return `${currIndent}${line.trim()}`; + }).join('\n'); +} + +async function getScript(url, scriptInfos) { + // check it's an example script, not some other lib + if (!scriptInfos[url].source) { + const source = await getHTML(url); + const fixedSource = fixSourceLinks(url, source); + const {text} = await getWorkerScripts(fixedSource, url, scriptInfos); + scriptInfos[url].source = text; + } +} + +/** + * @typedef {Object} ScriptInfo + * @property {string} fqURL The original fully qualified URL + * @property {ScriptInfo[]} deps Array of other ScriptInfos this is script dependant on + * @property {boolean} isWorker True if this script came from `new Worker('someurl')` vs `import` or `importScripts` + * @property {string} blobUrl The blobUrl for this script if one has been made + * @property {number} blobGenerationId Used to not visit things twice while recursing. + * @property {string} source The source as extracted. Updated from editor by getSourcesFromEditor + * @property {string} munged The source after urls have been replaced with blob urls etc... (the text send to new Blob) + */ + +async function getWorkerScripts(text, baseUrl, scriptInfos = {}) { + const parentScriptInfo = scriptInfos[baseUrl]; + const workerRE = /(new\s+Worker\s*\(\s*)('|")(.*?)('|")/g; + const importScriptsRE = /(importScripts\s*\(\s*)('|")(.*?)('|")/g; + + const newScripts = []; + const slashRE = /\/threejs\/[^/]+$/; + + function replaceWithUUID(match, prefix, quote, url) { + const fqURL = getFQUrl(url, baseUrl); + if (!slashRE.test(fqURL)) { + return match.toString(); + } + + if (!scriptInfos[url]) { + scriptInfos[fqURL] = { + fqURL, + deps: [], + isWorker: prefix.indexOf('Worker') >= 0, + }; + newScripts.push(fqURL); + } + parentScriptInfo.deps.push(scriptInfos[fqURL]); + + return `${prefix}${quote}${fqURL}${quote}`; + } + + text = text.replace(workerRE, replaceWithUUID); + text = text.replace(importScriptsRE, replaceWithUUID); + + await Promise.all(newScripts.map((url) => { + return getScript(url, scriptInfos); + })); + + return {text, scriptInfos}; +} + +// hack: scriptInfo is undefined for html and css +// should try to include html and css in scriptInfos +function addSource(type, name, source, scriptInfo) { + htmlParts[type].sources.push({source, name, scriptInfo}); +} + +async function parseHTML(url, html) { html = fixSourceLinks(url, html); html = html.replace(/<div class="description">[^]*?<\/div>/, ''); @@ -164,32 +230,49 @@ function parseHTML(url, html) { const hrefRE = /href="([^"]+)"/; const obj = { html: html }; - htmlParts.css.source = fixCSSLinks(url, getHTMLPart(styleRE, obj, '<style>\n${css}</style>')); - htmlParts.html.source = getHTMLPart(bodyRE, obj, '<body>${html}</body>'); - htmlParts.js.source = getHTMLPart(inlineScriptRE, obj, '<script>${js}</script>'); + addSource('css', 'css', formatCSS(fixCSSLinks(url, getHTMLPart(styleRE, obj, '<style>\n${css}</style>')))); + addSource('html', 'html', getHTMLPart(bodyRE, obj, '<body>${html}</body>')); + const rootScript = getHTMLPart(inlineScriptRE, obj, '<script>${js}</script>'); html = obj.html; + const fqURL = getFQUrl(url); + /** @type Object<string, SourceInfo> */ + const scriptInfos = {}; + g.rootScriptInfo = { + fqURL, + deps: [], + source: rootScript, + }; + scriptInfos[fqURL] = g.rootScriptInfo; + + const {text} = await getWorkerScripts(rootScript, fqURL, scriptInfos); + g.rootScriptInfo.source = text; + g.scriptInfos = scriptInfos; + for (const [fqURL, scriptInfo] of Object.entries(scriptInfos)) { + addSource('js', basename(fqURL), scriptInfo.source, scriptInfo); + } + const tm = titleRE.exec(html); if (tm) { g.title = tm[1]; } - let scripts = ''; + const scripts = []; html = html.replace(externalScriptRE, function(p0, p1, p2) { p1 = p1 || ''; - scripts += '\n' + p1 + '<script src="' + p2 + '"></script>'; + scripts.push(`${p1}<script src="${p2}"></script>`); return ''; }); - let dataScripts = ''; + const dataScripts = []; html = html.replace(dataScriptRE, function(p0, p1, p2, p3) { p1 = p1 || ''; - dataScripts += '\n' + p1 + '<script ' + p2 + '>' + p3 + '</script>'; + dataScripts.push(`${p1}<script ${p2}>${p3}</script>`); return ''; }); - htmlParts.html.source += dataScripts; - htmlParts.html.source += scripts + '\n'; + htmlParts.html.sources[0].source += dataScripts.join('\n'); + htmlParts.html.sources[0].source += scripts.join('\n'); // add style section if there is non if (html.indexOf('${css}') < 0) { @@ -201,6 +284,8 @@ function parseHTML(url, html) { // query params but that only works in Firefox >:( html = html.replace('</head>', '<script id="hackedparams">window.hackedParams = ${hackedParams}\n</script>\n</head>'); + html = extraHTMLParsing(html, htmlParts); + let links = ''; html = html.replace(cssLinkRE, function(p0, p1) { if (isCSSLinkRE.test(p1)) { @@ -214,7 +299,7 @@ function parseHTML(url, html) { } }); - htmlParts.css.source = links + htmlParts.css.source; + htmlParts.css.sources[0].source = links + htmlParts.css.sources[0].source; g.html = html; } @@ -224,93 +309,216 @@ function cantGetHTML(e) { // eslint-disable-line console.log("TODO: don't run editor if can't get HTML"); // eslint-disable-line } -function main() { +async function main() { const query = getQuery(); g.url = getFQUrl(query.url); g.query = getSearch(g.url); - getHTML(query.url, function(err, html) { - if (err) { - console.log(err); // eslint-disable-line - return; - } - parseHTML(query.url, html); - setupEditor(query.url); - if (query.startPane) { - const button = document.querySelector('.button-' + query.startPane); - toggleSourcePane(button); - } - }); + let html; + try { + html = await getHTML(query.url); + } catch (err) { + console.log(err); // eslint-disable-line + return; + } + await parseHTML(query.url, html); + setupEditor(query.url); + if (query.startPane) { + const button = document.querySelector('.button-' + query.startPane); + toggleSourcePane(button); + } +} + +function getJavaScriptBlob(source) { + const blob = new Blob([source], {type: 'application/javascript'}); + return URL.createObjectURL(blob); } +let blobGeneration = 0; +function makeBlobURLsForSources(scriptInfo) { + ++blobGeneration; -let blobUrl; -function getSourceBlob(htmlParts, options) { - options = options || {}; - if (blobUrl) { - URL.revokeObjectURL(blobUrl); + function makeBlobURLForSourcesImpl(scriptInfo) { + if (scriptInfo.blobGenerationId !== blobGeneration) { + scriptInfo.blobGenerationId = blobGeneration; + if (scriptInfo.blobUrl) { + URL.revokeObjectURL(scriptInfo.blobUrl); + } + scriptInfo.deps.forEach(makeBlobURLForSourcesImpl); + let text = scriptInfo.source; + scriptInfo.deps.forEach((depScriptInfo) => { + text = text.split(depScriptInfo.fqURL).join(depScriptInfo.blobUrl); + }); + scriptInfo.numLinesBeforeScript = 0; + if (scriptInfo.isWorker) { + const extra = `self.lessonSettings = ${JSON.stringify(lessonSettings)}; +importScripts('${dirname(scriptInfo.fqURL)}/resources/lessons-worker-helper.js')`; + scriptInfo.numLinesBeforeScript = extra.split('\n').length; + text = `${extra}\n${text}`; + } + scriptInfo.blobUrl = getJavaScriptBlob(text); + scriptInfo.munged = text; + } } + makeBlobURLForSourcesImpl(scriptInfo); +} + +function getSourceBlob(htmlParts) { + g.rootScriptInfo.source = htmlParts.js; + makeBlobURLsForSources(g.rootScriptInfo); + const prefix = dirname(g.url); let source = g.html; source = source.replace('${hackedParams}', JSON.stringify(g.query)); source = source.replace('${html}', htmlParts.html); source = source.replace('${css}', htmlParts.css); - source = source.replace('${js}', htmlParts.js); - source = source.replace('<head>', '<head>\n<script match="false">threejsLessonSettings = ' + JSON.stringify(options) + ';</script>'); + source = source.replace('${js}', g.rootScriptInfo.munged); //htmlParts.js); + source = source.replace('<head>', `<head> + <link rel="stylesheet" href="${prefix}/resources/lesson-helper.css" type="text/css"> + <script match="false">self.lessonSettings = ${JSON.stringify(lessonSettings)}</script>`); - source = source.replace('</head>', '<script src="' + prefix + '/resources/threejs-lessons-helper.js"></script>\n</head>'); + source = source.replace('</head>', `<script src="${prefix}/resources/lessons-helper.js"></script> + </head>`); const scriptNdx = source.indexOf('<script>'); - g.numLinesBeforeScript = (source.substring(0, scriptNdx).match(/\n/g) || []).length; + g.rootScriptInfo.numLinesBeforeScript = (source.substring(0, scriptNdx).match(/\n/g) || []).length; const blob = new Blob([source], {type: 'text/html'}); - blobUrl = URL.createObjectURL(blob); + // This seems hacky. We are combining html/css/js into one html blob but we already made + // a blob for the JS so let's replace that blob. That means it will get auto-released when script blobs + // are regenerated. It also means error reporting will work + const blobUrl = URL.createObjectURL(blob); + URL.revokeObjectURL(g.rootScriptInfo.blobUrl); + g.rootScriptInfo.blobUrl = blobUrl; return blobUrl; } -function getSourceBlobFromEditor(options) { +function getSourcesFromEditor() { + for (const partTypeInfo of Object.values(htmlParts)) { + for (const source of partTypeInfo.sources) { + source.source = source.editor.getValue(); + // hack: shouldn't store this twice. Also see other comment, + // should consolidate so scriptInfo is used for css and html + if (source.scriptInfo) { + source.scriptInfo.source = source.source; + } + } + } +} +function getSourceBlobFromEditor() { + getSourcesFromEditor(); + return getSourceBlob({ - html: htmlParts.html.editor.getValue(), - css: htmlParts.css.editor.getValue(), - js: htmlParts.js.editor.getValue(), - }, options); + html: htmlParts.html.sources[0].source, + css: htmlParts.css.sources[0].source, + js: htmlParts.js.sources[0].source, + }); } -function getSourceBlobFromOrig(options) { +function getSourceBlobFromOrig() { return getSourceBlob({ - html: htmlParts.html.source, - css: htmlParts.css.source, - js: htmlParts.js.source, - }, options); + html: htmlParts.html.sources[0].source, + css: htmlParts.css.sources[0].source, + js: htmlParts.js.sources[0].source, + }); } function dirname(path) { const ndx = path.lastIndexOf('/'); return path.substring(0, ndx + 1); } +function basename(path) { + const ndx = path.lastIndexOf('/'); + return path.substring(ndx + 1); +} + function resize() { forEachHTMLPart(function(info) { - info.editor.layout(); + info.editors.forEach((editorInfo) => { + editorInfo.editor.layout(); + }); }); } -function addCORSSupport(js) { - // not yet needed for three.js - return js; +function makeScriptsForWorkers(scriptInfo) { + ++blobGeneration; + + function makeScriptsForWorkersImpl(scriptInfo) { + const scripts = []; + if (scriptInfo.blobGenerationId !== blobGeneration) { + scriptInfo.blobGenerationId = blobGeneration; + scripts.push(...scriptInfo.deps.map(makeScriptsForWorkersImpl).flat()); + let text = scriptInfo.source; + scriptInfo.deps.forEach((depScriptInfo) => { + text = text.split(depScriptInfo.fqURL).join(`worker-${basename(depScriptInfo.fqURL)}`); + }); + + scripts.push({ + name: `worker-${basename(scriptInfo.fqURL)}`, + text, + }); + } + return scripts; + } + + const scripts = makeScriptsForWorkersImpl(scriptInfo); + const mainScript = scripts.pop().text; + if (!scripts.length) { + return { + js: mainScript, + html: '', + }; + } + + const workerName = scripts[scripts.length - 1].name; + const html = scripts.map((nameText) => { + const {name, text} = nameText; + return `<script id="${name}" type="x-worker">\n${text}\n</script>`; + }).join('\n'); + const init = ` + + + +// ------ +// Creates Blobs for the Worker Scripts so things can be self contained for snippets/JSFiddle/Codepen +// +function getWorkerBlob() { + const idsToUrls = []; + const scriptElements = [...document.querySelectorAll('script[type=x-worker]')]; + for (const scriptElement of scriptElements) { + let text = scriptElement.text; + for (const {id, url} of idsToUrls) { + text = text.split(id).join(url); + } + const blob = new Blob([text], {type: 'application/javascript'}); + const url = URL.createObjectURL(blob); + const id = scriptElement.id; + idsToUrls.push({id, url}); + } + return idsToUrls.pop().url; +} +`; + return { + js: mainScript.split(`'${workerName}'`).join('getWorkerBlob()') + init, + html, + }; } function openInCodepen() { const comment = `// ${g.title} // from ${g.url} + `; + getSourcesFromEditor(); + const scripts = makeScriptsForWorkers(g.rootScriptInfo); const pen = { title : g.title, description : 'from: ' + g.url, - tags : ['three.js', 'threejsfundamentals.org'], + tags : lessonEditorSettings.tags, editors : '101', - html : htmlParts.html.editor.getValue().replace(lessonHelperScriptRE, ''), - css : htmlParts.css.editor.getValue(), - js : comment + addCORSSupport(htmlParts.js.editor.getValue()), + html : scripts.html + htmlParts.html.sources[0].source.replace(lessonHelperScriptRE, ''), + css : htmlParts.css.sources[0].source, + js : comment + fixJSForCodeSite(scripts.js), }; const elem = document.createElement('div'); @@ -331,15 +539,9 @@ function openInJSFiddle() { // from ${g.url} `; - // const pen = { - // title : g.title, - // description : "from: " + g.url, - // tags : ["three.js", "threejsfundamentals.org"], - // editors : "101", - // html : htmlParts.html.editor.getValue(), - // css : htmlParts.css.editor.getValue(), - // js : comment + htmlParts.js.editor.getValue(), - // }; + + getSourcesFromEditor(); + const scripts = makeScriptsForWorkers(g.rootScriptInfo); const elem = document.createElement('div'); elem.innerHTML = ` @@ -352,24 +554,60 @@ function openInJSFiddle() { <input type="submit" /> </form> `; - elem.querySelector('input[name=html]').value = htmlParts.html.editor.getValue().replace(lessonHelperScriptRE, ''); - elem.querySelector('input[name=css]').value = htmlParts.css.editor.getValue(); - elem.querySelector('input[name=js]').value = comment + addCORSSupport(htmlParts.js.editor.getValue()); + elem.querySelector('input[name=html]').value = scripts.html + htmlParts.html.sources[0].source.replace(lessonHelperScriptRE, ''); + elem.querySelector('input[name=css]').value = htmlParts.css.sources[0].source; + elem.querySelector('input[name=js]').value = comment + fixJSForCodeSite(scripts.js); elem.querySelector('input[name=title]').value = g.title; window.frameElement.ownerDocument.body.appendChild(elem); elem.querySelector('form').submit(); window.frameElement.ownerDocument.body.removeChild(elem); } +function selectFile(info, ndx, fileDivs) { + if (info.editors.length <= 1) { + return; + } + info.editors.forEach((editorInfo, i) => { + const selected = i === ndx; + editorInfo.div.style.display = selected ? '' : 'none'; + editorInfo.editor.layout(); + addRemoveClass(fileDivs.children[i], 'fileSelected', selected); + }); +} + +function showEditorSubPane(type, ndx) { + const info = htmlParts[type]; + selectFile(info, ndx, info.files); +} + function setupEditor() { forEachHTMLPart(function(info, ndx, name) { - info.parent = document.querySelector('.panes>.' + name); - info.editor = runEditor(info.parent, info.source, info.language); + info.pane = document.querySelector('.panes>.' + name); + info.code = info.pane.querySelector('.code'); + info.files = info.pane.querySelector('.files'); + info.editors = info.sources.map((sourceInfo, ndx) => { + if (info.sources.length > 1) { + const div = document.createElement('div'); + div.textContent = basename(sourceInfo.name); + info.files.appendChild(div); + div.addEventListener('click', () => { + selectFile(info, ndx, info.files); + }); + } + const div = document.createElement('div'); + info.code.appendChild(div); + const editor = runEditor(div, sourceInfo.source, info.language); + sourceInfo.editor = editor; + return { + div, + editor, + }; + }); info.button = document.querySelector('.button-' + name); info.button.addEventListener('click', function() { toggleSourcePane(info.button); - run(); + runIfNeeded(); }); }); @@ -389,7 +627,7 @@ function setupEditor() { g.resultButton = document.querySelector('.button-result'); g.resultButton.addEventListener('click', function() { toggleResultPane(); - run(); + runIfNeeded(); }); g.result.style.display = 'none'; toggleResultPane(); @@ -400,23 +638,30 @@ function setupEditor() { window.addEventListener('resize', resize); + showEditorSubPane('js', 0); showOtherIfAllPanesOff(); document.querySelector('.other .loading').style.display = 'none'; resize(); - run({glDebug: false}); + run(); } function toggleFullscreen() { try { toggleIFrameFullscreen(window); resize(); - run(); + runIfNeeded(); } catch (e) { console.error(e); // eslint-disable-line } } +function runIfNeeded() { + if (runOnResize) { + run(); + } +} + function run(options) { g.setPosition = false; const url = getSourceBlobFromEditor(options); @@ -478,11 +723,11 @@ function toggleSourcePane(pressedButton) { const pressed = pressedButton === info.button; if (pressed && !info.showing) { addClass(info.button, 'show'); - info.parent.style.display = 'block'; + info.pane.style.display = 'flex'; info.showing = true; } else { removeClass(info.button, 'show'); - info.parent.style.display = 'none'; + info.pane.style.display = 'none'; info.showing = false; } }); @@ -509,19 +754,35 @@ function showOtherIfAllPanesOff() { g.other.style.display = paneOn ? 'none' : 'block'; } -function getActualLineNumberAndMoveTo(lineNo, colNo) { - const actualLineNo = lineNo - g.numLinesBeforeScript; - if (!g.setPosition) { - // Only set the first position - g.setPosition = true; - htmlParts.js.editor.setPosition({ - lineNumber: actualLineNo, - column: colNo, - }); - htmlParts.js.editor.revealLineInCenterIfOutsideViewport(actualLineNo); - htmlParts.js.editor.focus(); +// seems like we should probably store a map +function getEditorNdxByBlobUrl(type, url) { + return htmlParts[type].sources.findIndex(source => source.scriptInfo.blobUrl === url); +} + +function getActualLineNumberAndMoveTo(url, lineNo, colNo) { + let origUrl = url; + let actualLineNo = lineNo; + const scriptInfo = Object.values(g.scriptInfos).find(scriptInfo => scriptInfo.blobUrl === url); + if (scriptInfo) { + actualLineNo = lineNo - scriptInfo.numLinesBeforeScript; + origUrl = basename(scriptInfo.fqURL); + if (!g.setPosition) { + // Only set the first position + g.setPosition = true; + const editorNdx = getEditorNdxByBlobUrl('js', url); + if (editorNdx >= 0) { + showEditorSubPane('js', editorNdx); + const editor = htmlParts.js.editors[editorNdx].editor; + editor.setPosition({ + lineNumber: actualLineNo, + column: colNo, + }); + editor.revealLineInCenterIfOutsideViewport(actualLineNo); + editor.focus(); + } + } } - return actualLineNo; + return {origUrl, actualLineNo}; } window.getActualLineNumberAndMoveTo = getActualLineNumberAndMoveTo; @@ -539,17 +800,27 @@ function runEditor(parent, source, language) { }); } -function runAsBlob() { +async function runAsBlob() { const query = getQuery(); g.url = getFQUrl(query.url); g.query = getSearch(g.url); - getHTML(query.url, function(err, html) { - if (err) { - console.log(err); // eslint-disable-line - return; - } - parseHTML(query.url, html); - window.location.href = getSourceBlobFromOrig(); + let html; + try { + html = await getHTML(query.url); + } catch (err) { + console.log(err); // eslint-disable-line + return; + } + await parseHTML(query.url, html); + window.location.href = getSourceBlobFromOrig(); +} + +function applySubstitutions() { + [...document.querySelectorAll('[data-subst]')].forEach((elem) => { + elem.dataset.subst.split('&').forEach((pair) => { + const [attr, key] = pair.split('|'); + elem[attr] = lessonEditorSettings[key]; + }); }); } @@ -562,6 +833,7 @@ function start() { // var url = query.url; // window.location.href = url; } else { + applySubstitutions(); require.config({ paths: { 'vs': '/monaco-editor/min/vs' }}); require(['vs/editor/editor.main'], main); }
true
Other
mrdoob
three.js
2f7df6f53ad09bc57900f2e71750eb216a6f9163.json
handle workers in editor and use shared editor
threejs/resources/lesson-helper.css
@@ -0,0 +1,19 @@ +.contextlost { + position: absolute; + left: 0; + top: 0; + width: 100vw; + height: 100vh; + background: red; + color: white; + font-family: monospace; + font-weight: bold; + display: flex; + align-items: center; + justify-content: center; +} +.contextlost>div { + padding: 0.5em; + background: darkred; + cursor: pointer; +} \ No newline at end of file
true
Other
mrdoob
three.js
2f7df6f53ad09bc57900f2e71750eb216a6f9163.json
handle workers in editor and use shared editor
threejs/resources/lessons-helper.js
@@ -39,11 +39,12 @@ }); } else { // Browser globals - root.threejsLessonsHelper = factory.call(root); + root.lessonsHelper = factory.call(root); } }(this, function() { 'use strict'; // eslint-disable-line + const lessonSettings = window.lessonSettings || {}; const topWindow = this; /** @@ -204,28 +205,186 @@ window.console.error = wrapFunc(window.console, 'error', 'red', '❌'); } + function reportJSError(url, lineNo, colNo, msg) { + try { + const {origUrl, actualLineNo} = window.parent.getActualLineNumberAndMoveTo(url, lineNo, colNo); + url = origUrl; + lineNo = actualLineNo; + } catch (ex) { + origConsole.error(ex); + } + console.error(url, "line:", lineNo, ":", msg); // eslint-disable-line + } + + /** + * @typedef {Object} StackInfo + * @property {string} url Url of line + * @property {number} lineNo line number of error + * @property {number} colNo column number of error + * @property {string} [funcName] name of function + */ + + /** + * @parameter {string} stack A stack string as in `(new Error()).stack` + * @returns {StackInfo} + */ + const parseStack = function() { + const browser = getBrowser(); + let lineNdx; + let matcher; + if ((/chrome|opera/i).test(browser.name)) { + lineNdx = 3; + matcher = function(line) { + const m = /at ([^(]+)*\(*(.*?):(\d+):(\d+)/.exec(line); + if (m) { + let userFnName = m[1]; + let url = m[2]; + const lineNo = parseInt(m[3]); + const colNo = parseInt(m[4]); + if (url === '') { + url = userFnName; + userFnName = ''; + } + return { + url: url, + lineNo: lineNo, + colNo: colNo, + funcName: userFnName, + }; + } + return undefined; + }; + } else if ((/firefox|safari/i).test(browser.name)) { + lineNdx = 2; + matcher = function(line) { + const m = /@(.*?):(\d+):(\d+)/.exec(line); + if (m) { + const url = m[1]; + const lineNo = parseInt(m[2]); + const colNo = parseInt(m[3]); + return { + url: url, + lineNo: lineNo, + colNo: colNo, + }; + } + return undefined; + }; + } + + return function stackParser(stack) { + if (matcher) { + try { + const lines = stack.split('\n'); + // window.fooLines = lines; + // lines.forEach(function(line, ndx) { + // origConsole.log("#", ndx, line); + // }); + return matcher(lines[lineNdx]); + } catch (e) { + // do nothing + } + } + return undefined; + }; + }(); + + function setupWorkerSupport() { + function log(data) { + const {logType, msg} = data; + console[logType]('[Worker]', msg); /* eslint-disable-line no-console */ + } + + function lostContext(/* data */) { + addContextLostHTML(); + } + + function jsError(data) { + const {url, lineNo, colNo, msg} = data; + reportJSError(url, lineNo, colNo, msg); + } + + function jsErrorWithStack(data) { + const {url, stack, msg} = data; + const errorInfo = parseStack(stack); + if (errorInfo) { + reportJSError(errorInfo.url || url, errorInfo.lineNo, errorInfo.colNo, msg); + } else { + console.error(errorMsg) // eslint-disable-line + } + } + + const handlers = { + log, + lostContext, + jsError, + jsErrorWithStack, + }; + const OrigWorker = self.Worker; + class WrappedWorker extends OrigWorker { + constructor(url) { + super(url); + let listener; + this.onmessage = function(e) { + if (!e || !e.data || !e.data.type === '___editor___') { + if (listener) { + listener(e); + } + return; + } + + e.stopImmediatePropagation(); + const data = e.data.data; + const fn = handlers[data.type]; + if (!fn) { + origConsole.error('unknown editor msg:', data.type); + } else { + fn(data); + } + return; + }; + Object.defineProperty(this, 'onmessage', { + get() { + return listener; + }, + set(fn) { + listener = fn; + }, + }); + } + } + self.Worker = WrappedWorker; + } + + function addContextLostHTML() { + const div = document.createElement('div'); + div.className = 'contextlost'; + div.innerHTML = '<div>Context Lost: Click To Reload</div>'; + div.addEventListener('click', function() { + window.location.reload(); + }); + document.body.appendChild(div); + } + /** * Gets a WebGL context. * makes its backing store the size it is displayed. * @param {HTMLCanvasElement} canvas a canvas element. + * @param {module:webgl-utils.GetWebGLContextOptions} [opt_options] options * @memberOf module:webgl-utils */ - let setupLesson = function(canvas) { + let setupLesson = function(canvas, opt_options) { // only once setupLesson = function() {}; + const options = opt_options || {}; + if (canvas) { canvas.addEventListener('webglcontextlost', function(e) { // the default is to do nothing. Preventing the default // means allowing context to be restored e.preventDefault(); - const div = document.createElement('div'); - div.className = 'contextlost'; - div.innerHTML = '<div>Context Lost: Click To Reload</div>'; - div.addEventListener('click', function() { - window.location.reload(); - }); - document.body.appendChild(div); + addContextLostHTML(); }); canvas.addEventListener('webglcontextrestored', function() { // just reload the page. Easiest. @@ -633,8 +792,9 @@ */ function glEnumToString(value) { const name = glEnums[value]; - return (name !== undefined) ? ('gl.' + name) : - ('/*UNKNOWN WebGL ENUM*/ 0x' + value.toString(16) + ''); + return (name !== undefined) + ? `gl.${name}` + : `/*UNKNOWN WebGL ENUM*/ 0x${value.toString(16)}`; } /** @@ -727,8 +887,7 @@ options.sharedState = sharedState; const errorFunc = options.errorFunc || function(err, functionName, args) { - console.error("WebGL error " + glEnumToString(err) + " in " + functionName + // eslint-disable-line - '(' + glFunctionArgsToString(functionName, args) + ')'); + console.error(`WebGL error ${glEnumToString(err)} in ${functionName}(${glFunctionArgsToString(functionName, args)})`); /* eslint-disable-line no-console */ }; // Holds booleans for each GL error so after we get the error ourselves @@ -785,7 +944,7 @@ ext = wrapped.apply(ctx, arguments); if (ext) { const origExt = ext; - ext = makeDebugContext(ext, options); + ext = makeDebugContext(ext, Object.assign({}, options, {errCtx: ctx})); sharedState.wrappers[extensionName] = { wrapper: ext, orig: origExt }; addEnumsForContext(origExt, extensionName); } @@ -839,17 +998,9 @@ window.addEventListener('error', function(e) { const msg = e.message || e.error; const url = e.filename; - let lineNo = e.lineno || 1; + const lineNo = e.lineno || 1; const colNo = e.colno || 1; - const isUserScript = (url === window.location.href); - if (isUserScript) { - try { - lineNo = window.parent.getActualLineNumberAndMoveTo(lineNo, colNo); - } catch (ex) { - origConsole.error(ex); - } - } - console.error("line:", lineNo, ":", msg); // eslint-disable-line + reportJSError(url, lineNo, colNo, msg); origConsole.error(e.error); }); } @@ -927,79 +1078,13 @@ } return str; }); - - const browser = getBrowser(); - let lineNdx; - let matcher; - if ((/chrome|opera/i).test(browser.name)) { - lineNdx = 3; - matcher = function(line) { - const m = /at ([^(]+)*\(*(.*?):(\d+):(\d+)/.exec(line); - if (m) { - let userFnName = m[1]; - let url = m[2]; - const lineNo = parseInt(m[3]); - const colNo = parseInt(m[4]); - if (url === '') { - url = userFnName; - userFnName = ''; - } - return { - url: url, - lineNo: lineNo, - colNo: colNo, - funcName: userFnName, - }; - } - return undefined; - }; - } else if ((/firefox|safari/i).test(browser.name)) { - lineNdx = 2; - matcher = function(line) { - const m = /@(.*?):(\d+):(\d+)/.exec(line); - if (m) { - const url = m[1]; - const lineNo = parseInt(m[2]); - const colNo = parseInt(m[3]); - return { - url: url, - lineNo: lineNo, - colNo: colNo, - }; - } - return undefined; - }; + const errorMsg = `WebGL error ${glEnumToString(err)} in ${funcName}(${enumedArgs.join(', ')})`; + const errorInfo = parseStack((new Error()).stack); + if (errorInfo) { + reportJSError(errorInfo.url, errorInfo.lineNo, errorInfo.colNo, errorMsg); + } else { + console.error(errorMsg) // eslint-disable-line } - - let lineInfo = ''; - if (matcher) { - try { - const error = new Error(); - const lines = error.stack.split('\n'); - // window.fooLines = lines; - // lines.forEach(function(line, ndx) { - // origConsole.log("#", ndx, line); - // }); - const info = matcher(lines[lineNdx]); - if (info) { - let lineNo = info.lineNo; - const colNo = info.colNo; - const url = info.url; - const isUserScript = (url === window.location.href); - if (isUserScript) { - lineNo = window.parent.getActualLineNumberAndMoveTo(lineNo, colNo); - } - lineInfo = ' line:' + lineNo + ':' + colNo; - } - } catch (e) { - origConsole.error(e); - } - } - - console.error( // eslint-disable-line - 'WebGL error' + lineInfo, glEnumToString(err), 'in', - funcName, '(', enumedArgs.join(', '), ')'); - }, }); } @@ -1011,9 +1096,10 @@ installWebGLLessonSetup(); if (isInEditor()) { + setupWorkerSupport(); setupConsole(); captureJSErrors(); - if (window.threejsLessonSettings === undefined || window.threejsLessonSettings.glDebug !== false) { + if (lessonSettings.glDebug !== false) { installWebGLDebugContextCreator(); } }
true
Other
mrdoob
three.js
2f7df6f53ad09bc57900f2e71750eb216a6f9163.json
handle workers in editor and use shared editor
threejs/resources/lessons-worker-helper.js
@@ -0,0 +1,699 @@ +/* + * Copyright 2019, Gregg Tavares. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Gregg Tavares. nor the names of his + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/* global */ +'use strict'; + +(function() { + + const lessonSettings = self.lessonSettings || {}; + + function isInEditor() { + return self.location.href.substring(0, 4) === 'blob'; + } + + function sendMessage(data) { + self.postMessage({ + type: '__editor__', + data, + }); + } + + const origConsole = {}; + + function setupConsole() { + function wrapFunc(obj, logType) { + const origFunc = obj[logType].bind(obj); + origConsole[logType] = origFunc; + return function(...args) { + origFunc(...args); + sendMessage({ + type: 'log', + logType, + msg: [...args].join(' '), + }); + }; + } + self.console.log = wrapFunc(self.console, 'log'); + self.console.warn = wrapFunc(self.console, 'warn'); + self.console.error = wrapFunc(self.console, 'error'); + } + + /** + * Gets a WebGL context. + * makes its backing store the size it is displayed. + * @param {OffscreenCanvas} canvas a canvas element. + * @memberOf module:webgl-utils + */ + let setupLesson = function(canvas) { + // only once + setupLesson = function() {}; + + if (canvas) { + canvas.addEventListener('webglcontextlost', function(e) { + // the default is to do nothing. Preventing the default + // means allowing context to be restored + e.preventDefault(); + sendMessage({ + type: 'lostContext', + }); + }); + } + + }; + + + //------------ [ from https://github.com/KhronosGroup/WebGLDeveloperTools ] + + /* + ** Copyright (c) 2012 The Khronos Group Inc. + ** + ** Permission is hereby granted, free of charge, to any person obtaining a + ** copy of this software and/or associated documentation files (the + ** "Materials"), to deal in the Materials without restriction, including + ** without limitation the rights to use, copy, modify, merge, publish, + ** distribute, sublicense, and/or sell copies of the Materials, and to + ** permit persons to whom the Materials are furnished to do so, subject to + ** the following conditions: + ** + ** The above copyright notice and this permission notice shall be included + ** in all copies or substantial portions of the Materials. + ** + ** THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + ** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + ** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + ** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + ** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + ** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + ** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. + */ + + /** + * Types of contexts we have added to map + */ + const mappedContextTypes = {}; + + /** + * Map of numbers to names. + * @type {Object} + */ + const glEnums = {}; + + /** + * Map of names to numbers. + * @type {Object} + */ + const enumStringToValue = {}; + + /** + * Initializes this module. Safe to call more than once. + * @param {!WebGLRenderingContext} ctx A WebGL context. If + * you have more than one context it doesn't matter which one + * you pass in, it is only used to pull out constants. + */ + function addEnumsForContext(ctx, type) { + if (!mappedContextTypes[type]) { + mappedContextTypes[type] = true; + for (const propertyName in ctx) { + if (typeof ctx[propertyName] === 'number') { + glEnums[ctx[propertyName]] = propertyName; + enumStringToValue[propertyName] = ctx[propertyName]; + } + } + } + } + + function enumArrayToString(enums) { + const enumStrings = []; + if (enums.length) { + for (let i = 0; i < enums.length; ++i) { + enums.push(glEnumToString(enums[i])); // eslint-disable-line + } + return '[' + enumStrings.join(', ') + ']'; + } + return enumStrings.toString(); + } + + function makeBitFieldToStringFunc(enums) { + return function(value) { + let orResult = 0; + const orEnums = []; + for (let i = 0; i < enums.length; ++i) { + const enumValue = enumStringToValue[enums[i]]; + if ((value & enumValue) !== 0) { + orResult |= enumValue; + orEnums.push(glEnumToString(enumValue)); // eslint-disable-line + } + } + if (orResult === value) { + return orEnums.join(' | '); + } else { + return glEnumToString(value); // eslint-disable-line + } + }; + } + + const destBufferBitFieldToString = makeBitFieldToStringFunc([ + 'COLOR_BUFFER_BIT', + 'DEPTH_BUFFER_BIT', + 'STENCIL_BUFFER_BIT', + ]); + + /** + * Which arguments are enums based on the number of arguments to the function. + * So + * 'texImage2D': { + * 9: { 0:true, 2:true, 6:true, 7:true }, + * 6: { 0:true, 2:true, 3:true, 4:true }, + * }, + * + * means if there are 9 arguments then 6 and 7 are enums, if there are 6 + * arguments 3 and 4 are enums. Maybe a function as well in which case + * value is passed to function and returns a string + * + * @type {!Object.<number, (!Object.<number, string>|function)} + */ + const glValidEnumContexts = { + // Generic setters and getters + + 'enable': {1: { 0:true }}, + 'disable': {1: { 0:true }}, + 'getParameter': {1: { 0:true }}, + + // Rendering + + 'drawArrays': {3:{ 0:true }}, + 'drawElements': {4:{ 0:true, 2:true }}, + 'drawArraysInstanced': {4: { 0:true }}, + 'drawElementsInstanced': {5: {0:true, 2: true }}, + 'drawRangeElements': {6: {0:true, 4: true }}, + + // Shaders + + 'createShader': {1: { 0:true }}, + 'getShaderParameter': {2: { 1:true }}, + 'getProgramParameter': {2: { 1:true }}, + 'getShaderPrecisionFormat': {2: { 0: true, 1:true }}, + + // Vertex attributes + + 'getVertexAttrib': {2: { 1:true }}, + 'vertexAttribPointer': {6: { 2:true }}, + 'vertexAttribIPointer': {5: { 2:true }}, // WebGL2 + + // Textures + + 'bindTexture': {2: { 0:true }}, + 'activeTexture': {1: { 0:true }}, + 'getTexParameter': {2: { 0:true, 1:true }}, + 'texParameterf': {3: { 0:true, 1:true }}, + 'texParameteri': {3: { 0:true, 1:true, 2:true }}, + 'texImage2D': { + 9: { 0:true, 2:true, 6:true, 7:true }, + 6: { 0:true, 2:true, 3:true, 4:true }, + 10: { 0:true, 2:true, 6:true, 7:true }, // WebGL2 + }, + 'texImage3D': { + 10: { 0:true, 2:true, 7:true, 8:true }, // WebGL2 + 11: { 0:true, 2:true, 7:true, 8:true }, // WebGL2 + }, + 'texSubImage2D': { + 9: { 0:true, 6:true, 7:true }, + 7: { 0:true, 4:true, 5:true }, + 10: { 0:true, 6:true, 7:true }, // WebGL2 + }, + 'texSubImage3D': { + 11: { 0:true, 8:true, 9:true }, // WebGL2 + 12: { 0:true, 8:true, 9:true }, // WebGL2 + }, + 'texStorage2D': { 5: { 0:true, 2:true }}, // WebGL2 + 'texStorage3D': { 6: { 0:true, 2:true }}, // WebGL2 + 'copyTexImage2D': {8: { 0:true, 2:true }}, + 'copyTexSubImage2D': {8: { 0:true }}, + 'copyTexSubImage3D': {9: { 0:true }}, // WebGL2 + 'generateMipmap': {1: { 0:true }}, + 'compressedTexImage2D': { + 7: { 0: true, 2:true }, + 8: { 0: true, 2:true }, // WebGL2 + }, + 'compressedTexSubImage2D': { + 8: { 0: true, 6:true }, + 9: { 0: true, 6:true }, // WebGL2 + }, + 'compressedTexImage3D': { + 8: { 0: true, 2: true, }, // WebGL2 + 9: { 0: true, 2: true, }, // WebGL2 + }, + 'compressedTexSubImage3D': { + 9: { 0: true, 8: true, }, // WebGL2 + 10: { 0: true, 8: true, }, // WebGL2 + }, + + // Buffer objects + + 'bindBuffer': {2: { 0:true }}, + 'bufferData': { + 3: { 0:true, 2:true }, + 4: { 0:true, 2:true }, // WebGL2 + 5: { 0:true, 2:true }, // WebGL2 + }, + 'bufferSubData': { + 3: { 0:true }, + 4: { 0:true }, // WebGL2 + 5: { 0:true }, // WebGL2 + }, + 'copyBufferSubData': { + 5: { 0:true }, // WeBGL2 + }, + 'getBufferParameter': {2: { 0:true, 1:true }}, + 'getBufferSubData': { + 3: { 0: true, }, // WebGL2 + 4: { 0: true, }, // WebGL2 + 5: { 0: true, }, // WebGL2 + }, + + // Renderbuffers and framebuffers + + 'pixelStorei': {2: { 0:true, 1:true }}, + 'readPixels': { + 7: { 4:true, 5:true }, + 8: { 4:true, 5:true }, // WebGL2 + }, + 'bindRenderbuffer': {2: { 0:true }}, + 'bindFramebuffer': {2: { 0:true }}, + 'blitFramebuffer': {10: { 8: destBufferBitFieldToString, 9:true }}, // WebGL2 + 'checkFramebufferStatus': {1: { 0:true }}, + 'framebufferRenderbuffer': {4: { 0:true, 1:true, 2:true }}, + 'framebufferTexture2D': {5: { 0:true, 1:true, 2:true }}, + 'framebufferTextureLayer': {5: {0:true, 1:true }}, // WebGL2 + 'getFramebufferAttachmentParameter': {3: { 0:true, 1:true, 2:true }}, + 'getInternalformatParameter': {3: {0:true, 1:true, 2:true }}, // WebGL2 + 'getRenderbufferParameter': {2: { 0:true, 1:true }}, + 'invalidateFramebuffer': {2: { 0:true, 1: enumArrayToString, }}, // WebGL2 + 'invalidateSubFramebuffer': {6: {0: true, 1: enumArrayToString, }}, // WebGL2 + 'readBuffer': {1: {0: true}}, // WebGL2 + 'renderbufferStorage': {4: { 0:true, 1:true }}, + 'renderbufferStorageMultisample': {5: { 0: true, 2: true }}, // WebGL2 + + // Frame buffer operations (clear, blend, depth test, stencil) + + 'clear': {1: { 0: destBufferBitFieldToString }}, + 'depthFunc': {1: { 0:true }}, + 'blendFunc': {2: { 0:true, 1:true }}, + 'blendFuncSeparate': {4: { 0:true, 1:true, 2:true, 3:true }}, + 'blendEquation': {1: { 0:true }}, + 'blendEquationSeparate': {2: { 0:true, 1:true }}, + 'stencilFunc': {3: { 0:true }}, + 'stencilFuncSeparate': {4: { 0:true, 1:true }}, + 'stencilMaskSeparate': {2: { 0:true }}, + 'stencilOp': {3: { 0:true, 1:true, 2:true }}, + 'stencilOpSeparate': {4: { 0:true, 1:true, 2:true, 3:true }}, + + // Culling + + 'cullFace': {1: { 0:true }}, + 'frontFace': {1: { 0:true }}, + + // ANGLE_instanced_arrays extension + + 'drawArraysInstancedANGLE': {4: { 0:true }}, + 'drawElementsInstancedANGLE': {5: { 0:true, 2:true }}, + + // EXT_blend_minmax extension + + 'blendEquationEXT': {1: { 0:true }}, + + // Multiple Render Targets + + 'drawBuffersWebGL': {1: {0: enumArrayToString, }}, // WEBGL_draw_bufers + 'drawBuffers': {1: {0: enumArrayToString, }}, // WebGL2 + 'clearBufferfv': { + 4: {0: true }, // WebGL2 + 5: {0: true }, // WebGL2 + }, + 'clearBufferiv': { + 4: {0: true }, // WebGL2 + 5: {0: true }, // WebGL2 + }, + 'clearBufferuiv': { + 4: {0: true }, // WebGL2 + 5: {0: true }, // WebGL2 + }, + 'clearBufferfi': { 4: {0: true}}, // WebGL2 + + // QueryObjects + + 'beginQuery': { 2: { 0: true }}, // WebGL2 + 'endQuery': { 1: { 0: true }}, // WebGL2 + 'getQuery': { 2: { 0: true, 1: true }}, // WebGL2 + 'getQueryParameter': { 2: { 1: true }}, // WebGL2 + + // Sampler Objects + + 'samplerParameteri': { 3: { 1: true }}, // WebGL2 + 'samplerParameterf': { 3: { 1: true }}, // WebGL2 + 'getSamplerParameter': { 2: { 1: true }}, // WebGL2 + + // Sync objects + + 'clientWaitSync': { 3: { 1: makeBitFieldToStringFunc(['SYNC_FLUSH_COMMANDS_BIT']) }}, // WebGL2 + 'fenceSync': { 2: { 0: true }}, // WebGL2 + 'getSyncParameter': { 2: { 1: true }}, // WebGL2 + + // Transform Feedback + + 'bindTransformFeedback': { 2: { 0: true }}, // WebGL2 + 'beginTransformFeedback': { 1: { 0: true }}, // WebGL2 + + // Uniform Buffer Objects and Transform Feedback Buffers + 'bindBufferBase': { 3: { 0: true }}, // WebGL2 + 'bindBufferRange': { 5: { 0: true }}, // WebGL2 + 'getIndexedParameter': { 2: { 0: true }}, // WebGL2 + 'getActiveUniforms': { 3: { 2: true }}, // WebGL2 + 'getActiveUniformBlockParameter': { 3: { 2: true }}, // WebGL2 + }; + + /** + * Gets an string version of an WebGL enum. + * + * Example: + * var str = WebGLDebugUtil.glEnumToString(ctx.getError()); + * + * @param {number} value Value to return an enum for + * @return {string} The string version of the enum. + */ + function glEnumToString(value) { + const name = glEnums[value]; + return (name !== undefined) ? ('gl.' + name) : + ('/*UNKNOWN WebGL ENUM*/ 0x' + value.toString(16) + ''); + } + + /** + * Returns the string version of a WebGL argument. + * Attempts to convert enum arguments to strings. + * @param {string} functionName the name of the WebGL function. + * @param {number} numArgs the number of arguments passed to the function. + * @param {number} argumentIndx the index of the argument. + * @param {*} value The value of the argument. + * @return {string} The value as a string. + */ + function glFunctionArgToString(functionName, numArgs, argumentIndex, value) { + const funcInfos = glValidEnumContexts[functionName]; + if (funcInfos !== undefined) { + const funcInfo = funcInfos[numArgs]; + if (funcInfo !== undefined) { + const argType = funcInfo[argumentIndex]; + if (argType) { + if (typeof argType === 'function') { + return argType(value); + } else { + return glEnumToString(value); + } + } + } + } + if (value === null) { + return 'null'; + } else if (value === undefined) { + return 'undefined'; + } else { + return value.toString(); + } + } + + /** + * Converts the arguments of a WebGL function to a string. + * Attempts to convert enum arguments to strings. + * + * @param {string} functionName the name of the WebGL function. + * @param {number} args The arguments. + * @return {string} The arguments as a string. + */ + function glFunctionArgsToString(functionName, args) { + // apparently we can't do args.join(","); + const argStrs = []; + const numArgs = args.length; + for (let ii = 0; ii < numArgs; ++ii) { + argStrs.push(glFunctionArgToString(functionName, numArgs, ii, args[ii])); + } + return argStrs.join(', '); + } + + function makePropertyWrapper(wrapper, original, propertyName) { + wrapper.__defineGetter__(propertyName, function() { // eslint-disable-line + return original[propertyName]; + }); + // TODO(gmane): this needs to handle properties that take more than + // one value? + wrapper.__defineSetter__(propertyName, function(value) { // eslint-disable-line + original[propertyName] = value; + }); + } + + /** + * Given a WebGL context returns a wrapped context that calls + * gl.getError after every command and calls a function if the + * result is not gl.NO_ERROR. + * + * @param {!WebGLRenderingContext} ctx The webgl context to + * wrap. + * @param {!function(err, funcName, args): void} opt_onErrorFunc + * The function to call when gl.getError returns an + * error. If not specified the default function calls + * console.log with a message. + * @param {!function(funcName, args): void} opt_onFunc The + * function to call when each webgl function is called. + * You can use this to log all calls for example. + * @param {!WebGLRenderingContext} opt_err_ctx The webgl context + * to call getError on if different than ctx. + */ + function makeDebugContext(ctx, options) { + options = options || {}; + const errCtx = options.errCtx || ctx; + const onFunc = options.funcFunc; + const sharedState = options.sharedState || { + numDrawCallsRemaining: options.maxDrawCalls || -1, + wrappers: {}, + }; + options.sharedState = sharedState; + + const errorFunc = options.errorFunc || function(err, functionName, args) { + console.error(`WebGL error ${glEnumToString(err)} in ${functionName}(${glFunctionArgsToString(functionName, args)})`); /* eslint-disable-line no-console */ + }; + + // Holds booleans for each GL error so after we get the error ourselves + // we can still return it to the client app. + const glErrorShadow = { }; + const wrapper = {}; + + function removeChecks() { + Object.keys(sharedState.wrappers).forEach(function(name) { + const pair = sharedState.wrappers[name]; + const wrapper = pair.wrapper; + const orig = pair.orig; + for (const propertyName in wrapper) { + if (typeof wrapper[propertyName] === 'function') { + wrapper[propertyName] = orig[propertyName].bind(orig); + } + } + }); + } + + function checkMaxDrawCalls() { + if (sharedState.numDrawCallsRemaining === 0) { + removeChecks(); + } + --sharedState.numDrawCallsRemaining; + } + + function noop() { + } + + // Makes a function that calls a WebGL function and then calls getError. + function makeErrorWrapper(ctx, functionName) { + const check = functionName.substring(0, 4) === 'draw' ? checkMaxDrawCalls : noop; + return function() { + if (onFunc) { + onFunc(functionName, arguments); + } + const result = ctx[functionName].apply(ctx, arguments); + const err = errCtx.getError(); + if (err !== 0) { + glErrorShadow[err] = true; + errorFunc(err, functionName, arguments); + } + check(); + return result; + }; + } + + function makeGetExtensionWrapper(ctx, wrapped) { + return function() { + const extensionName = arguments[0]; + let ext = sharedState.wrappers[extensionName]; + if (!ext) { + ext = wrapped.apply(ctx, arguments); + if (ext) { + const origExt = ext; + ext = makeDebugContext(ext, options); + sharedState.wrappers[extensionName] = { wrapper: ext, orig: origExt }; + addEnumsForContext(origExt, extensionName); + } + } + return ext; + }; + } + + // Make a an object that has a copy of every property of the WebGL context + // but wraps all functions. + for (const propertyName in ctx) { + if (typeof ctx[propertyName] === 'function') { + if (propertyName !== 'getExtension') { + wrapper[propertyName] = makeErrorWrapper(ctx, propertyName); + } else { + const wrapped = makeErrorWrapper(ctx, propertyName); + wrapper[propertyName] = makeGetExtensionWrapper(ctx, wrapped); + } + } else { + makePropertyWrapper(wrapper, ctx, propertyName); + } + } + + // Override the getError function with one that returns our saved results. + if (wrapper.getError) { + wrapper.getError = function() { + for (const err in glErrorShadow) { + if (glErrorShadow.hasOwnProperty(err)) { + if (glErrorShadow[err]) { + glErrorShadow[err] = false; + return err; + } + } + } + return ctx.NO_ERROR; + }; + } + + if (wrapper.bindBuffer) { + sharedState.wrappers['webgl'] = { wrapper: wrapper, orig: ctx }; + addEnumsForContext(ctx, ctx.bindBufferBase ? 'WebGL2' : 'WebGL'); + } + + return wrapper; + } + + //------------ + + function captureJSErrors() { + // capture JavaScript Errors + self.addEventListener('error', function(e) { + const msg = e.message || e.error; + const url = e.filename; + const lineNo = e.lineno || 1; + const colNo = e.colno || 1; + sendMessage({ + type: 'jsError', + lineNo, + colNo, + url, + msg, + }); + }); + } + + + const isWebGLRE = /^(webgl|webgl2|experimental-webgl)$/i; + function installWebGLLessonSetup() { + OffscreenCanvas.prototype.getContext = (function(oldFn) { + return function() { + const type = arguments[0]; + const isWebGL = isWebGLRE.test(type); + if (isWebGL) { + setupLesson(this); + } + const args = [].slice.apply(arguments); + args[1] = Object.assign({ + powerPreference: 'low-power', + }, args[1]); + return oldFn.apply(this, args); + }; + }(OffscreenCanvas.prototype.getContext)); + } + + function installWebGLDebugContextCreator() { + // capture GL errors + OffscreenCanvas.prototype.getContext = (function(oldFn) { + return function() { + let ctx = oldFn.apply(this, arguments); + // Using bindTexture to see if it's WebGL. Could check for instanceof WebGLRenderingContext + // but that might fail if wrapped by debugging extension + if (ctx && ctx.bindTexture) { + ctx = makeDebugContext(ctx, { + maxDrawCalls: 100, + errorFunc: function(err, funcName, args) { + const numArgs = args.length; + const enumedArgs = [].map.call(args, function(arg, ndx) { + let str = glFunctionArgToString(funcName, numArgs, ndx, arg); + // shorten because of long arrays + if (str.length > 200) { + str = str.substring(0, 200) + '...'; + } + return str; + }); + + { + const error = new Error(); + sendMessage({ + type: 'jsErrorWithStack', + stack: error.stack, + msg: `${glEnumToString(err)} in ${funcName}(${enumedArgs.join(', ')})`, + }); + } + }, + }); + } + return ctx; + }; + }(OffscreenCanvas.prototype.getContext)); + } + + installWebGLLessonSetup(); + + if (isInEditor()) { + setupConsole(); + captureJSErrors(); + if (lessonSettings.glDebug !== false) { + installWebGLDebugContextCreator(); + } + } + +}()); +
true
Other
mrdoob
three.js
929c4ec8cd7c6744926a827a03d09f38b402965f.json
add suggestion link
threejs/lessons/langinfo.hanson
@@ -5,7 +5,7 @@ title: 'three.js fundamentals', description: 'Learn Three.js', link: 'http://threejsfundamentals.org/', - commentSectionHeader: '<div>Questions? <a href="http://stackoverflow.com/questions/tagged/three.js">Ask on stackoverflow</a>.</div>\n <div>Issue/Bug? <a href="http://github.com/greggman/threejsfundamentals/issues">Create an issue on github</a>.</div>', + commentSectionHeader: '<div>Questions? <a href="http://stackoverflow.com/questions/tagged/three.js">Ask on stackoverflow</a>.</div>\n <div><a href="https://github.com/greggman/threejsfundamentals/issues/new?assignees=&labels=suggested+topic&template=suggest-topic.md&title=%5BSUGGESTION%5D">Suggestion</a>? <a href="https://github.com/greggman/threejsfundamentals/issues/new?assignees=&labels=&template=request.md&title=">Request</a>? <a href="https://github.com/greggman/threejsfundamentals/issues/new?assignees=&labels=bug+%2F+issue&template=bug-issue-report.md&title=">Issue</a>? <a href="https://github.com/greggman/threejsfundamentals/issues/new?assignees=&labels=bug+%2F+issue&template=bug-issue-report.md&title=">Bug</a>?</div>', missing: "Sorry this article has not been translated yet. [Translations Welcome](https://github.com/greggman/threejsfundamentals)! 😄\n\n[Here's the original English article for now]({{{origLink}}}).", toc: 'Table of Contents', }
false
Other
mrdoob
three.js
849d8a8676fc251fa26d1ffce419df388e1cedc3.json
add webvr point to select article
threejs/lessons/threejs-webvr-point-to-select.md
@@ -0,0 +1,382 @@ +Title: Three.js WebVR - 3DOF Point to Select +Description: How to implement 3DOF Point to Select. + +**NOTE: The examples on this page require a VR capable +device with a pointing device. Without one they won't work. See [this article](threejs-webvr.html) +as to why** + +In the [previous article](threejs-webvr-look-to-select.html) we went over +a very simple WebVR example where we let the user choose things by +pointing via looking. In this article we will take it one step further +and let the user choose with a pointing device + +Three.js makes is relatively easy by providing 2 controller objects in VR +and tries to handle both cases of a single 3DOF controller and two 6DOF +controllers. Each of the controllers are `Object3D` objects which give +the orientation and position of that controller. They also provide +`selectstart`, `select` and `selectend` events when the user starts pressing, +is pressing, and stops pressing (ends) the "main" button on the controller. + +Starting with the last example from [the previous article](threejs-webvr-look-to-select.html) +let's change the `PickHelper` into a `ControllerPickHelper`. + +Our new implementation will emit a `select` event that gives us the object that was picked +so to use it we'll just need to do this. + +```js +const pickHelper = new ControllerPickHelper(scene); +pickHelper.addEventListener('select', (event) => { + event.selectedObject.visible = false; + const partnerObject = meshToMeshMap.get(event.selectedObject); + partnerObject.visible = true; +}); +``` + +Remember from our previous code `meshToMeshMap` maps our boxes and spheres to +each other so if we have one we can look up its partner through `meshToMeshMap` +so here we're just hiding the selected object and un-hiding its partner. + +As for the actual implementation of `ControllerPickHelper`, first we need +to add the VR controller objects to the scene and to those add some 3D lines +we can use to display where the user is pointing. We save off both the controllers +and the their lines. + +```js +class ControllerPickHelper { + constructor(scene) { + const pointerGeometry = new THREE.BufferGeometry().setFromPoints([ + new THREE.Vector3(0, 0, 0), + new THREE.Vector3(0, 0, -1), + ]); + + this.controllers = []; + for (let i = 0; i < 2; ++i) { + const controller = renderer.vr.getController(i); + scene.add(controller); + + const line = new THREE.Line(pointerGeometry); + line.scale.z = 5; + controller.add(line); + this.controllers.push({controller, line}); + } + } +} +``` + +Without doing anything else this alone would give us 1 or 2 lines in the scene +showing where the user's pointing devices are and which way they are pointing. + +Next let's add some code to pick from the controllers. This is the first time +we've picked with something not the camera. In our [article on picking](threejs-picking.html) +the user uses the mouse or finger to pick which means picking comes from the camera +into the screen. In [the previous article](threejs-webvr-look-to-select.html) we +were picking based on which way the user is looking so again that comes from the +camera. This time though we're picking from the position of the controllers so +we're not using the camera. + +```js +class ControllerPickHelper { + constructor(scene) { ++ this.raycaster = new THREE.Raycaster(); ++ this.objectToColorMap = new Map(); ++ this.controllerToObjectMap = new Map(); ++ this.tempMatrix = new THREE.Matrix4(); + + const pointerGeometry = new THREE.BufferGeometry().setFromPoints([ + new THREE.Vector3(0, 0, 0), + new THREE.Vector3(0, 0, -1), + ]); + + this.controllers = []; + for (let i = 0; i < 2; ++i) { + const controller = renderer.vr.getController(i); + scene.add(controller); + + const line = new THREE.Line(pointerGeometry); + line.scale.z = 5; + controller.add(line); + this.controllers.push({controller, line}); + } + } ++ update(scene, time) { ++ this.reset(); ++ for (const {controller, line} of this.controllers) { ++ // cast a ray through the from the controller ++ this.tempMatrix.identity().extractRotation(controller.matrixWorld); ++ this.raycaster.ray.origin.setFromMatrixPosition(controller.matrixWorld); ++ this.raycaster.ray.direction.set(0, 0, -1).applyMatrix4(this.tempMatrix); ++ // get the list of objects the ray intersected ++ const intersections = this.raycaster.intersectObjects(scene.children); ++ if (intersections.length) { ++ const intersection = intersections[0]; ++ // make the line touch the object ++ line.scale.z = intersection.distance; ++ // pick the first object. It's the closest one ++ const pickedObject = intersection.object; ++ // save which object this controller picked ++ this.controllerToObjectMap.set(controller, pickedObject); ++ // highlight the object if we haven't already ++ if (this.objectToColorMap.get(pickedObject) === undefined) { ++ // save its color ++ this.objectToColorMap.set(pickedObject, pickedObject.material.emissive.getHex()); ++ // set its emissive color to flashing red/yellow ++ pickedObject.material.emissive.setHex((time * 8) % 2 > 1 ? 0xFF2000 : 0xFF0000); ++ } ++ } else { ++ line.scale.z = 5; ++ } ++ } ++ } +} +``` + +Like before we use a `Raycaster` but this time we take the ray from the controller. +Our previous `PickHelper` there was only one thing picking but here we have up to 2 +controllers, one for each hand. We save off which object each controller is +looking at in `controllerToObjectMap`. We also save off the original emissive color in +`objectToColorMap` and we make the line long enough to touch whatever it's pointing at. + +We need to add some code to reset these settings every frame. + +```js +class ControllerPickHelper { + + ... + ++ _reset() { ++ // restore the colors ++ this.objectToColorMap.forEach((color, object) => { ++ object.material.emissive.setHex(color); ++ }); ++ this.objectToColorMap.clear(); ++ this.controllerToObjectMap.clear(); ++ } + update(scene, time) { ++ this._reset(); + + ... + +} +``` + +Next we want to emit a `select` event when the user clicks the controller. +To do that we can extend three.js's `EventDispatcher` and then we'll check +when we get a `select` event from the controller, then if that controller +is pointing at something we emit what that controller is pointing at +as our own `select` event. + +```js +-class ControllerPickHelper { ++class ControllerPickHelper extends THREE.EventDispatcher { + constructor(scene) { ++ super(); + this.raycaster = new THREE.Raycaster(); + this.objectToColorMap = new Map(); // object to save color and picked object + this.controllerToObjectMap = new Map(); + this.tempMatrix = new THREE.Matrix4(); + + const pointerGeometry = new THREE.BufferGeometry().setFromPoints([ + new THREE.Vector3(0, 0, 0), + new THREE.Vector3(0, 0, -1), + ]); + + this.controllers = []; + for (let i = 0; i < 2; ++i) { + const controller = renderer.vr.getController(i); ++ controller.addEventListener('select', (event) => { ++ const controller = event.target; ++ const selectedObject = this.controllerToObjectMap.get(controller); ++ if (selectedObject) { ++ this.dispatchEvent({type: 'select', controller, selectedObject}); ++ } ++ }); + scene.add(controller); + + const line = new THREE.Line(pointerGeometry); + line.scale.z = 5; + controller.add(line); + this.controllers.push({controller, line}); + } + } +} +``` + +All that is left is to call `update` in our render loop + +```js +function render(time) { + + ... + ++ pickHelper.update(scene, time); + + renderer.render(scene, camera); +} +``` + +and assuming you have a VR device with a controller you should +be able to use the controllers to pick things. + +{{{example url="../threejs-webvr-point-to-select.html" }}} + +And what if we wanted to be able to move the objects? + +That's relatively easy. Let's move our controller 'select' listener +code out into a function so we can use it for more than one thing. + +```js +class ControllerPickHelper extends THREE.EventDispatcher { + constructor(scene) { + super(); + + ... + + this.controllers = []; + ++ const selectListener = (event) => { ++ const controller = event.target; ++ const selectedObject = this.controllerToObjectMap.get(event.target); ++ if (selectedObject) { ++ this.dispatchEvent({type: 'select', controller, selectedObject}); ++ } ++ }; + + for (let i = 0; i < 2; ++i) { + const controller = renderer.vr.getController(i); +- controller.addEventListener('select', (event) => { +- const controller = event.target; +- const selectedObject = this.controllerToObjectMap.get(event.target); +- if (selectedObject) { +- this.dispatchEvent({type: 'select', controller, selectedObject}); +- } +- }); ++ controller.addEventListener('select', selectListener); + + ... +``` + +Then let's use it for both `selectstart` and `select` + +```js +class ControllerPickHelper extends THREE.EventDispatcher { + constructor(scene) { + super(); + + ... + + this.controllers = []; + + const selectListener = (event) => { + const controller = event.target; + const selectedObject = this.controllerToObjectMap.get(event.target); + if (selectedObject) { +- this.dispatchEvent({type: 'select', controller, selectedObject}); ++ this.dispatchEvent({type: event.type, controller, selectedObject}); + } + }; + + for (let i = 0; i < 2; ++i) { + const controller = renderer.vr.getController(i); + controller.addEventListener('select', selectListener); + controller.addEventListener('selectstart', selectListener); + + ... +``` + +and let's also pass on the `selectend` event which three.js sends out +when you user lets of the button on the controller. + +```js +class ControllerPickHelper extends THREE.EventDispatcher { + constructor(scene) { + super(); + + ... + + this.controllers = []; + + const selectListener = (event) => { + const controller = event.target; + const selectedObject = this.controllerToObjectMap.get(event.target); + if (selectedObject) { + this.dispatchEvent({type: event.type, controller, selectedObject}); + } + }; + ++ const endListener = (event) => { ++ const controller = event.target; ++ this.dispatchEvent({type: event.type, controller}); ++ }; + + for (let i = 0; i < 2; ++i) { + const controller = renderer.vr.getController(i); + controller.addEventListener('select', selectListener); + controller.addEventListener('selectstart', selectListener); ++ controller.addEventListener('selectend', endListener); + + ... +``` + +Now let's change the code so when we get a `selectstart` event we'll +remove the selected object from the scene and make it a child of the controller. +This means it will move with the controller. When we get a `selectend` +event we'll put it back in the scene. + +```js +const pickHelper = new ControllerPickHelper(scene); +-pickHelper.addEventListener('select', (event) => { +- event.selectedObject.visible = false; +- const partnerObject = meshToMeshMap.get(event.selectedObject); +- partnerObject.visible = true; +-}); + ++const controllerToSelection = new Map(); ++pickHelper.addEventListener('selectstart', (event) => { ++ const {controller, selectedObject} = event; ++ const existingSelection = controllerToSelection.get(controller); ++ if (!existingSelection) { ++ controllerToSelection.set(controller, { ++ object: selectedObject, ++ parent: selectedObject.parent, ++ }); ++ THREE.SceneUtils.detach(selectedObject, selectedObject.parent, scene); ++ THREE.SceneUtils.attach(selectedObject, scene, controller); ++ } ++}); ++ ++pickHelper.addEventListener('selectend', (event) => { ++ const {controller} = event; ++ const selection = controllerToSelection.get(controller); ++ if (selection) { ++ controllerToSelection.delete(controller); ++ THREE.SceneUtils.detach(selection.object, controller, scene); ++ THREE.SceneUtils.attach(selection.object, scene, selection.parent); ++ } ++}); +``` + +When an object is selected we save off that object and its +original parent. When the user is done we can put the object back. + +We use the `SceneUtils.detach` and `SceneUtils.attach` to re-parent +the selected objects. These functions let us change the parent +of an object without changing its orientation and position in the +scene. + +We need to include them. + +```html +<script src="resources/threejs/r103/three.min.js"></script> +<script src="resources/threejs/r103/js/vr/WebVR.js"></script> ++<script src="resources/threejs/r103/js/utils/SceneUtils.js"></script> +``` + +And with that we should be able to move the objects around with a 6DOF +controller or at least change their orientation with a 3DOF controller + +{{{example url="../threejs-webvr-point-to-select-w-move.html" }}} + +To be honest I'm not 100% sure this `ControllerPickHelper` is +the best way to organize the code but it's useful to demonstrating +the various parts of getting something simple working in VR +in three.js
true
Other
mrdoob
three.js
849d8a8676fc251fa26d1ffce419df388e1cedc3.json
add webvr point to select article
threejs/lessons/toc.html
@@ -25,6 +25,7 @@ <ul> <li><a href="/threejs/lessons/threejs-webvr.html">WebVR - Basics</a></li> <li><a href="/threejs/lessons/threejs-webvr-look-to-select.html">WebVR - Look To Select</a></li> + <li><a href="/threejs/lessons/threejs-webvr-point-to-select.html">WebVR - Point To Select</a></li> </ul> <li>Optimization</li> <ul>
true
Other
mrdoob
three.js
849d8a8676fc251fa26d1ffce419df388e1cedc3.json
add webvr point to select article
threejs/threejs-webvr-point-to-select-w-move.html
@@ -0,0 +1,247 @@ +<!-- Licensed under a BSD license. See license.html for license --> +<!DOCTYPE html> +<html> + <head> + <meta charset="utf-8"> + <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes"> + <title>Three.js - WebVR - Point to Select w/Move</title> + <style> + body { + margin: 0; + } + #c { + width: 100vw; + height: 100vh; + display: block; + } + </style> + </head> + <body> + <canvas id="c"></canvas> + </body> +<script src="resources/threejs/r103/three.min.js"></script> +<script src="resources/threejs/r103/js/vr/WebVR.js"></script> +<script src="resources/threejs/r103/js/utils/SceneUtils.js"></script> +<script> +'use strict'; + +/* global THREE, WEBVR */ + +function main() { + const canvas = document.querySelector('#c'); + const renderer = new THREE.WebGLRenderer({canvas}); + renderer.vr.enabled = true; + document.body.appendChild(WEBVR.createButton(renderer)); + + const fov = 75; + const aspect = 2; // the canvas default + const near = 0.1; + const far = 50; + const camera = new THREE.PerspectiveCamera(fov, aspect, near, far); + + const scene = new THREE.Scene(); + { + const loader = new THREE.CubeTextureLoader(); + const texture = loader.load([ + 'resources/images/grid-1024.png', + 'resources/images/grid-1024.png', + 'resources/images/grid-1024.png', + 'resources/images/grid-1024.png', + 'resources/images/grid-1024.png', + 'resources/images/grid-1024.png', + ]); + scene.background = texture; + } + + { + const color = 0xFFFFFF; + const intensity = 1; + const light = new THREE.DirectionalLight(color, intensity); + light.position.set(-1, 2, 4); + scene.add(light); + } + + const boxWidth = 1; + const boxHeight = 1; + const boxDepth = 1; + const boxGeometry = new THREE.BoxBufferGeometry(boxWidth, boxHeight, boxDepth); + + const sphereRadius = 0.5; + const sphereGeometry = new THREE.SphereBufferGeometry(sphereRadius); + + function makeInstance(geometry, color, x) { + const material = new THREE.MeshPhongMaterial({color}); + + const cube = new THREE.Mesh(geometry, material); + scene.add(cube); + + cube.position.x = x; + cube.position.y = 1.6; + cube.position.z = -2; + + return cube; + } + + const meshToMeshMap = new Map(); + [ + { x: 0, boxColor: 0x44aa88, sphereColor: 0xFF4444, }, + { x: 2, boxColor: 0x8844aa, sphereColor: 0x44FF44, }, + { x: -2, boxColor: 0xaa8844, sphereColor: 0x4444FF, }, + ].forEach((info) => { + const {x, boxColor, sphereColor} = info; + const sphere = makeInstance(sphereGeometry, sphereColor, x); + const box = makeInstance(boxGeometry, boxColor, x); + // hide the sphere + sphere.visible = false; + // map the sphere to the box + meshToMeshMap.set(box, sphere); + // map the box to the sphere + meshToMeshMap.set(sphere, box); + }); + + class ControllerPickHelper extends THREE.EventDispatcher { + constructor(scene) { + super(); + this.raycaster = new THREE.Raycaster(); + this.objectToColorMap = new Map(); + this.controllerToObjectMap = new Map(); + this.tempMatrix = new THREE.Matrix4(); + + const pointerGeometry = new THREE.BufferGeometry().setFromPoints([ + new THREE.Vector3(0, 0, 0), + new THREE.Vector3(0, 0, -1), + ]); + + this.controllers = []; + + const selectListener = (event) => { + const controller = event.target; + const selectedObject = this.controllerToObjectMap.get(event.target); + if (selectedObject) { + this.dispatchEvent({type: event.type, controller, selectedObject}); + } + }; + + const endListener = (event) => { + const controller = event.target; + this.dispatchEvent({type: event.type, controller}); + }; + + for (let i = 0; i < 2; ++i) { + const controller = renderer.vr.getController(i); + controller.addEventListener('select', selectListener); + controller.addEventListener('selectstart', selectListener); + controller.addEventListener('selectend', endListener); + scene.add(controller); + + const line = new THREE.Line(pointerGeometry); + line.scale.z = 5; + controller.add(line); + this.controllers.push({controller, line}); + } + } + reset() { + // restore the colors + this.objectToColorMap.forEach((color, object) => { + object.material.emissive.setHex(color); + }); + this.objectToColorMap.clear(); + this.controllerToObjectMap.clear(); + } + update(scene, time) { + this.reset(); + for (const {controller, line} of this.controllers) { + // cast a ray through the from the controller + this.tempMatrix.identity().extractRotation(controller.matrixWorld); + this.raycaster.ray.origin.setFromMatrixPosition(controller.matrixWorld); + this.raycaster.ray.direction.set(0, 0, -1).applyMatrix4(this.tempMatrix); + // get the list of objects the ray intersected + const intersections = this.raycaster.intersectObjects(scene.children); + if (intersections.length) { + const intersection = intersections[0]; + // make the line touch the object + line.scale.z = intersection.distance; + // pick the first object. It's the closest one + const pickedObject = intersection.object; + // save which object this controller picked + this.controllerToObjectMap.set(controller, pickedObject); + // highlight the object if we haven't already + if (this.objectToColorMap.get(pickedObject) === undefined) { + // save its color + this.objectToColorMap.set(pickedObject, pickedObject.material.emissive.getHex()); + // set its emissive color to flashing red/yellow + pickedObject.material.emissive.setHex((time * 8) % 2 > 1 ? 0xFF2000 : 0xFF0000); + } + } else { + line.scale.z = 5; + } + } + } + } + + const controllerToSelection = new Map(); + const pickHelper = new ControllerPickHelper(scene); + pickHelper.addEventListener('selectstart', (event) => { + const {controller, selectedObject} = event; + const existingSelection = controllerToSelection.get(controller); + if (!existingSelection) { + controllerToSelection.set(controller, { + object: selectedObject, + parent: selectedObject.parent, + }); + THREE.SceneUtils.detach(selectedObject, selectedObject.parent, scene); + THREE.SceneUtils.attach(selectedObject, scene, controller); + } + }); + + pickHelper.addEventListener('selectend', (event) => { + const {controller} = event; + const selection = controllerToSelection.get(controller); + if (selection) { + controllerToSelection.delete(controller); + THREE.SceneUtils.detach(selection.object, controller, scene); + THREE.SceneUtils.attach(selection.object, scene, selection.parent); + } + }); + + function resizeRendererToDisplaySize(renderer) { + const canvas = renderer.domElement; + const width = canvas.clientWidth; + const height = canvas.clientHeight; + const needResize = canvas.width !== width || canvas.height !== height; + if (needResize) { + renderer.setSize(width, height, false); + } + return needResize; + } + + function render(time) { + time *= 0.001; + + if (!renderer.vr.isPresenting() && resizeRendererToDisplaySize(renderer)) { + const canvas = renderer.domElement; + camera.aspect = canvas.clientWidth / canvas.clientHeight; + camera.updateProjectionMatrix(); + } + + let ndx = 0; + for (const mesh of meshToMeshMap.keys()) { + const speed = 1 + ndx * .1; + const rot = time * speed; + mesh.rotation.x = rot; + mesh.rotation.y = rot; + ++ndx; + } + + pickHelper.update(scene, time); + + renderer.render(scene, camera); + } + + renderer.setAnimationLoop(render); +} + +main(); +</script> +</html> +
true
Other
mrdoob
three.js
849d8a8676fc251fa26d1ffce419df388e1cedc3.json
add webvr point to select article
threejs/threejs-webvr-point-to-select.html
@@ -0,0 +1,218 @@ +<!-- Licensed under a BSD license. See license.html for license --> +<!DOCTYPE html> +<html> + <head> + <meta charset="utf-8"> + <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes"> + <title>Three.js - WebVR - Point to Select</title> + <style> + body { + margin: 0; + } + #c { + width: 100vw; + height: 100vh; + display: block; + } + </style> + </head> + <body> + <canvas id="c"></canvas> + </body> +<script src="resources/threejs/r103/three.min.js"></script> +<script src="resources/threejs/r103/js/vr/WebVR.js"></script> +<script> +'use strict'; + +/* global THREE, WEBVR */ + +function main() { + const canvas = document.querySelector('#c'); + const renderer = new THREE.WebGLRenderer({canvas}); + renderer.vr.enabled = true; + document.body.appendChild(WEBVR.createButton(renderer)); + + const fov = 75; + const aspect = 2; // the canvas default + const near = 0.1; + const far = 50; + const camera = new THREE.PerspectiveCamera(fov, aspect, near, far); + + const scene = new THREE.Scene(); + { + const loader = new THREE.CubeTextureLoader(); + const texture = loader.load([ + 'resources/images/grid-1024.png', + 'resources/images/grid-1024.png', + 'resources/images/grid-1024.png', + 'resources/images/grid-1024.png', + 'resources/images/grid-1024.png', + 'resources/images/grid-1024.png', + ]); + scene.background = texture; + } + + { + const color = 0xFFFFFF; + const intensity = 1; + const light = new THREE.DirectionalLight(color, intensity); + light.position.set(-1, 2, 4); + scene.add(light); + } + + const boxWidth = 1; + const boxHeight = 1; + const boxDepth = 1; + const boxGeometry = new THREE.BoxBufferGeometry(boxWidth, boxHeight, boxDepth); + + const sphereRadius = 0.5; + const sphereGeometry = new THREE.SphereBufferGeometry(sphereRadius); + + function makeInstance(geometry, color, x) { + const material = new THREE.MeshPhongMaterial({color}); + + const cube = new THREE.Mesh(geometry, material); + scene.add(cube); + + cube.position.x = x; + cube.position.y = 1.6; + cube.position.z = -2; + + return cube; + } + + const meshToMeshMap = new Map(); + [ + { x: 0, boxColor: 0x44aa88, sphereColor: 0xFF4444, }, + { x: 2, boxColor: 0x8844aa, sphereColor: 0x44FF44, }, + { x: -2, boxColor: 0xaa8844, sphereColor: 0x4444FF, }, + ].forEach((info) => { + const {x, boxColor, sphereColor} = info; + const sphere = makeInstance(sphereGeometry, sphereColor, x); + const box = makeInstance(boxGeometry, boxColor, x); + // hide the sphere + sphere.visible = false; + // map the sphere to the box + meshToMeshMap.set(box, sphere); + // map the box to the sphere + meshToMeshMap.set(sphere, box); + }); + + class ControllerPickHelper extends THREE.EventDispatcher { + constructor(scene) { + super(); + this.raycaster = new THREE.Raycaster(); + this.objectToColorMap = new Map(); + this.controllerToObjectMap = new Map(); + this.tempMatrix = new THREE.Matrix4(); + + const pointerGeometry = new THREE.BufferGeometry().setFromPoints([ + new THREE.Vector3(0, 0, 0), + new THREE.Vector3(0, 0, -1), + ]); + + this.controllers = []; + for (let i = 0; i < 2; ++i) { + const controller = renderer.vr.getController(i); + controller.addEventListener('select', (event) => { + const controller = event.target; + const selectedObject = this.controllerToObjectMap.get(controller); + if (selectedObject) { + this.dispatchEvent({type: 'select', controller, selectedObject}); + } + }); + scene.add(controller); + + const line = new THREE.Line(pointerGeometry); + line.scale.z = 5; + controller.add(line); + this.controllers.push({controller, line}); + } + } + reset() { + // restore the colors + this.objectToColorMap.forEach((color, object) => { + object.material.emissive.setHex(color); + }); + this.objectToColorMap.clear(); + this.controllerToObjectMap.clear(); + } + update(scene, time) { + this.reset(); + for (const {controller, line} of this.controllers) { + // cast a ray through the from the controller + this.tempMatrix.identity().extractRotation(controller.matrixWorld); + this.raycaster.ray.origin.setFromMatrixPosition(controller.matrixWorld); + this.raycaster.ray.direction.set(0, 0, -1).applyMatrix4(this.tempMatrix); + // get the list of objects the ray intersected + const intersections = this.raycaster.intersectObjects(scene.children); + if (intersections.length) { + const intersection = intersections[0]; + // make the line touch the object + line.scale.z = intersection.distance; + // pick the first object. It's the closest one + const pickedObject = intersection.object; + // save which object this controller picked + this.controllerToObjectMap.set(controller, pickedObject); + // highlight the object if we haven't already + if (this.objectToColorMap.get(pickedObject) === undefined) { + // save its color + this.objectToColorMap.set(pickedObject, pickedObject.material.emissive.getHex()); + // set its emissive color to flashing red/yellow + pickedObject.material.emissive.setHex((time * 8) % 2 > 1 ? 0xFF2000 : 0xFF0000); + } + } else { + line.scale.z = 5; + } + } + } + } + + const pickHelper = new ControllerPickHelper(scene); + pickHelper.addEventListener('select', (event) => { + event.selectedObject.visible = false; + const partnerObject = meshToMeshMap.get(event.selectedObject); + partnerObject.visible = true; + }); + + function resizeRendererToDisplaySize(renderer) { + const canvas = renderer.domElement; + const width = canvas.clientWidth; + const height = canvas.clientHeight; + const needResize = canvas.width !== width || canvas.height !== height; + if (needResize) { + renderer.setSize(width, height, false); + } + return needResize; + } + + function render(time) { + time *= 0.001; + + if (!renderer.vr.isPresenting() && resizeRendererToDisplaySize(renderer)) { + const canvas = renderer.domElement; + camera.aspect = canvas.clientWidth / canvas.clientHeight; + camera.updateProjectionMatrix(); + } + + let ndx = 0; + for (const mesh of meshToMeshMap.keys()) { + const speed = 1 + ndx * .1; + const rot = time * speed; + mesh.rotation.x = rot; + mesh.rotation.y = rot; + ++ndx; + } + + pickHelper.update(scene, time); + + renderer.render(scene, camera); + } + + renderer.setAnimationLoop(render); +} + +main(); +</script> +</html> +
true
Other
mrdoob
three.js
3d96d13d8e752774239a9ecc573069b4ae93ca57.json
switch meshes instead of changing background
threejs/lessons/threejs-webvr-look-to-select.md
@@ -384,82 +384,80 @@ time. If so we add the elapsed time to a timer and if the timer reaches it's limit we return the selected item. Now let's use that to pick the cubes. As a simple example -we'll just change the background texture to match the -selected cube. +we'll add 3 spheres as well. When a cube is picked with hide +the cube and un-hide the corresponding sphere. -First let's change the code we had for loading a cubemap -into something a little more -[D.R.Y.](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself). +So first we'll make a sphere geometry ```js --{ -- const loader = new THREE.CubeTextureLoader(); -- const texture = loader.load([ -- 'resources/images/grid-1024.png', -- 'resources/images/grid-1024.png', -- 'resources/images/grid-1024.png', -- 'resources/images/grid-1024.png', -- 'resources/images/grid-1024.png', -- 'resources/images/grid-1024.png', -- ]); -- scene.background = texture; --} - -+const loader = new THREE.CubeTextureLoader(); -+function loadCubemap(url) { -+ return loader.load([url, url, url, url, url, url]); -+} -+scene.background = loadCubemap('resources/images/grid-1024.png'); +const boxWidth = 1; +const boxHeight = 1; +const boxDepth = 1; +-const geometry = new THREE.BoxBufferGeometry(boxWidth, boxHeight, boxDepth); ++const boxGeometry = new THREE.BoxBufferGeometry(boxWidth, boxHeight, boxDepth); ++ ++const sphereRadius = 0.5; ++const sphereGeometry = new THREE.SphereBufferGeometry(sphereRadius); ``` -Then we'll load 3 more cubemap textures, one for each cube. We'll +Then let's create 3 pairs of box and sphere meshes. We'll use a [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) -so that we can associate a `Mesh` with a texture. +so that we can associate each `Mesh` with it's partner. ```js -const cubes = [ - makeInstance(geometry, 0x44aa88, 0), - makeInstance(geometry, 0x8844aa, -2), - makeInstance(geometry, 0xaa8844, 2), -]; -+const cubeToTextureMap = new Map(); -+cubeToTextureMap.set( -+ makeInstance(geometry, 0x44aa88, 0), -+ loadCubemap('resources/images/grid-cyan-1024.png')); -+cubeToTextureMap.set( -+ makeInstance(geometry, 0x8844aa, -2), -+ loadCubemap('resources/images/grid-purple-1024.png')); -+cubeToTextureMap.set( -+ makeInstance(geometry, 0xaa8844, 2), -+ loadCubemap('resources/images/grid-gold-1024.png')); ++const meshToMeshMap = new Map(); ++[ ++ { x: 0, boxColor: 0x44aa88, sphereColor: 0xFF4444, }, ++ { x: 2, boxColor: 0x8844aa, sphereColor: 0x44FF44, }, ++ { x: -2, boxColor: 0xaa8844, sphereColor: 0x4444FF, }, ++].forEach((info) => { ++ const {x, boxColor, sphereColor} = info; ++ const sphere = makeInstance(sphereGeometry, sphereColor, x); ++ const box = makeInstance(boxGeometry, boxColor, x); ++ // hide the sphere ++ sphere.visible = false; ++ // map the sphere to the box ++ meshToMeshMap.set(box, sphere); ++ // map the box to the sphere ++ meshToMeshMap.set(sphere, box); ++}); ``` -In `render` where we rotate the cubes we need to iterate over `cubeToTextureMap` +In `render` where we rotate the cubes we need to iterate over `meshToMeshMap` instead of `cubes`. ```js -cubes.forEach((cube, ndx) => { +let ndx = 0; -+cubeToTextureMap.forEach((texture, cube) => { ++for (const mesh of meshToMeshMap.keys()) { const speed = 1 + ndx * .1; const rot = time * speed; - cube.rotation.x = rot; - cube.rotation.y = rot; +- cube.rotation.x = rot; +- cube.rotation.y = rot; +-}); ++ mesh.rotation.x = rot; ++ mesh.rotation.y = rot; + ++ndx; -}); ++} ``` And now we can use our new `PickHelper` implementation -to select one of the cubes and assign the associated background -texture. +to select one of the objects. When selected we hide +that object and un-hide its partner. ```js // 0, 0 is the center of the view in normalized coordinates. -pickHelper.pick({x: 0, y: 0}, scene, camera, time); -+const selectedObject = pickHelper.pick({x: 0, y: 0}, scene, camera, time); -+if (selectedObject) { -+ scene.background = cubeToTextureMap.get(selectedObject); -+} +if (selectedObject) { + selectedObject.visible = false; + const partnerObject = meshToMeshMap.get(selectedObject); + partnerObject.visible = true; +} ``` And with that we should have a pretty decent *look to select* implementation.
true
Other
mrdoob
three.js
3d96d13d8e752774239a9ecc573069b4ae93ca57.json
switch meshes instead of changing background
threejs/threejs-webvr-look-to-select-w-cursor.html
@@ -39,11 +39,18 @@ const camera = new THREE.PerspectiveCamera(fov, aspect, near, far); const scene = new THREE.Scene(); - const loader = new THREE.CubeTextureLoader(); - function loadCubemap(url) { - return loader.load([url, url, url, url, url, url]); + { + const loader = new THREE.CubeTextureLoader(); + const texture = loader.load([ + 'resources/images/grid-1024.png', + 'resources/images/grid-1024.png', + 'resources/images/grid-1024.png', + 'resources/images/grid-1024.png', + 'resources/images/grid-1024.png', + 'resources/images/grid-1024.png', + ]); + scene.background = texture; } - scene.background = loadCubemap('resources/images/grid-1024.png'); /* threejsfundamentals: url */ { const color = 0xFFFFFF; @@ -64,7 +71,10 @@ const boxWidth = 1; const boxHeight = 1; const boxDepth = 1; - const geometry = new THREE.BoxBufferGeometry(boxWidth, boxHeight, boxDepth); + const boxGeometry = new THREE.BoxBufferGeometry(boxWidth, boxHeight, boxDepth); + + const sphereRadius = 0.5; + const sphereGeometry = new THREE.SphereBufferGeometry(sphereRadius); function makeInstance(geometry, color, x) { const material = new THREE.MeshPhongMaterial({color}); @@ -79,21 +89,28 @@ return cube; } - const cubeToTextureMap = new Map(); - cubeToTextureMap.set( - makeInstance(geometry, 0x44aa88, 0), - loadCubemap('resources/images/grid-cyan-1024.png')); /* threejsfundamentals: url */ - cubeToTextureMap.set( - makeInstance(geometry, 0x8844aa, -2), - loadCubemap('resources/images/grid-purple-1024.png')); /* threejsfundamentals: url */ - cubeToTextureMap.set( - makeInstance(geometry, 0xaa8844, 2), - loadCubemap('resources/images/grid-gold-1024.png')); /* threejsfundamentals: url */ + const meshToMeshMap = new Map(); + [ + { x: 0, boxColor: 0x44aa88, sphereColor: 0xFF4444, }, + { x: 2, boxColor: 0x8844aa, sphereColor: 0x44FF44, }, + { x: -2, boxColor: 0xaa8844, sphereColor: 0x4444FF, }, + ].forEach((info) => { + const {x, boxColor, sphereColor} = info; + const sphere = makeInstance(sphereGeometry, sphereColor, x); + const box = makeInstance(boxGeometry, boxColor, x); + // hide the sphere + sphere.visible = false; + // map the sphere to the box + meshToMeshMap.set(box, sphere); + // map the box to the sphere + meshToMeshMap.set(sphere, box); + }); class PickHelper { constructor(camera) { this.raycaster = new THREE.Raycaster(); this.pickedObject = null; + this.pickedObjectSavedColor = 0; const cursorColors = new Uint8Array([ 64, 64, 64, 64, // dark gray @@ -117,9 +134,7 @@ blendDst: THREE.OneMinusSrcColorFactor, }); const cursor = new THREE.Mesh(cursorGeometry, cursorMaterial); - // add the cursor as a child of the camera camera.add(cursor); - // and move it in front of the camera cursor.position.z = -1; const scale = 0.05; cursor.scale.set(scale, scale, scale); @@ -134,7 +149,10 @@ this.lastTime = time; const lastPickedObject = this.pickedObject; - this.pickedObject = undefined; + // restore the color if there is a picked object + if (this.pickedObject) { + this.pickedObject = undefined; + } // cast a ray through the frustum this.raycaster.setFromCamera(normalizedPosition, camera); @@ -145,7 +163,7 @@ this.pickedObject = intersectedObjects[0].object; } - // show the cursor only if it's hitting something + // show or hide cursor this.cursor.visible = this.pickedObject ? true : false; let selected = false; @@ -200,18 +218,20 @@ } let ndx = 0; - cubeToTextureMap.forEach((texture, cube) => { + for (const mesh of meshToMeshMap.keys()) { const speed = 1 + ndx * .1; const rot = time * speed; - cube.rotation.x = rot; - cube.rotation.y = rot; + mesh.rotation.x = rot; + mesh.rotation.y = rot; ++ndx; - }); + } // 0, 0 is the center of the view in normalized coordinates. const selectedObject = pickHelper.pick({x: 0, y: 0}, scene, camera, time); if (selectedObject) { - scene.background = cubeToTextureMap.get(selectedObject); + selectedObject.visible = false; + const partnerObject = meshToMeshMap.get(selectedObject); + partnerObject.visible = true; } renderer.render(scene, camera);
true
Other
mrdoob
three.js
394abbb9d1f879eb47f4c565b3d307bab851e610.json
fix resize in VR
threejs/lessons/threejs-webvr.md
@@ -1,16 +1,68 @@ Title: Three.js WebVR Description: How to use Virtual Reality in Three.js. -Making WebVR apps in three.js is pretty simple. -You basically just have to tell three.js you want to use WebVR. -If you think about it a few things about WebVR should be clear. -Which way the camera is pointing is supplied by the VR system itself -since the user turns their head to choose a direction to look. -Similarly the field of view and aspect will be supplied by the VR system since -each system has a different field of view and display aspect. - -Let's take an example from the article on [making a responsive webpage](threejs-responsive.html) -and make it support VR. +Making WebVR apps in three.js is pretty simple. You basically just have to tell +three.js you want to use WebVR. If you think about it a few things about WebVR +should be clear. Which way the camera is pointing is supplied by the VR system +itself since the user turns their head to choose a direction to look. Similarly +the field of view and aspect will be supplied by the VR system since each system +has a different field of view and display aspect. + +Let's take an example from the article on [making a responsive +webpage](threejs-responsive.html) and make it support VR. + +Before we get started you're going to need a VR capable device like an Android +smartphone, Google Daydream, Oculus Go, Oculus Rift, Vive, Samsung Gear VR, an +iPhone with a [WebVR browser](https://itunes.apple.com/us/app/webvr-browser/id1286543066?mt=8). + +Next, if you are running locally you need to run a simple web server like is +covered in [the article on setting up](threejs-setup.html). + +You then need to look up the *local* IP address of your computer. On Mac you can +Option-Click the WiFi controls (assuming you're on Wifi). + +<div class="threejs_center"><img src="resources/images/ipaddress-macos.png" style="width: 428px;"></div> + +On Windows you can +[click the Wifi icon in the taskbar and then click "Properties" for a particular +network connection](https://support.microsoft.com/en-us/help/4026518/windows-10-find-your-ip-address). + +If you see more than one IP address, local IP addresses most commonly start with +`10.` or `192.` or `172.`. If you see an address that starts with `127.` that +address is for your computer only. It's the address the computer can use to talk +to itself so ignore anything that starts with `127.`. + +On your VR device, first make sure it's connected to the same WiFi as your +computer. Then, open your browser and type in `http://<ipaddress:port>`. Which +port depends on what server you're running. If you're using +[Servez](https://greggman.github.io/servez) or the http-server from node.js then +the port will likely be 8080. + +On my computer as I write this article its IP address is `192.168.100.78` and my +web server is using port 8080 so on my VR device I'd enter +`http://192.168.100.78:8080` to get the main page of my webserver to appear. If +you've downloaded these articles and are serving them you should see the front +page of this website appear. If you're making a new page then you might need to +add the path to your page for example when entering the URL on your VR device +something like `http://192.168.100.78:8080/path/to/page.html` + +Note that anytime you switch networks your local ip address will change. +Even on the same network when you re-connect to it your local ip address +might change so you will need to look it up again and type a different +address into your VR device. + +Also note that this will likely work on your home network or your work network but +may likely **not work** at a cafe. The WiFi at many cafe's, especially at large +chains like Starbucks or McDonalds are configured so that machines on the local +network can not talk to each other. + +If you're really going to do WebVR development another thing you should learn about is +[remote debugging](https://developers.google.com/web/tools/chrome-devtools/remote-debugging/) +so that you can see console warnings, errors, and of course actually +[debug your code](threejs-debugging-javascript.html). + +If you just want to see the code work below you can just run the code from +this site. The first thing we need to do is include the VR support after including three.js @@ -31,6 +83,14 @@ function main() { + document.body.appendChild(WEBVR.createButton(renderer)); ``` +We need to not try to resize when in VR mode as the VR device +will decide the size + +```js +-if (resizeRendererToDisplaySize(renderer)) { ++if (!renderer.vr.isPresenting() && resizeRendererToDisplaySize(renderer)) { +``` + The last major thing we need to do is let three.js run our render loop. Until now we have used a `requestAnimationFrame` loop but to support VR we need to let three.js handle our @@ -41,7 +101,7 @@ and passing a function to call for the loop. function render(time) { time *= 0.001; - if (resizeRendererToDisplaySize(renderer)) { + if (!renderer.vr.isPresenting() && resizeRendererToDisplaySize(renderer)) { const canvas = renderer.domElement; camera.aspect = canvas.clientWidth / canvas.clientHeight; camera.updateProjectionMatrix();
true
Other
mrdoob
three.js
394abbb9d1f879eb47f4c565b3d307bab851e610.json
fix resize in VR
threejs/threejs-webvr-basic-vr-optional.html
@@ -121,7 +121,7 @@ function render(time) { time *= 0.001; - if (resizeRendererToDisplaySize(renderer)) { + if (!renderer.vr.isPresenting() && resizeRendererToDisplaySize(renderer)) { const canvas = renderer.domElement; camera.aspect = canvas.clientWidth / canvas.clientHeight; camera.updateProjectionMatrix();
true
Other
mrdoob
three.js
394abbb9d1f879eb47f4c565b3d307bab851e610.json
fix resize in VR
threejs/threejs-webvr-basic-w-background.html
@@ -98,7 +98,7 @@ function render(time) { time *= 0.001; - if (resizeRendererToDisplaySize(renderer)) { + if (!renderer.vr.isPresenting() && resizeRendererToDisplaySize(renderer)) { const canvas = renderer.domElement; camera.aspect = canvas.clientWidth / canvas.clientHeight; camera.updateProjectionMatrix();
true
Other
mrdoob
three.js
394abbb9d1f879eb47f4c565b3d307bab851e610.json
fix resize in VR
threejs/threejs-webvr-basic.html
@@ -86,7 +86,7 @@ function render(time) { time *= 0.001; - if (resizeRendererToDisplaySize(renderer)) { + if (!renderer.vr.isPresenting() && resizeRendererToDisplaySize(renderer)) { const canvas = renderer.domElement; camera.aspect = canvas.clientWidth / canvas.clientHeight; camera.updateProjectionMatrix();
true
Other
mrdoob
three.js
394abbb9d1f879eb47f4c565b3d307bab851e610.json
fix resize in VR
threejs/threejs-webvr-look-to-select-selector.html
@@ -103,7 +103,7 @@ function render(time) { time *= 0.001; - if (resizeRendererToDisplaySize(renderer)) { + if (!renderer.vr.isPresenting() && resizeRendererToDisplaySize(renderer)) { const canvas = renderer.domElement; const aspect = canvas.clientWidth / canvas.clientHeight; camera.left = -aspect;
true
Other
mrdoob
three.js
394abbb9d1f879eb47f4c565b3d307bab851e610.json
fix resize in VR
threejs/threejs-webvr-look-to-select-w-cursor.html
@@ -193,7 +193,7 @@ function render(time) { time *= 0.001; - if (resizeRendererToDisplaySize(renderer)) { + if (!renderer.vr.isPresenting() && resizeRendererToDisplaySize(renderer)) { const canvas = renderer.domElement; camera.aspect = canvas.clientWidth / canvas.clientHeight; camera.updateProjectionMatrix();
true
Other
mrdoob
three.js
394abbb9d1f879eb47f4c565b3d307bab851e610.json
fix resize in VR
threejs/threejs-webvr-look-to-select.html
@@ -128,7 +128,7 @@ function render(time) { time *= 0.001; - if (resizeRendererToDisplaySize(renderer)) { + if (!renderer.vr.isPresenting() && resizeRendererToDisplaySize(renderer)) { const canvas = renderer.domElement; camera.aspect = canvas.clientWidth / canvas.clientHeight; camera.updateProjectionMatrix();
true
Other
mrdoob
three.js
0270f3d0663d9c2f43870488715091dd7e2f4f93.json
remove unused file
threejs/lessons/threejs-textures-canvas.md
@@ -1,6 +0,0 @@ -Title: Three.js Canvas Textures -Description: How to use a canvas as a texture. - -TBD - -
false
Other
mrdoob
three.js
a9e4075a80db06c37a1d2800e90a6e92089aef94.json
correct a mistake in writing
threejs/lessons/threejs-load-gltf.md
@@ -291,7 +291,7 @@ the new `Object3D` a `cars` array. + + root.updateMatrixWorld(); + for (const car of loadedCars.children.slice()) { -+ const fix = fixes.find(fix => car.name.startsWith+(fix.prefix)); ++ const fix = fixes.find(fix => car.name.startsWith(fix.prefix)); + const obj = new THREE.Object3D(); + car.getWorldPosition(obj.position); + car.position.set(0, 0, 0);
false
Other
mrdoob
three.js
201d00b9c315ee7be245303f44c1605629ee9a12.json
add disqus formatting comment
threejs/lessons/langinfo.hanson
@@ -5,8 +5,24 @@ title: 'three.js fundamentals', description: 'Learn Three.js', link: 'http://threejsfundamentals.org/', - commentSectionHeader: '<div>Questions? <a href="http://stackoverflow.com/questions/tagged/three.js">Ask on stackoverflow</a>.</div>\n <div><a href="https://github.com/gfxfundamentals/threejsfundamentals/issues/new?assignees=&labels=suggested+topic&template=suggest-topic.md&title=%5BSUGGESTION%5D">Suggestion</a>? <a href="https://github.com/gfxfundamentals/threejsfundamentals/issues/new?assignees=&labels=&template=request.md&title=">Request</a>? <a href="https://github.com/gfxfundamentals/threejsfundamentals/issues/new?assignees=&labels=bug+%2F+issue&template=bug-issue-report.md&title=">Issue</a>? <a href="https://github.com/gfxfundamentals/threejsfundamentals/issues/new?assignees=&labels=bug+%2F+issue&template=bug-issue-report.md&title=">Bug</a>?</div>', - missing: "Sorry this article has not been translated yet. [Translations Welcome](https://github.com/gfxfundamentals/threejsfundamentals)! 😄\n\n[Here's the original English article for now]({{{origLink}}}).", + commentSectionHeader: ` + <div>Questions? <a href="http://stackoverflow.com/questions/tagged/three.js">Ask on stackoverflow</a>.</div> + <div> + <a href="https://github.com/gfxfundamentals/threejsfundamentals/issues/new?assignees=&labels=suggested+topic&template=suggest-topic.md&title=%5BSUGGESTION%5D">Suggestion</a>? + <a href="https://github.com/gfxfundamentals/threejsfundamentals/issues/new?assignees=&labels=&template=request.md&title=">Request</a>? + <a href="https://github.com/gfxfundamentals/threejsfundamentals/issues/new?assignees=&labels=bug+%2F+issue&template=bug-issue-report.md&title=">Issue</a>? + <a href="https://github.com/gfxfundamentals/threejsfundamentals/issues/new?assignees=&labels=bug+%2F+issue&template=bug-issue-report.md&title=">Bug</a>? + </div> + <div class="lesson-comment-notes"> + Use <b>&lt;pre&gt;&lt;code&gt;</b>code goes here<b>&lt;/code&gt;&lt;/pre&gt;</b> for code blocks + </div> + `, + missing: ` + Sorry this article has not been translated yet. + [Translations Welcome](https://github.com/gfxfundamentals/threejsfundamentals)! 😄 + + [Here's the original English article for now]({{{origLink}}}). + `, toc: 'Table of Contents', categoryMapping: { 'basics': 'Basics',
true
Other
mrdoob
three.js
201d00b9c315ee7be245303f44c1605629ee9a12.json
add disqus formatting comment
threejs/lessons/resources/lesson.css
@@ -87,6 +87,12 @@ div[data-diagram] { border: 1px solid black; } +.lesson-comment-notes { + padding: 1em; + margin: 1em; + background: #DDD; + color: red; +} .threejs_navbar>div, .lesson-title, @@ -556,5 +562,8 @@ pre.prettyprint.lighttheme .fun { color: #900; } /* function name */ div.threejs_bottombar code { background-color: #348; } + .lesson-comment-notes { + background: #222; + } }
true
Other
mrdoob
three.js
28fac0dabd02ce2a498d6cbb367aa126f4ca15ae.json
add contribute banner to all pages
build/templates/header.template
@@ -6,5 +6,6 @@ </div> <div class="threejs_header"> <h1><a href="{{langInfo.home}}">threejsfundamentals.org</a></h1> +{{{include "build/templates/repobanner.template"}}} </div>
true
Other
mrdoob
three.js
28fac0dabd02ce2a498d6cbb367aa126f4ca15ae.json
add contribute banner to all pages
build/templates/index.template
@@ -98,73 +98,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. </div> </div> </div> +{{{include "build/templates/repobanner.template"}}} <iframe class="background" src="/threejs/background.html"></iframe> -<style> -#forkongithub a { - background: #000; - color: #fff; - text-decoration: none; - font-family: arial,sans-serif; - text-align: center; - font-weight: bold; - padding: 5px 40px; - font-size: 0.9rem; - line-height: 2rem; - position: relative; - transition: 0.5s; - display: block; - width: 300px; - position: absolute; - top: 0; - right: 0; - transform: translateX(150px) rotate(45deg) translate(10px,70px); - box-shadow: 4px 4px 10px rgba(0,0,0,0.8); - pointer-events: auto; -} -#forkongithub a:hover { - background: #c11; - color: #fff; -} -#forkongithub a::before,#forkongithub a::after { - content: ""; - width: 100%; - display: block; - position: absolute; - top: 1px; - left: 0; - height: 1px; - background: #fff; -} -#forkongithub a::after { - bottom: 1px; - top: auto; -} - -#forkongithub{ - z-index: 9999; - /* needed for firefox */ - overflow: hidden; - width: 300px; - height: 300px; - position: absolute; - right: 0; - top: 0; - pointer-events: none; -} -@media (max-width: 900px) { - #forkongithub a{ - line-height: 1.2rem; - } -} -@media (max-width: 410px) { - #forkongithub a{ - font-size: 0.7rem; - transform: translateX(150px) rotate(45deg) translate(20px,40px); - } -} - -</style> -<div id="forkongithub"><a href="https://github.com/gfxfundamentals/threejsfundamentals">Fix or Fork me on GitHub</a></div> </body> <script src="/3rdparty/jquery-3.3.1.slim.min.js"></script> <script src="/threejs/lessons/resources/lesson.js"></script>
true
Other
mrdoob
three.js
28fac0dabd02ce2a498d6cbb367aa126f4ca15ae.json
add contribute banner to all pages
build/templates/octocat-icon.svg
@@ -0,0 +1,7 @@ +<?xml version="1.0" encoding="UTF-8" standalone="no"?> +<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> +<svg width="100%" height="100%" viewBox="0 0 136 133" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve" xmlns:serif="http://www.serif.com/" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:2;"> + <g transform="matrix(3.92891,0,0,3.92891,67.867,129.125)"> + <path d="M0,-31.904C-8.995,-31.904 -16.288,-24.611 -16.288,-15.614C-16.288,-8.417 -11.621,-2.312 -5.148,-0.157C-4.333,-0.008 -4.036,-0.511 -4.036,-0.943C-4.036,-1.329 -4.05,-2.354 -4.058,-3.713C-8.589,-2.729 -9.545,-5.897 -9.545,-5.897C-10.286,-7.779 -11.354,-8.28 -11.354,-8.28C-12.833,-9.29 -11.242,-9.27 -11.242,-9.27C-9.607,-9.155 -8.747,-7.591 -8.747,-7.591C-7.294,-5.102 -4.934,-5.821 -4.006,-6.238C-3.858,-7.29 -3.438,-8.008 -2.972,-8.415C-6.589,-8.826 -10.392,-10.224 -10.392,-16.466C-10.392,-18.244 -9.757,-19.698 -8.715,-20.837C-8.883,-21.249 -9.442,-22.905 -8.556,-25.148C-8.556,-25.148 -7.188,-25.586 -4.076,-23.478C-2.777,-23.84 -1.383,-24.02 0.002,-24.026C1.385,-24.02 2.779,-23.84 4.08,-23.478C7.19,-25.586 8.555,-25.148 8.555,-25.148C9.444,-22.905 8.885,-21.249 8.717,-20.837C9.761,-19.698 10.392,-18.244 10.392,-16.466C10.392,-10.208 6.583,-8.831 2.954,-8.428C3.539,-7.925 4.06,-6.931 4.06,-5.411C4.06,-3.234 4.04,-1.477 4.04,-0.943C4.04,-0.507 4.333,0 5.16,-0.159C11.628,-2.318 16.291,-8.419 16.291,-15.614C16.291,-24.611 8.997,-31.904 0,-31.904" style="fill:white;"/> + </g> +</svg>
true
Other
mrdoob
three.js
28fac0dabd02ce2a498d6cbb367aa126f4ca15ae.json
add contribute banner to all pages
build/templates/repobanner.template
@@ -0,0 +1,76 @@ +<style> +#forkongithub a { + background: #000; + color: #fff; + text-decoration: none; + font-family: arial,sans-serif; + text-align: center; + font-weight: bold; + padding: 5px 40px; + font-size: 0.9rem; + line-height: 2rem; + position: relative; + transition: 0.5s; + display: block; + width: 300px; + position: absolute; + top: 0; + right: 0; + transform: translateX(150px) rotate(45deg) translate(10px,70px); + box-shadow: 4px 4px 10px rgba(0,0,0,0.8); + pointer-events: auto; +} +#forkongithub a:hover { + background: #c11; + color: #fff; +} +#forkongithub a::before,#forkongithub a::after { + content: ""; + width: 100%; + display: block; + position: absolute; + top: 1px; + left: 0; + height: 1px; + background: #fff; +} +#forkongithub a::after { + bottom: 1px; + top: auto; +} + +#forkongithub{ + z-index: 9999; + /* needed for firefox */ + overflow: hidden; + width: 300px; + height: 300px; + position: absolute; + right: 0; + top: 0; + pointer-events: none; +} +#forkongithub svg{ + width: 1em; + height: 1em; + vertical-align: middle; +} +@media (max-width: 900px) { + #forkongithub a{ + line-height: 1.2rem; + } +} +@media (max-width: 700px) { + #forkongithub { + display: none; + } +} +@media (max-width: 410px) { + #forkongithub a{ + font-size: 0.7rem; + transform: translateX(150px) rotate(45deg) translate(20px,40px); + } +} + +</style> +<div id="forkongithub"><a href="https://github.com/gfxfundamentals/threejsfundamentals">Fix, Fork, Contribute {{{include "build/templates/octocat-icon.svg"}}}</a></div>
true
Other
mrdoob
three.js
28fac0dabd02ce2a498d6cbb367aa126f4ca15ae.json
add contribute banner to all pages
threejs/lessons/resources/lesson.css
@@ -123,6 +123,7 @@ div[data-diagram] { background-position: center, center; padding: 1em; text-align: center; + position: relative; } .threejs_header h1 { font-size: 5vw;
true
Other
mrdoob
three.js
eada0c6ef3001e42c25d574f561ad066e8daaf32.json
add info on Points and PointsMaterial
threejs/lessons/resources/threejs-primitives.js
@@ -326,6 +326,41 @@ import {threejsLessonUtils} from './threejs-lesson-utils.js'; }, nonBuffer: false, }, + Points: { + create() { + const radius = 7; + const widthSegments = 12; + const heightSegments = 8; + const geometry = new THREE.SphereBufferGeometry(radius, widthSegments, heightSegments); + const material = new THREE.PointsMaterial({ + color: 'red', + size: 0.2, + }); + const points = new THREE.Points(geometry, material); + return { + showLines: false, + mesh: points, + }; + }, + }, + PointsUniformSize: { + create() { + const radius = 7; + const widthSegments = 12; + const heightSegments = 8; + const geometry = new THREE.SphereBufferGeometry(radius, widthSegments, heightSegments); + const material = new THREE.PointsMaterial({ + color: 'red', + size: 3 * window.devicePixelRatio, + sizeAttenuation: false, + }); + const points = new THREE.Points(geometry, material); + return { + showLines: false, + mesh: points, + }; + }, + }, SphereBufferGeometryLow: { create() { const radius = 7; @@ -493,31 +528,36 @@ import {threejsLessonUtils} from './threejs-lesson-utils.js'; const root = new THREE.Object3D(); - const boxGeometry = geometryInfo.geometry || geometryInfo.lineGeometry; - boxGeometry.computeBoundingBox(); - const centerOffset = new THREE.Vector3(); - boxGeometry.boundingBox.getCenter(centerOffset).multiplyScalar(-1); - - if (geometryInfo.geometry) { - const material = new THREE.MeshPhongMaterial({ - flatShading: info.flatShading === false ? false : true, - side: THREE.DoubleSide, - }); - material.color.setHSL(Math.random(), .5, .5); - const mesh = new THREE.Mesh(geometryInfo.geometry, material); - mesh.position.copy(centerOffset); - root.add(mesh); - } - if (info.showLines !== false) { - const lineMesh = new THREE.LineSegments( - geometryInfo.lineGeometry || geometryInfo.geometry, - new THREE.LineBasicMaterial({ - color: geometryInfo.geometry ? 0xffffff : colors.lines, - transparent: true, - opacity: 0.5, - })); - lineMesh.position.copy(centerOffset); - root.add(lineMesh); + if (geometry.mesh) { + root.add(geometry.mesh); + } else { + const boxGeometry = geometryInfo.geometry || geometryInfo.lineGeometry; + boxGeometry.computeBoundingBox(); + const centerOffset = new THREE.Vector3(); + boxGeometry.boundingBox.getCenter(centerOffset).multiplyScalar(-1); + + if (geometryInfo.geometry) { + const material = new THREE.MeshPhongMaterial({ + flatShading: info.flatShading === false ? false : true, + side: THREE.DoubleSide, + }); + material.color.setHSL(Math.random(), .5, .5); + const mesh = new THREE.Mesh(geometryInfo.geometry, material); + mesh.position.copy(centerOffset); + root.add(mesh); + } + + if (info.showLines !== false) { + const lineMesh = new THREE.LineSegments( + geometryInfo.lineGeometry || geometryInfo.geometry, + new THREE.LineBasicMaterial({ + color: geometryInfo.geometry ? 0xffffff : colors.lines, + transparent: true, + opacity: 0.5, + })); + lineMesh.position.copy(centerOffset); + root.add(lineMesh); + } } threejsLessonUtils.addDiagram(elem, {create: () => root});
true
Other
mrdoob
three.js
eada0c6ef3001e42c25d574f561ad066e8daaf32.json
add info on Points and PointsMaterial
threejs/lessons/threejs-primitives.md
@@ -291,6 +291,46 @@ and it's best to [look in the documentation](https://threejs.org/docs/) for all repeat them here. You can also click the links above next to each shape to take you directly to the docs for that shape. +There is one other pair of classes that doesn't really fit the patterns above. Those are +the `PointsMaterial` and the `Points` class. `Points` is like `LineSegments` above in that it takes a +a `Geometry` or `BufferGeometry` but draws points at each vertex instead of lines. +To use it you also need to pass it a `PointsMaterial` which +take a [`size`](PointsMaterial.size) for how large to make the points. + +```js +const radius = 7; +const widthSegments = 12; +const heightSegments = 8; +const geometry = new THREE.SphereBufferGeometry(radius, widthSegments, heightSegments); +const material = new THREE.PointsMaterial({ + color: 'red', + size: 0.2, // in world units +}); +const points = new THREE.Points(geometry, material); +scene.add(points); +``` + +<div class="spread"> +<div data-diagram="Points"></div> +</div> + +You can turn off [`sizeAttenuation`](PointsMaterial.sizeAttenuation) by setting it to false if you want the points to +be the same size regardless of their distance from the camera. + +```js +const material = new THREE.PointsMaterial({ + color: 'red', ++ sizeAttenuation: false, ++ size: 3, // in pixels +- size: 0.2, // in world units +}); +... +``` + +<div class="spread"> +<div data-diagram="PointsUniformSize"></div> +</div> + One other thing that's important to cover is that almost all shapes have various settings for how much to subdivide them. A good example might be the sphere geometries. Spheres take parameters for @@ -345,6 +385,12 @@ subdivisions you choose the more likely things will run smoothly and the less memory they'll take. You'll have to decide for yourself what the correct tradeoff is for your particular situation. +If none of the shapes above fit your use case you can load +geometry for example from a [.obj file](threejs-load-obj.html) +or a [.gltf file](threejs-load-gltf.html). +You can also create your own [custom Geometry](threejs-custom-geometry.html) +or [custom BufferGeometry](threejs-custom-buffergeometry.html). + Next up let's go over [how three's scene graph works and how to use it](threejs-scenegraph.html).
true
Other
mrdoob
three.js
eb14a670e7b95fac283bf996f6225aad507a2d61.json
add dev notes
DEVELOPMENT.md
@@ -0,0 +1,24 @@ +# DEVELOPMENT NOTES + +## archiving old versions + +(hopefully automated someday) + +1. make repo on github +2. in threejsfundamentals.org + 1. git fetch origin gh-pages + 2. git checkout gh-pages + 3. git rebase origin/gh-pages? + 4. git clone --branch gh-pages ../old.threejsfundamentals/rXXX +3. cd ../old.threejsfundamentals.rXXX +4. git remote rm origin +5. git remote add origin <new-github-repo> +6. edit CNAME +7. delete + * robots.txt + * sitemap.xml + * atom.xml + * Gruntfile.js +8. s/\/threejsfundamentals.org/\/rXXX.threejsfundamentals.org/g +9. git push -u origin gh-pages +10. Update DNS (cloudflare)
false
Other
mrdoob
three.js
6f09b6546399cb9d39284fba8231aea76b9aecd5.json
add another example using http-server
threejs/lessons/threejs-setup.md
@@ -43,6 +43,11 @@ Once you've done that type http-server path/to/folder/where/you/unzipped/files +Or if you're like me + + cd path/to/folder/where/you/unzipped/files + http-server + It should print something like {{{image url="resources/http-server-response.png" }}}
false
Other
mrdoob
three.js
61f41f468a6efd3c8f086f175ba4776d0c369fc0.json
use module in prerequisites
threejs/lessons/threejs-prerequisites.md
@@ -5,8 +5,9 @@ TOC: Prerequisites These articles are meant to help you learn how to use three.js. They assume you know how to program in JavaScript. They assume you know what the DOM is, how to write HTML as well as create DOM elements -in JavaScript. They assume you know how to use `<script>` tags to -include external JavaScript files as well as inline scripts. +in JavaScript. They assume you know how to use +[es6 modules](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import) +oth via import and via `<script type="module">` tags. They assume you know some CSS and that you know what [CSS selectors are](https://developer.mozilla.org/en-US/docs/Learn/CSS/Introduction_to_CSS/Selectors). They also assume you know ES5, ES6 and maybe some ES7. @@ -15,6 +16,26 @@ They assume you know what a closure is. Here's some brief refreshers and notes +## es6 modules + +es6 modules can be loaded via the `import` keyword in a script +or inline via a `<script type="module">` tag. Here's an example of +both + +```html +<script type="module"> +import * as THREE from './resources/threejs/r108/build/three.module.js'; + +... + +</script> +``` + +Paths must be absolute or relative. Relative paths always start with `./` or `../` +which is different than other tags like `<img>` and `<a>` and css references. + +More details are mentioned at the bottom of [this article](threejs-fundamentals.html). + ## `document.querySelector` and `document.querySelectorAll` You can use `document.querySelector` to select the first element @@ -46,20 +67,6 @@ at the bottom of the page. or [use the `defer` property](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script). -## You don't need `type="text/javascript"` - -modern - - <script>...</script> - -outdated - - <script type="text/javascript"></script> - -## Always use `strict` mode - -Put `'use strict';` at the top of every JavaScript file. It will help prevent lots of bugs. - ## Know how closures work ```js @@ -77,7 +84,7 @@ console.log(g()); // prints 456 ``` In the code above the function `a` creates a new function every time it's called. That -funciton *closes* over the variable `foo`. Here's [more info](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures). +function *closes* over the variable `foo`. Here's [more info](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures). ## Understand how `this` works @@ -87,7 +94,7 @@ like somefunction(a, b, c); -`this` will be `null` (when in strict mode) where as when you call a function via the dot operator `.` like this +`this` will be `null` (when in strict mode or in a module) where as when you call a function via the dot operator `.` like this someobject.somefunction(a, b, c); @@ -100,7 +107,7 @@ The parts where people get confused is with callbacks. doesn't work as someone inexperienced might expect because when `loader.load` calls the callback it's not calling it with the dot `.` operator -so by default `this` will be null (unless the loader explicitly sets it to someting). +so by default `this` will be null (unless the loader explicitly sets it to something). If you want `this` to be `someobject` when the callback happens you need to tell JavaScript that by binding it to the function. @@ -219,14 +226,20 @@ This is especially useful with callbacks and promises. ```js loader.load((texture) => { - // use textrue + // use texture }); ``` -Arrow functions bind `this`. They are a shortcut for +Arrow functions bind `this`. ```js -(function(args) {/* code */}).bind(this)) +const foo = (args) => {/* code */}; +``` + +is a shortcut for + +```js +const foo = (function(args) {/* code */}).bind(this)); ``` ### Promises as well as async/await @@ -286,9 +299,16 @@ someElement.style.width = `${aWidth + bWidth}px`; While you're welcome to format your code any way you chose there is at least one convention you should be aware of. Variables, function names, method names, in -JavaScript are all lowercasedCamelCase. Constructors, the names of classes are +JavaScript are all lowerCasedCamelCase. Constructors, the names of classes are CapitalizedCamelCase. If you follow this rule you code will match most other -JavaScript. +JavaScript. Many [linters](https://eslint.org), programs that check for obvious errors in your code, +will point out errors if you use the wrong case since by following the convention +above they know these are wrong + +```js +const v = new vector(); // clearly an error if all classes start with a capital letter +const v = Vector(); // clearly an error if all functions start with a lowercase latter. +``` # Consider using Visual Studio Code
true
Other
mrdoob
three.js
61f41f468a6efd3c8f086f175ba4776d0c369fc0.json
use module in prerequisites
threejs/lessons/zh_cn/threejs-prerequisites.md
@@ -46,20 +46,6 @@ DOM元素。假设你知道如何使用 `<script>`标签来 or [use the `defer` property](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script). -## 不需要`type="text/javascript"` - -最新的 - - <script>...</script> - -过时的 - - <script type="text/javascript"></script> - -## 始终使用`strict`模式 - -将`'use strict';`放在JavaScript文件的顶部。可以帮助减少很多bug。 - ## 了解闭包如何工作 ```js
true
Other
mrdoob
three.js
81e6567ce7de82e01b0583452602b9cf6a223fe4.json
use module in fundamentals
threejs/lessons/ru/threejs-fundamentals.md
@@ -41,10 +41,8 @@ Three.js будет рисовать на этом холсте, так что его и передать three.js. ``` -<script> -'use strict'; - -/* global THREE */ +<script type="module"> +import * as THREE from './resources/threejs/r108/build/three.module.js'; function main() { const canvas = document.querySelector('#c');
true
Other
mrdoob
three.js
81e6567ce7de82e01b0583452602b9cf6a223fe4.json
use module in fundamentals
threejs/lessons/threejs-fundamentals.md
@@ -40,10 +40,8 @@ Three.js will draw into that canvas so we need to look it up and pass it to three.js. ```html -<script> -'use strict'; - -/* global THREE */ +<script type="module"> +import * as THREE from './resources/threejs/r108/build/three.module.js'; function main() { const canvas = document.querySelector('#c'); @@ -52,6 +50,13 @@ function main() { </script> ``` +It's important you put `type="module"` in the script tag. This enables +us to use the `import` keyword to load three.js. There are other ways +to load three.js but as of r106 using modules is the recommended way. +Modules have the advantage that they can easily import other modules +they need. That saves us from having to manually load extra scripts +they are dependent on. + Note there are some esoteric details here. If you don't pass a canvas into three.js it will create one for you but then you have to add it to your document. Where to add it may change depending on your use case @@ -318,3 +323,75 @@ across the canvas is so extreme. I hope this short intro helps to get things started. [Next up we'll cover making our code responsive so it is adaptable to multiple situations](threejs-responsive.html). +<div class="threejs_bottombar"> +<h3>es6 modules, three.js, and folder structure</h3> +<p>As of version r106 the preferred way to use three.js is via <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import">es6 modules</a>.</p> +<p> +es6 modules can be loaded via the `import` keyword in a script +or inline via a <code>&lt;script type="module"&gt;</code> tag. Here's an example of +both +</p> +<pre class=prettyprint> +&lt;script type="module"&gt; +import * as THREE from './resources/threejs/r108/build/three.module.js'; + +... + +&lt;/script&gt; +</pre> +<p> +Paths must be absolute or relative. Relative paths always start with <code>./</code> or <code>../</code> +which is different than other tags like <code>&lt;img&gt;</code> and <code>&lt;a&gt;</code>. +</p> +<p> +References to the same script will only be loaded once as long as their absolute paths +are exactly the same. For three.js this means it's required that you put all the examples +libraries in the correct folder structure +</p> +<pre class="dos"> +someFolder + | + ├-build + | | + | +-three.module.js + | + +-examples + | + +-jsm + | + +-controls + | | + | +-OrbitControls.js + | +-TrackballControls.js + | +-... + | + +-loaders + | | + | +-GLTFLoader.js + | +-... + | + ... +</pre> +<p> +The reason this folder structure is required is because the scripts in the +examples like <a href="https://github.com/mrdoob/three.js/blob/master/examples/jsm/controls/OrbitControls.js"><code>OrbitControls.js</code></a> +have hard coded relative paths like +</p> +<pre class="prettyprint"> +import * as THREE from '../../../build/three.module.js'; +</pre> +<p> +Using the same structure assures then when you import both three and one of the example +libraries they'll both reference the same three.module.js file. +</p> +<pre class="prettyprint"> +import * as THREE from './someFolder/build/three.module.js'; +import {OrbitControls} from './someFolder/examples/jsm/controls/OrbitControls.js'; +</pre> +<p>This includes when using a CDN. Be sure your path to <code>three.modules.js</code> ends with +<code>/build/three.modules.js</code>. For example</p> +<pre class="prettyprint"> +import * as THREE from 'https://unpkg.com/three@0.108.0/<b>build/three.module.js</b>'; +import {OrbitControls} from 'https://unpkg.com/three@0.108.0/examples/jsm/controls/OrbitControls.js'; +</pre> +</div> \ No newline at end of file
true
Other
mrdoob
three.js
81e6567ce7de82e01b0583452602b9cf6a223fe4.json
use module in fundamentals
threejs/lessons/zh_cn/threejs-fundamentals.md
@@ -34,10 +34,8 @@ Three.js经常会和WebGL混淆, Three.js将会使用这个canvas标签所以我们要先获取它然后传给three.js。 ```html -<script> -'use strict'; - -/* global THREE */ +<script type="module"> +import * as THREE from './resources/threejs/r108/build/three.module.js'; function main() { const canvas = document.querySelector('#c');
true
Other
mrdoob
three.js
054f6ec64440bbed8017b98f2bdfba1df4dc8ea7.json
put offscreen back to non es6 module
threejs/lessons/threejs-offscreencanvas.md
@@ -10,6 +10,10 @@ to a web worker so as not to slow down the responsiveness of the browser. It also means data is loaded and parsed in the worker so possibly less jank while the page loads. +One big issue with offscreen canvas is, at least in Chrome, es6 modules are not yet +supported on web workers, so, unlike all the other examples on this site that use +es6 modules these examples will use class scripts. + Getting *started* using it is pretty straight forward. Let's port the 3 spinning cube example from [the article on responsiveness](threejs-responsive.html). @@ -92,7 +96,7 @@ So now we just need to start changing the `main` we pasted into The first thing we need to do is include THREE.js into our worker. ```js -importScripts('https://threejsfundamentals.org/threejs/resources/threejs/r108/three.min.js'); +importScripts('resources/threejs/r108/build/three.min.js'); ``` Then instead of looking up the canvas from the DOM we'll receive it from the @@ -290,7 +294,7 @@ HTML file. /* global importScripts, init, state */ -importScripts('resources/threejs/r108/three.min.js'); +importScripts('resources/threejs/r108/build/three.min.js'); +importScripts('shared-cubes.js'); function size(data) { @@ -315,11 +319,11 @@ self.onmessage = function(e) { note we include `shared-cubes.js` which is all our three.js code -Similarly we need to include `shared-cubes.js` in the main page +Similarly we need to include three.js and `shared-cubes.js` in the main page -```js -import * as THREE from './resources/three/r108/build/three.module.js'; -import {init, state} from './shared-cubes.js'; +```html +<script src="resources/threejs/r108/build/three.min.js"></script> +<script src="shared-cubes.js"><script> ``` We can remove the HTML and CSS we added previously @@ -728,8 +732,8 @@ We also need to actually add the `OrbitControls` to the top of the script ```js -importScripts('resources/threejs/r108/three.js'); -+importScripts('resources/threejs/r108/js/controls/OrbitControls.js'); +importScripts('resources/threejs/r108/build/three.min/js'); ++importScripts('resources/threejs/r108/examples/js/controls/OrbitControls.js'); *importScripts('shared-orbitcontrols.js'); ```
true
Other
mrdoob
three.js
054f6ec64440bbed8017b98f2bdfba1df4dc8ea7.json
put offscreen back to non es6 module
threejs/offscreencanvas-cubes.js
@@ -1,8 +1,8 @@ -'use strict'; +'use strict'; // eslint-disable-line /* global importScripts, THREE */ -importScripts('resources/threejs/r108/three.min.js'); +importScripts('resources/threejs/r108/build/three.min.js'); const state = { width: 300, // canvas default
true
Other
mrdoob
three.js
054f6ec64440bbed8017b98f2bdfba1df4dc8ea7.json
put offscreen back to non es6 module
threejs/offscreencanvas-worker-cubes.js
@@ -2,7 +2,7 @@ /* global importScripts, init, state */ -importScripts('resources/threejs/r108/three.min.js'); +importScripts('resources/threejs/r108/build/three.min.js'); importScripts('shared-cubes.js'); function size(data) {
true
Other
mrdoob
three.js
054f6ec64440bbed8017b98f2bdfba1df4dc8ea7.json
put offscreen back to non es6 module
threejs/offscreencanvas-worker-orbitcontrols.js
@@ -2,8 +2,8 @@ /* global importScripts, init, THREE */ -importScripts('resources/threejs/r108/three.js'); -importScripts('resources/threejs/r108/js/controls/OrbitControls.js'); +importScripts('resources/threejs/r108/build/three.min.js'); +importScripts('resources/threejs/r108/examples/js/controls/OrbitControls.js'); importScripts('shared-orbitcontrols.js'); function noop() {
true
Other
mrdoob
three.js
054f6ec64440bbed8017b98f2bdfba1df4dc8ea7.json
put offscreen back to non es6 module
threejs/offscreencanvas-worker-picking.js
@@ -2,7 +2,7 @@ /* global importScripts, init, state, pickPosition */ -importScripts('resources/threejs/r108/three.min.js'); +importScripts('resources/threejs/r108/build/three.min.js'); importScripts('shared-picking.js'); function size(data) {
true
Other
mrdoob
three.js
054f6ec64440bbed8017b98f2bdfba1df4dc8ea7.json
put offscreen back to non es6 module
threejs/shared-cubes.js
@@ -1,6 +1,4 @@ -import * as THREE from 'resources/threejs/r108/build/three.module.js'; - -export const state = { +const state = { width: 300, // canvas default height: 150, // canvas default };
true
Other
mrdoob
three.js
054f6ec64440bbed8017b98f2bdfba1df4dc8ea7.json
put offscreen back to non es6 module
threejs/shared-orbitcontrols.js
@@ -1,7 +1,4 @@ -import * as THREE from './resources/threejs/r108/build/three.module.js'; -import {OrbitControls} from './resources/threejs/r108/examples/jsm/controls/OrbitControls.js'; - -export function init(data) { /* eslint-disable-line no-unused-vars */ +function init(data) { /* eslint-disable-line no-unused-vars */ const {canvas, inputElement} = data; const renderer = new THREE.WebGLRenderer({canvas}); @@ -12,7 +9,7 @@ export function init(data) { /* eslint-disable-line no-unused-vars */ const camera = new THREE.PerspectiveCamera(fov, aspect, near, far); camera.position.z = 4; - const controls = new OrbitControls(camera, inputElement); + const controls = new THREE.OrbitControls(camera, inputElement); controls.target.set(0, 0, 0); controls.update();
true
Other
mrdoob
three.js
054f6ec64440bbed8017b98f2bdfba1df4dc8ea7.json
put offscreen back to non es6 module
threejs/shared-picking.js
@@ -1,13 +1,11 @@ -import * as THREE from './resources/threejs/r108/build/three.module.js'; - -export const state = { +const state = { width: 300, // canvas default height: 150, // canvas default }; -export const pickPosition = {x: 0, y: 0}; +const pickPosition = {x: 0, y: 0}; -export function init(data) { // eslint-disable-line no-unused-vars +function init(data) { // eslint-disable-line no-unused-vars const {canvas} = data; const renderer = new THREE.WebGLRenderer({canvas});
true
Other
mrdoob
three.js
054f6ec64440bbed8017b98f2bdfba1df4dc8ea7.json
put offscreen back to non es6 module
threejs/threejs-offscreencanvas-w-fallback.html
@@ -19,8 +19,12 @@ <body> <canvas id="c"></canvas> </body> -<script type="module"> -import {state, init} from './shared-cubes.js'; +<script src="resources/threejs/r108/build/three.min.js"></script> +<script src="shared-cubes.js"></script> +<script> +'use strict'; // eslint-disable-line + +/* globals state, init */ function startWorker(canvas) { const offscreen = canvas.transferControlToOffscreen();
true
Other
mrdoob
three.js
054f6ec64440bbed8017b98f2bdfba1df4dc8ea7.json
put offscreen back to non es6 module
threejs/threejs-offscreencanvas-w-orbitcontrols.html
@@ -22,8 +22,13 @@ <body> <canvas id="c" tabindex="1"></canvas> </body> -<script type="module"> -import {init} from './shared-orbitcontrols.js'; +<script src="resources/threejs/r108/build/three.min.js"></script> +<script src="resources/threejs/r108/examples/js/controls/OrbitControls.js"></script> +<script src="shared-orbitcontrols.js"></script> +<script> +'use strict'; // eslint-disable-line + +/* global init */ const mouseEventHandler = makeSendPropertiesHandler([ 'ctrlKey',
true
Other
mrdoob
three.js
054f6ec64440bbed8017b98f2bdfba1df4dc8ea7.json
put offscreen back to non es6 module
threejs/threejs-offscreencanvas-w-picking.html
@@ -19,8 +19,13 @@ <body> <canvas id="c"></canvas> </body> -<script type="module"> -import {state, init, pickPosition} from './shared-picking.js'; +<script src="resources/threejs/r108/build/three.min.js"></script> +<script src="resources/threejs/r108/examples/js/controls/OrbitControls.js"></script> +<script src="shared-picking.js"></script> +<script> +'use strict'; // eslint-disable-line + +/* global state, init, pickPosition */ let sendMouse;
true
Other
mrdoob
three.js
054f6ec64440bbed8017b98f2bdfba1df4dc8ea7.json
put offscreen back to non es6 module
threejs/threejs-offscreencanvas.html
@@ -31,7 +31,8 @@ <div>no OffscreenCanvas support</div> </div> </body> -<script type="module"> +<script> +'use strict'; // eslint-disable-line function main() { /* eslint consistent-return: 0 */ const canvas = document.querySelector('#c');
true
Other
mrdoob
three.js
0c4969b330f0e84636d4f535a2e90dc80249a68e.json
remove extra lines
.github/ISSUE_TEMPLATE/bug-issue-report.md
@@ -7,4 +7,3 @@ assignees: '' --- -
true
Other
mrdoob
three.js
0c4969b330f0e84636d4f535a2e90dc80249a68e.json
remove extra lines
.github/ISSUE_TEMPLATE/question.md
@@ -7,4 +7,3 @@ assignees: '' --- -
true
Other
mrdoob
three.js
0c4969b330f0e84636d4f535a2e90dc80249a68e.json
remove extra lines
.github/ISSUE_TEMPLATE/request.md
@@ -7,4 +7,3 @@ assignees: '' --- -
true
Other
mrdoob
three.js
0c4969b330f0e84636d4f535a2e90dc80249a68e.json
remove extra lines
.github/ISSUE_TEMPLATE/suggest-topic.md
@@ -7,4 +7,3 @@ assignees: '' --- -
true
Other
mrdoob
three.js
0c4969b330f0e84636d4f535a2e90dc80249a68e.json
remove extra lines
.github/ISSUE_TEMPLATE/translation.md
@@ -7,4 +7,3 @@ assignees: '' --- -
true
Other
mrdoob
three.js
0c4969b330f0e84636d4f535a2e90dc80249a68e.json
remove extra lines
contributors.md
@@ -5,4 +5,3 @@ Threejsfundamentals is brought to you by: * Gregg (Greggman) Tavares [games.greggman.com](http://games.greggman.com) -
true
Other
mrdoob
three.js
0c4969b330f0e84636d4f535a2e90dc80249a68e.json
remove extra lines
threejs/3dlut-base-cube-maker.html
@@ -26,7 +26,6 @@ <h1>Color Cube Image Maker</h1> </body> <script type="module"> - const ctx = document.querySelector('canvas').getContext('2d'); function drawColorCubeImage(ctx, size) {
true
Other
mrdoob
three.js
0c4969b330f0e84636d4f535a2e90dc80249a68e.json
remove extra lines
threejs/canvas-random-dots.html
@@ -10,7 +10,6 @@ </body> <script type="module"> - function main() { const ctx = document.createElement('canvas').getContext('2d'); document.body.appendChild(ctx.canvas);
true
Other
mrdoob
three.js
0c4969b330f0e84636d4f535a2e90dc80249a68e.json
remove extra lines
threejs/gpw-data-viewer.html
@@ -14,7 +14,6 @@ </body> <script type="module"> - async function loadFile(url) { const req = await fetch(url); return req.text();
true
Other
mrdoob
three.js
0c4969b330f0e84636d4f535a2e90dc80249a68e.json
remove extra lines
threejs/lessons/index.md
@@ -4,12 +4,10 @@ A set of articles to help learn Three.js. {{{include "threejs/lessons/toc.html"}}} - <!-- {{{table_of_contents}}} --> -
true
Other
mrdoob
three.js
0c4969b330f0e84636d4f535a2e90dc80249a68e.json
remove extra lines
threejs/lessons/ru/index.md
@@ -4,12 +4,10 @@ Title: Основы Three.js {{{include "threejs/lessons/ru/toc.html"}}} - <!-- {{{table_of_contents}}} --> -
true
Other
mrdoob
three.js
0c4969b330f0e84636d4f535a2e90dc80249a68e.json
remove extra lines
threejs/lessons/ru/threejs-materials.md
@@ -320,4 +320,3 @@ flat shaded <canvas id="c"></canvas> <script type="module" src="../resources/threejs-materials.js"></script> -
true
Other
mrdoob
three.js
0c4969b330f0e84636d4f535a2e90dc80249a68e.json
remove extra lines
threejs/lessons/ru/threejs-primitives.md
@@ -247,7 +247,6 @@ function addSolidGeometry(x, y, geometry) { Если бы мы этого не делали, текст был бы оторван от центра. - {{{example url="../threejs-primitives-text.html" }}} Обратите внимание, что то что слева не вращается вокруг своего центра,
true
Other
mrdoob
three.js
0c4969b330f0e84636d4f535a2e90dc80249a68e.json
remove extra lines
threejs/lessons/threejs-custom-buffergeometry.md
@@ -463,4 +463,3 @@ depends on your needs. <canvas id="c"></canvas> <script type="module" src="resources/threejs-custom-buffergeometry.js"></script> -
true
Other
mrdoob
three.js
0c4969b330f0e84636d4f535a2e90dc80249a68e.json
remove extra lines
threejs/lessons/threejs-debugging-glsl.md
@@ -110,4 +110,3 @@ live while the code is running. -
true
Other
mrdoob
three.js
0c4969b330f0e84636d4f535a2e90dc80249a68e.json
remove extra lines
threejs/lessons/threejs-materials.md
@@ -306,4 +306,3 @@ switch from using one to using the other. <canvas id="c"></canvas> <script type="module" src="resources/threejs-materials.js"></script> -
true
Other
mrdoob
three.js
0c4969b330f0e84636d4f535a2e90dc80249a68e.json
remove extra lines
threejs/lessons/threejs-optimize-lots-of-objects-animated.md
@@ -266,7 +266,6 @@ First let's change `addBoxes` to just make and return the merged geometry. ... - - const mergedGeometry = BufferGeometryUtils.mergeBufferGeometries( - geometries, false); - const material = new THREE.MeshBasicMaterial({ @@ -725,4 +724,3 @@ not make a good visualization. Feel free to change the `amountGreaterThan` from `Math.max(a - b, 0)` to something like `(a - b)` "raw difference" or `a / (a + b)` "percent" and you'll see what I mean. -
true
Other
mrdoob
three.js
0c4969b330f0e84636d4f535a2e90dc80249a68e.json
remove extra lines
threejs/lessons/threejs-primitives.md
@@ -352,4 +352,3 @@ to use it](threejs-scenegraph.html). <link rel="stylesheet" href="resources/threejs-primitives.css"> <script type="module" src="resources/threejs-primitives.js"></script> -
true
Other
mrdoob
three.js
0c4969b330f0e84636d4f535a2e90dc80249a68e.json
remove extra lines
threejs/lessons/threejs-shadows.md
@@ -129,7 +129,6 @@ The shadow is a `MeshBasicMaterial` because it doesn't need lighting. We make each sphere a different hue and then save off the base, the sphere mesh, the shadow mesh and the initial y position of each sphere. - ```js const numSpheres = 15; for (let i = 0; i < numSpheres; ++i) { @@ -434,7 +433,6 @@ from our [article about lights](threejs-lights.html). {{{example url="../threejs-shadows-spot-light-with-camera-gui.html" }}} - <!-- You can notice, just like the last example if we set the angle high then the shadow map, the texture is spread over a very large area and @@ -449,7 +447,6 @@ also blur the result --> - And finally there's shadows with a `PointLight`. Since a `PointLight` shines in all directions the only relevent settings are `near` and `far`. Otherwise the `PointLight` shadow is effectively 6 `SpotLight` shadows
true
Other
mrdoob
three.js
0c4969b330f0e84636d4f535a2e90dc80249a68e.json
remove extra lines
threejs/lessons/threejs-voxel-geometry.md
@@ -1068,7 +1068,6 @@ in the adjacent cell might need new geometry. This means we need to check the cell for the voxel we just edited as well as in all 6 directions from that cell. - ```js const neighborOffsets = [ [ 0, 0, 0], // self @@ -1215,4 +1214,3 @@ to generate some what efficient geometry. <canvas id="c"></canvas> <script type="module" src="resources/threejs-voxel-geometry.js"></script> -
true
Other
mrdoob
three.js
0c4969b330f0e84636d4f535a2e90dc80249a68e.json
remove extra lines
threejs/lessons/tools/geo-picking/README.md
@@ -24,4 +24,3 @@ export the table called `level1` to a json file called `level1.json` Then run a simple server like above and open `make-geo-picking-texture-ogc.html` in your browser. -
true
Other
mrdoob
three.js
0c4969b330f0e84636d4f535a2e90dc80249a68e.json
remove extra lines
threejs/lessons/tools/geo-picking/make-geo-picking-texture-ogc.html
@@ -9,7 +9,6 @@ // # need to draw to 2nd canvas, then shave off non perfect pixels - async function main() { const ctx = document.querySelector('canvas').getContext('2d'); ctx.canvas.width = 2048;
true
Other
mrdoob
three.js
0c4969b330f0e84636d4f535a2e90dc80249a68e.json
remove extra lines
threejs/lessons/zh_cn/index.md
@@ -4,12 +4,10 @@ Title: Three.js基础 {{{include "threejs/lessons/toc.html"}}} - <!-- {{{table_of_contents}}} --> -
true