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 | laravel | framework | 28b6f2e6c9490d4d55ccdeeb6dbd8352c15bfb28.json | Add implicit extensions to validator | tests/Validation/ValidationFactoryTest.php | @@ -22,9 +22,10 @@ public function testMakeMethodCreatesValidValidator()
$presence = m::mock('Illuminate\Validation\PresenceVerifierInterface');
$factory->extend('foo', function() {});
+ $factory->extendImplicit('implicit', function() {});
$factory->setPresenceVerifier($presence);
$validator = $factory->make(array(), array());
- $this->assertEquals(array('foo' => function() {}), $validator->getExtensions());
+ $this->assertEquals(array('foo' => function() {}, 'implicit' => function() {}), $validator->getExtensions());
$this->assertEquals($presence, $validator->getPresenceVerifier());
}
| true |
Other | laravel | framework | 28b6f2e6c9490d4d55ccdeeb6dbd8352c15bfb28.json | Add implicit extensions to validator | tests/Validation/ValidationValidatorTest.php | @@ -623,6 +623,15 @@ public function testCustomValidators()
}
+ public function testCustomImplicitValidators()
+ {
+ $trans = $this->getRealTranslator();
+ $v = new Validator($trans, array(), array('implicit_rule' => 'foo'));
+ $v->addImplicitExtension('implicit_rule', function() { return true; });
+ $this->assertTrue($v->passes());
+ }
+
+
protected function getTranslator()
{
return m::mock('Symfony\Component\Translation\TranslatorInterface'); | true |
Other | laravel | framework | a98ad9d4610e27bd7bf243a026a696f60647a394.json | fix bug in sqlite truncate. | src/Illuminate/Database/Query/Grammars/SQLiteGrammar.php | @@ -74,11 +74,9 @@ public function compileInsert(Builder $query, array $values)
*/
public function compileTruncate(Builder $query)
{
- $table = $this->wrapTable($query->from);
-
- $sql = array('delete from sqlite_sequence where name = ?' => array($table));
+ $sql = array('delete from sqlite_sequence where name = ?' => array($query->from));
- $sql['delete from '.$table] = array();
+ $sql['delete from '.$this->wrapTable($query->from)] = array();
return $sql;
} | true |
Other | laravel | framework | a98ad9d4610e27bd7bf243a026a696f60647a394.json | fix bug in sqlite truncate. | tests/Database/DatabaseQueryBuilderTest.php | @@ -522,7 +522,7 @@ public function testTruncateMethod()
$builder = $this->getBuilder();
$builder->from('users');
$this->assertEquals(array(
- 'delete from sqlite_sequence where name = ?' => array('"users"'),
+ 'delete from sqlite_sequence where name = ?' => array('users'),
'delete from "users"' => array(),
), $sqlite->compileTruncate($builder));
} | true |
Other | laravel | framework | 6c3e34b7e64b4757c827d10323f55c1a4f4b0ced.json | fix argument order passing to url generator. | src/Illuminate/Routing/Redirector.php | @@ -55,7 +55,7 @@ public function back($status = 302, $headers = array())
*/
public function to($path, $status = 302, $headers = array(), $secure = false)
{
- $path = $this->generator->to($path, $secure);
+ $path = $this->generator->to($path, array(), $secure);
return $this->createRedirect($path, $status, $headers);
} | false |
Other | laravel | framework | 69a1f9616f55de439dca3800ed544861dbaf40e4.json | Fix foreach order. | src/Illuminate/Routing/Router.php | @@ -202,7 +202,7 @@ public function any($pattern, $action)
*/
public function controllers(array $controllers)
{
- foreach ($controllers as $name => $uri)
+ foreach ($controllers as $uri => $name)
{
$this->controller($uri, $name);
} | false |
Other | laravel | framework | 2c1ccba4864f017f3a473f52a3957eefe5f50982.json | Fix parameter order on Route::controllers. | src/Illuminate/Routing/Router.php | @@ -204,7 +204,7 @@ public function controllers(array $controllers)
{
foreach ($controllers as $name => $uri)
{
- $this->controller($name, $uri);
+ $this->controller($uri, $name);
}
}
| false |
Other | laravel | framework | fc7943b495fdce550a85e1c24ef1b4efab26045f.json | use setFrom instead of addFrom. | src/Illuminate/Mail/Message.php | @@ -33,7 +33,7 @@ public function __construct($swift)
*/
public function from($address, $name = null)
{
- $this->swift->addFrom($address, $name);
+ $this->swift->setFrom($address, $name);
return $this;
} | false |
Other | laravel | framework | 24a3fc8ccf7d6839e42f5f509e413bbcde8ac06b.json | fix bug in wincache driver. | src/Illuminate/Cache/WinCacheStore.php | @@ -46,7 +46,7 @@ protected function retrieveItem($key)
*/
protected function storeItem($key, $value, $minutes)
{
- wincache_ucache_add($this->prefix.$key, value, $minutes * 60);
+ wincache_ucache_add($this->prefix.$key, $value, $minutes * 60);
}
/** | false |
Other | laravel | framework | 04308b7c4435d96f05822f76b1d652ca565c9783.json | throw notfoundhttpexception on app::abort(404) | src/Illuminate/Foundation/Application.php | @@ -485,7 +485,14 @@ public function setLocale($locale)
*/
public function abort($code, $message = '', array $headers = array())
{
- throw new HttpException($code, $message, null, $headers);
+ if ($code == 404)
+ {
+ throw new NotFoundHttpException($message);
+ }
+ else
+ {
+ throw new HttpException($code, $message, null, $headers);
+ }
}
/** | false |
Other | laravel | framework | b59741374d692934cfe86ca095296447bea96033.json | fix fallback locale. | src/Illuminate/Translation/Translator.php | @@ -3,6 +3,7 @@
use Illuminate\Support\NamespacedItemResolver;
use Symfony\Component\Translation\Loader\ArrayLoader;
use Symfony\Component\Translation\TranslatorInterface;
+use Symfony\Component\Translation\Translator as SymfonyTranslator;
class Translator extends NamespacedItemResolver implements TranslatorInterface {
@@ -20,6 +21,13 @@ class Translator extends NamespacedItemResolver implements TranslatorInterface {
*/
protected $trans;
+ /**
+ * The fallback locale for the translator.
+ *
+ * @var string
+ */
+ protected $fallback;
+
/**
* The array of loaded translation groups.
*
@@ -40,6 +48,8 @@ public function __construct(LoaderInterface $loader, $default, $fallback)
{
$this->loader = $loader;
+ $this->fallback = $fallback;
+
$this->trans = $this->createSymfonyTranslator($default, $fallback);
}
@@ -166,26 +176,40 @@ public function load($group, $namespace, $locale)
{
$domain = $namespace.'::'.$group;
- $locale = $locale ?: $this->getLocale();
-
- // The domain is used to store the messages in the Symfony translator object
- // and functions as a sort of logical separator of message types so we'll
- // use the namespace and group as the "domain", which should be unique.
- if ($this->loaded($group, $namespace, $locale))
+ foreach ($this->getLocales($locale) as $locale)
{
- return $domain;
+ // The domain is used to store the messages in the Symfony translator object
+ // and functions as a sort of logical separator of message types so we'll
+ // use the namespace and group as the "domain", which should be unique.
+ if ($this->loaded($group, $namespace, $locale))
+ {
+ return $domain;
+ }
+
+ $lines = $this->loader->load($locale, $group, $namespace);
+
+ // We're finally ready to load the array of messages from the loader and add
+ // them to the Symfony translator. We will also convert this array to dot
+ // format so that deeply nested items will be accessed by a translator.
+ $this->addResource(array_dot($lines), $locale, $domain);
+
+ $this->setLoaded($group, $namespace, $locale);
}
- $lines = $this->loader->load($locale, $group, $namespace);
-
- // We're finally ready to load the array of messages from the loader and add
- // them to the Symfony translator. We will also convert this array to dot
- // format so that deeply nested items will be accessed by a translator.
- $this->addResource(array_dot($lines), $locale, $domain);
+ return $domain;
+ }
- $this->setLoaded($group, $namespace, $locale);
+ /**
+ * Get the locales to be loaded.
+ *
+ * @param string $locale
+ * @return array
+ */
+ protected function getLocales($locale)
+ {
+ $locale = $locale ?: $this->getLocale();
- return $domain;
+ return array_unique(array($locale, $this->fallback));
}
/**
@@ -199,8 +223,6 @@ public function load($group, $namespace, $locale)
protected function addResource(array $lines, $locale, $domain)
{
$this->trans->addResource('array', $lines, $locale, $domain);
-
- $this->trans->refreshCatalogue($locale);
}
/** | true |
Other | laravel | framework | b59741374d692934cfe86ca095296447bea96033.json | fix fallback locale. | tests/Translation/TranslationTranslatorTest.php | @@ -56,9 +56,10 @@ public function testLoadMethodProperlyCallsLoaderToRetrieveItems()
{
$t = new Translator($loader = $this->getLoader(), 'en', 'sp');
$loader->shouldReceive('load')->once()->with('en', 'foo', 'bar')->andReturn(array('messages' => array('foo' => 'bar')));
+ $loader->shouldReceive('load')->once()->with('sp', 'foo', 'bar')->andReturn(array());
$t->setSymfonyTranslator($base = m::mock('Illuminate\Translation\SymfonyTranslator'));
$base->shouldReceive('addResource')->once()->with('array', array('messages.foo' => 'bar'), 'en', 'bar::foo');
- $base->shouldReceive('refreshCatalogue')->once()->with('en');
+ $base->shouldReceive('addResource')->once()->with('array', array(), 'sp', 'bar::foo');
$base->shouldReceive('getLocale')->andReturn('en');
$domain = $t->load('foo', 'bar', null);
@@ -72,11 +73,11 @@ public function testLoadMethodProperlyCallsLoaderToRetrieveItems()
public function testKeyIsReturnedThroughTransMethodsWhenItemsDontExist()
{
$t = new Translator($loader = $this->getLoader(), 'en', 'sp');
- $loader->shouldReceive('load')->once()->andReturn(array());
+ $loader->shouldReceive('load')->twice()->andReturn(array());
$t->setSymfonyTranslator($base = m::mock('Illuminate\Translation\SymfonyTranslator'));
$base->shouldReceive('getLocale')->andReturn('en');
- $base->shouldReceive('addResource');
- $base->shouldReceive('refreshCatalogue')->once()->with('en');
+ $base->shouldReceive('addResource')->once()->with('array', array(), 'en', '::foo');
+ $base->shouldReceive('addResource')->once()->with('array', array(), 'sp', '::foo');
$base->shouldReceive('trans')->once()->with('bar', array(), '::foo', null)->andReturn('bar');
$this->assertEquals('foo.bar', $t->trans('foo.bar')); | true |
Other | laravel | framework | b6869eb887d8c4bc6f71b57f2dc7b91cef2cca49.json | allow generic custom rules on validator. | src/Illuminate/Validation/Validator.php | @@ -853,14 +853,14 @@ protected function getMessage($attribute, $rule)
{
$lowerRule = strtolower(snake_case($rule));
- $inlineKey = "{$attribute}.{$lowerRule}";
+ $inlineMessage = $this->getInlineMessage($attribute, $lowerRule);
// First we will retrieve the custom message for the validation rule if one
// exists. If a custom validation message is being used we'll return the
// custom message, otherwise we'll keep searching for a valid message.
- if (isset($this->customMessages[$inlineKey]))
+ if ( ! is_null($inlineMessage))
{
- return $this->customMessages[$inlineKey];
+ return $inlineMessage;
}
$customKey = "validation.custom.{$attribute}.{$lowerRule}";
@@ -894,6 +894,29 @@ protected function getMessage($attribute, $rule)
}
}
+ /**
+ * Get the inline message for a rule if it exists.
+ *
+ * @param string $attribute
+ * @param string $lowerRule
+ * @return string
+ */
+ protected function getInlineMessage($attribute, $lowerRule)
+ {
+ $keys = array($lowerRule, "{$attribute}.{$lowerRule}");
+
+ // First we will check for a custom message for an attribute specific rule
+ // message for the fields, then we will check for a general custom line
+ // that is not attribute specific. If we find either we'll return it.
+ foreach ($keys as $key)
+ {
+ if (isset($this->customMessages[$key]))
+ {
+ return $this->customMessages[$key];
+ }
+ }
+ }
+
/**
* Get the proper error message for an attribute and size rule.
* | true |
Other | laravel | framework | b6869eb887d8c4bc6f71b57f2dc7b91cef2cca49.json | allow generic custom rules on validator. | tests/Validation/ValidationValidatorTest.php | @@ -69,6 +69,12 @@ public function testInlineValidationMessagesAreRespected()
$this->assertFalse($v->passes());
$v->messages()->setFormat(':message');
$this->assertEquals('require it please!', $v->messages()->first('name'));
+
+ $trans = $this->getRealTranslator();
+ $v = new Validator($trans, array('name' => ''), array('name' => 'Required'), array('required' => 'require it please!'));
+ $this->assertFalse($v->passes());
+ $v->messages()->setFormat(':message');
+ $this->assertEquals('require it please!', $v->messages()->first('name'));
}
| true |
Other | laravel | framework | 37fc266596f17d0e1e55f93f6f4ec404018b0f8a.json | make translator parameters like L3. | src/Illuminate/Translation/Translator.php | @@ -88,6 +88,8 @@ public function get($key, $parameters = array(), $locale = null)
{
list($namespace, $group, $item) = $this->parseKey($key);
+ $parameters = $this->formatParameters($parameters);
+
// Once we call the "load" method, we will receive back the "domain" for the
// namespace and group. The "domain" is used by the Symfony translator to
// logically separate related groups of messages, and should be unique.
@@ -111,6 +113,11 @@ public function choice($key, $number, $parameters = array(), $locale = null)
{
list($namespace, $group, $item) = $this->parseKey($key);
+ $parameters = $this->formatParameters($parameters);
+
+ // Once we call the "load" method, we will receive back the "domain" for the
+ // namespace and group. The "domain" is used by the Symfony translator to
+ // logically separate related groups of messages, and should be unique.
$domain = $this->load($group, $namespace, $locale);
$line = $this->trans->transChoice($item, $number, $parameters, $domain, $locale);
@@ -157,13 +164,13 @@ public function transChoice($id, $number, array $parameters = array(), $domain =
*/
public function load($group, $namespace, $locale)
{
- // The domain is used to store the messages in the Symfony translator object
- // and functions as a sort of logical separator of message types so we'll
- // use the namespace and group as the "domain", which should be unique.
$domain = $namespace.'::'.$group;
$locale = $locale ?: $this->getLocale();
+ // The domain is used to store the messages in the Symfony translator object
+ // and functions as a sort of logical separator of message types so we'll
+ // use the namespace and group as the "domain", which should be unique.
if ($this->loaded($group, $namespace, $locale))
{
return $domain;
@@ -196,6 +203,24 @@ protected function addResource(array $lines, $locale, $domain)
$this->trans->refreshCatalogue($locale);
}
+ /**
+ * Format the parameter array.
+ *
+ * @param array $parameters
+ * @return array
+ */
+ protected function formatParameters($parameters)
+ {
+ foreach ($parameters as $key => $value)
+ {
+ $parameters[':'.$key] = $value;
+
+ unset($parameters[$key]);
+ }
+
+ return $parameters;
+ }
+
/**
* Determine if the given group has been loaded.
* | true |
Other | laravel | framework | 37fc266596f17d0e1e55f93f6f4ec404018b0f8a.json | make translator parameters like L3. | tests/Translation/TranslationTranslatorTest.php | @@ -35,9 +35,9 @@ public function testGetMethodProperlyLoadsAndRetrievesItem()
$t = $this->getMock('Illuminate\Translation\Translator', array('load', 'trans'), array($this->getLoader(), 'en', 'sp'));
$t->expects($this->once())->method('load')->with($this->equalTo('bar'), $this->equalTo('foo'), $this->equalTo('en'))->will($this->returnValue('foo::bar'));
$t->setSymfonyTranslator($base = m::mock('Illuminate\Translation\SymfonyTranslator'));
- $base->shouldReceive('trans')->once()->with('baz', array('foo'), 'foo::bar', 'en')->andReturn('breeze');
+ $base->shouldReceive('trans')->once()->with('baz', array(':foo' => 'bar'), 'foo::bar', 'en')->andReturn('breeze');
- $this->assertEquals('breeze', $t->get('foo::bar.baz', array('foo'), 'en'));
+ $this->assertEquals('breeze', $t->get('foo::bar.baz', array('foo' => 'bar'), 'en'));
}
@@ -46,9 +46,9 @@ public function testChoiceMethodProperlyLoadsAndRetrievesItem()
$t = $this->getMock('Illuminate\Translation\Translator', array('load', 'transChoice'), array($this->getLoader(), 'en', 'sp'));
$t->expects($this->once())->method('load')->with($this->equalTo('bar'), $this->equalTo('foo'), $this->equalTo('en'))->will($this->returnValue('foo::bar'));
$t->setSymfonyTranslator($base = m::mock('Illuminate\Translation\SymfonyTranslator'));
- $base->shouldReceive('transChoice')->once()->with('baz', 10, array('foo'), 'foo::bar', 'en')->andReturn('breeze');
+ $base->shouldReceive('transChoice')->once()->with('baz', 10, array(':foo' => 'bar'), 'foo::bar', 'en')->andReturn('breeze');
- $this->assertEquals('breeze', $t->choice('foo::bar.baz', 10, array('foo'), 'en'));
+ $this->assertEquals('breeze', $t->choice('foo::bar.baz', 10, array('foo' => 'bar'), 'en'));
}
| true |
Other | laravel | framework | 60f26afc13d943b5a2ae546307224c8178c41005.json | allow multi-line echos. | src/Illuminate/View/Compilers/BladeCompiler.php | @@ -146,7 +146,7 @@ protected function compileComments($value)
*/
protected function compileEchos($value)
{
- return preg_replace('/\{\{\s*(.+?)\s*\}\}/', '<?php echo $1; ?>', $value);
+ return preg_replace('/\{\{\s*(.+?)\s*\}\}/s', '<?php echo $1; ?>', $value);
}
/** | false |
Other | laravel | framework | 7670d5c9462d5a34295cc5967b0d420cb7a5e6a0.json | allow trailing slashes. | src/Illuminate/Routing/Router.php | @@ -667,7 +667,7 @@ protected function findRoute(Request $request)
// that's used by the Illuminate foundation framework for responses.
try
{
- $path = '/'.ltrim($request->getPathInfo(), '/');
+ $path = $this->formatRequestPath($request);
$parameters = $this->getUrlMatcher($request)->match($path);
}
@@ -690,6 +690,24 @@ protected function findRoute(Request $request)
return $route;
}
+ /**
+ * Format the request path info for routing.
+ *
+ * @param Illuminate\Http\Request $request
+ * @return string
+ */
+ protected function formatRequestPath($request)
+ {
+ $path = $request->getPathInfo();
+
+ if (strlen($path) > 1 and ends_with($path, '/'))
+ {
+ return '/'.ltrim(substr($path, 0, -1), '/');
+ }
+
+ return '/'.ltrim($path, '/');
+ }
+
/**
* Register a "before" routing filter.
* | true |
Other | laravel | framework | 7670d5c9462d5a34295cc5967b0d420cb7a5e6a0.json | allow trailing slashes. | tests/Routing/RoutingTest.php | @@ -17,19 +17,15 @@ public function testBasic()
$router = new Router;
$router->get('/', function() { return 'root'; });
$router->get('/foo', function() { return 'bar'; });
- $router->get('/foo//', function() { return 'foo'; });
$request = Request::create('/foo', 'GET');
$this->assertEquals('bar', $router->dispatch($request)->getContent());
- $request = Request::create('/foo//', 'GET');
- $this->assertEquals('foo', $router->dispatch($request)->getContent());
+ $request = Request::create('/foo/', 'GET');
+ $this->assertEquals('bar', $router->dispatch($request)->getContent());
$request = Request::create('http://foo.com', 'GET');
$this->assertEquals('root', $router->dispatch($request)->getContent());
- $request = Request::create('http://foo.com///', 'GET');
- $this->assertEquals('root', $router->dispatch($request)->getContent());
-
$router = new Router;
$router->get('/foo/{name}/{age}', function($name, $age) { return $name.$age; });
$request = Request::create('/foo/taylor/25', 'GET'); | true |
Other | mrdoob | three.js | f618a57397feca711b6749635fc99b0f7c65e8d0.json | add dark mode support to index.css | threejs/lessons/resources/index.css | @@ -42,3 +42,9 @@ iframe.background {
padding: 15px 20px;
}
}
+
+@media (prefers-color-scheme: dark) {
+ .container {
+ background-color: rgba(0, 0, 0, 0.9);
+ }
+} | false |
Other | mrdoob | three.js | a8c5a8ffce852b94a145b94ed041edd57a7bc131.json | remove unneeded css | threejs/lessons/resources/lesson.css | @@ -20,16 +20,10 @@ table {
pre {
background: rgb(143, 140, 140);
padding: 1em;
- line-height: 1;
- background: #444;
- overflow: auto;
}
pre>code {
white-space: inherit;
background: none;
- font-size: 10pt;
- padding: none;
- color: #99e4fd;
}
pre.prettyprint {
margin-top: 2em !important; | false |
Other | mrdoob | three.js | 519e74d868c5bb8b05e862ee811d67fb520f721f.json | fix build to add class to code blocks | build/js/build.js | @@ -400,6 +400,9 @@ const Builder = function(outBaseDir, options) {
const info = extractHandlebars(content);
let html = marked(info.content);
// HACK! :-(
+ // There's probably a way to do this in marked
+ html = html.replace(/<pre><code/g, '<pre class="prettyprint"><code');
+ // HACK! :-(
if (opt_extra && opt_extra.home && opt_extra.home.length > 1) {
html = hackRelLinks(html, pageUrl);
} | false |
Other | mrdoob | three.js | 2c9e8dd148c3d6fa1b7fe63fa7ac436ade632f15.json | use one canvas | threejs/lessons/threejs-canvas-textures.md | @@ -365,6 +365,40 @@ and we get labels where the text is centered and scaled to fit
{{{example url="../threejs-canvas-textured-labels-scale-to-fit.html" }}}
+Above we used a new canvas for each texture. Whether or not to use a
+canvas per texture is up to you. If you need to up them often then
+having one canvas per texture is probably the best option. If they are
+rarely or never updated then you can choose to use a single canvas
+for multiple textures by calling `WebGLRenderer.setTexture2D`.
+Let's change the code above to do just that.
+
+```js
++const ctx = document.createElement('canvas').getContext('2d');
+
+function makeLabelCanvas(baseWidth, size, name) {
+ const borderSize = 2;
+- const ctx = document.createElement('canvas').getContext('2d');
+ const font = `${size}px bold sans-serif`;
+
+ ...
+
+}
+
+function makePerson(x, labelWidth, size, name, color) {
+ const canvas = makeLabelCanvas(labelWidth, size, name);
+ const texture = new THREE.CanvasTexture(canvas);
+ // because our canvas is likely not a power of 2
+ // in both dimensions set the filtering appropriately.
+ texture.minFilter = THREE.LinearFilter;
+ texture.wrapS = THREE.ClampToEdgeWrapping;
+ texture.wrapT = THREE.ClampToEdgeWrapping;
++ renderer.setTexture2D(texture, 0);
+
+ ...
+```
+
+{{{example url="../threejs-canvas-textured-labels-one-canvas.html" }}}
+
Another issue is that the labels don't always face the camera. If you're using
labels as badges that's probably a good thing. If you're using labels to put
names over players in a 3D game maybe you want the labels to always face the camera. | true |
Other | mrdoob | three.js | 2c9e8dd148c3d6fa1b7fe63fa7ac436ade632f15.json | use one canvas | threejs/threejs-canvas-textured-labels-one-canvas.html | @@ -0,0 +1,186 @@
+<!-- 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 - Canvas Textured Labels One Canvas</title>
+ <style>
+ body {
+ margin: 0;
+ }
+ #c {
+ width: 100vw;
+ height: 100vh;
+ display: block;
+ }
+ </style>
+ </head>
+ <body>
+ <canvas id="c"></canvas>
+ </body>
+<script src="resources/threejs/r102/three.min.js"></script>
+<script src="resources/threejs/r102/js/controls/OrbitControls.js"></script>
+<script>
+'use strict';
+
+/* global THREE */
+
+function main() {
+ const canvas = document.querySelector('#c');
+ const renderer = new THREE.WebGLRenderer({canvas: canvas});
+
+ 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);
+ camera.position.set(0, 2, 5);
+
+ const controls = new THREE.OrbitControls(camera, canvas);
+ controls.target.set(0, 2, 0);
+ controls.update();
+
+ const scene = new THREE.Scene();
+ scene.background = new THREE.Color('white');
+
+ function addLight(position) {
+ const color = 0xFFFFFF;
+ const intensity = 1;
+ const light = new THREE.DirectionalLight(color, intensity);
+ light.position.set(...position);
+ scene.add(light);
+ scene.add(light.target);
+ }
+ addLight([-3, 1, 1]);
+ addLight([ 2, 1, .5]);
+
+ const bodyRadiusTop = .4;
+ const bodyRadiusBottom = .2;
+ const bodyHeight = 2;
+ const bodyRadialSegments = 6;
+ const bodyGeometry = new THREE.CylinderBufferGeometry(
+ bodyRadiusTop, bodyRadiusBottom, bodyHeight, bodyRadialSegments);
+
+ const headRadius = bodyRadiusTop * 0.8;
+ const headLonSegments = 12;
+ const headLatSegments = 5;
+ const headGeometry = new THREE.SphereBufferGeometry(
+ headRadius, headLonSegments, headLatSegments);
+
+ const labelGeometry = new THREE.PlaneBufferGeometry(1, 1);
+
+ const ctx = document.createElement('canvas').getContext('2d');
+
+ function makeLabelCanvas(baseWidth, size, name) {
+ const borderSize = 2;
+ const font = `${size}px bold sans-serif`;
+ ctx.font = font;
+ // measure how long the name will be
+ const textWidth = ctx.measureText(name).width;
+
+ const doubleBorderSize = borderSize * 2;
+ const width = baseWidth + doubleBorderSize;
+ const height = size + doubleBorderSize;
+ ctx.canvas.width = width;
+ ctx.canvas.height = height;
+
+ // need to set font again after resizing canvas
+ ctx.font = font;
+ ctx.textBaseline = 'middle';
+ ctx.textAlign = 'center';
+
+ ctx.fillStyle = 'blue';
+ ctx.fillRect(0, 0, width, height);
+
+ // scale to fit but don't stretch
+ const scaleFactor = Math.min(1, baseWidth / textWidth);
+ ctx.translate(width / 2, height / 2);
+ ctx.scale(scaleFactor, 1);
+ ctx.fillStyle = 'white';
+ ctx.fillText(name, 0, 0);
+
+ return ctx.canvas;
+ }
+
+ function makePerson(x, labelWidth, size, name, color) {
+ const canvas = makeLabelCanvas(labelWidth, size, name);
+ const texture = new THREE.CanvasTexture(canvas);
+ // because our canvas is likely not a power of 2
+ // in both dimensions set the filtering appropriately.
+ texture.minFilter = THREE.LinearFilter;
+ texture.wrapS = THREE.ClampToEdgeWrapping;
+ texture.wrapT = THREE.ClampToEdgeWrapping;
+ renderer.setTexture2D(texture, 0);
+
+ const labelMaterial = new THREE.MeshBasicMaterial({
+ map: texture,
+ side: THREE.DoubleSide,
+ transparent: true,
+ });
+ const bodyMaterial = new THREE.MeshPhongMaterial({
+ color,
+ flatShading: true,
+ });
+
+ const root = new THREE.Object3D();
+ root.position.x = x;
+
+ const body = new THREE.Mesh(bodyGeometry, bodyMaterial);
+ root.add(body);
+ body.position.y = bodyHeight / 2;
+
+ const head = new THREE.Mesh(headGeometry, bodyMaterial);
+ root.add(head);
+ head.position.y = bodyHeight + headRadius * 1.1;
+
+ const label = new THREE.Mesh(labelGeometry, labelMaterial);
+ root.add(label);
+ label.position.y = bodyHeight * 4 / 5;
+ label.position.z = bodyRadiusTop * 1.01;
+
+ // if units are meters then 0.01 here makes size
+ // of the label into centimeters.
+ const labelBaseScale = 0.01;
+ label.scale.x = canvas.width * labelBaseScale;
+ label.scale.y = canvas.height * labelBaseScale;
+
+ scene.add(root);
+ return root;
+ }
+
+ makePerson(-3, 150, 32, 'Purple People Eater', 'purple');
+ makePerson(-0, 150, 32, 'Green Machine', 'green');
+ makePerson(+3, 150, 32, 'Red Menace', 'red');
+
+ 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 | 6b1afd44966074033493bc65e3a036f718d045f8.json | change main page | build/templates/index.template | @@ -80,7 +80,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
</div>
{{{content}}}
<div>
- 3d scene by: <a href="https://sketchfab.com/elsergio217">elsergio217</a>
+ flamingo by: <a href="http://mirada.com/">mirada</a>
</div>
</div>
</div> | true |
Other | mrdoob | three.js | 6b1afd44966074033493bc65e3a036f718d045f8.json | change main page | threejs/background-v01.html | @@ -0,0 +1,193 @@
+<!-- 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 - Fundamentals</title>
+ <link type="text/css" href="resources/threejs-tutorials.css" rel="stylesheet" />
+ <style>
+ html, body {
+ margin: 0;
+ height: 100%;
+ }
+ canvas {
+ width: 100%;
+ height: 100%;
+ display: block;
+ }
+ </style>
+ </head>
+ <body>
+ <canvas id="c"></canvas>
+ </body>
+<script src="resources/threejs/r102/three.min.js"></script>
+<script src="resources/threejs/r102/js/controls/OrbitControls.js"></script>
+<script src="resources/threejs/r102/js/shaders/SSAOShader.js"></script>
+<script src="resources/threejs/r102/js/shaders/CopyShader.js"></script>
+<script src="resources/threejs/r102/js/postprocessing/EffectComposer.js"></script>
+<script src="resources/threejs/r102/js/postprocessing/RenderPass.js"></script>
+<script src="resources/threejs/r102/js/postprocessing/ShaderPass.js"></script>
+<script src="resources/threejs/r102/js/postprocessing/MaskPass.js"></script>
+<script src="resources/threejs/r102/js/postprocessing/SSAOPass.js"></script>
+<script src="resources/threejs/r102/js/loaders/GLTFLoader.js"></script>
+<script>
+'use strict';
+
+/* global THREE */
+
+function main() {
+ const canvas = document.querySelector('#c');
+ const renderer = new THREE.WebGLRenderer({canvas: canvas});
+ const scene = new THREE.Scene();
+
+ const aspect = 2; // the canvas default
+ const fov = 35;
+ const near = 0.1;
+ const far = 5000;
+ const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
+ camera.position.x = -0.;
+ camera.position.y = 350;
+ camera.position.z = 40.;
+
+ const useFog = true;
+ const useOrbitCamera = false;
+ const showHelpers = false;
+ const camSpeed = 0.2;
+
+ if (useOrbitCamera) {
+ const controls = new THREE.OrbitControls(camera);
+ controls.target.set(0, 100.01, 0.2);
+ controls.update();
+ }
+
+ renderer.gammaInput = true;
+ renderer.gammaOutput = true;
+ renderer.shadowMap.enabled = true;
+
+ const hemiLight = new THREE.HemisphereLight(0xffffff, 0xffffff, 0.6);
+ hemiLight.color.setHSL(0.6, 1, 0.6);
+ hemiLight.groundColor.setHSL(0.095, 1, 0.75);
+ hemiLight.position.set(0, 50, 0);
+ scene.add(hemiLight);
+
+ if (showHelpers) {
+ const hemiLightHelper = new THREE.HemisphereLightHelper(hemiLight, 10);
+ scene.add(hemiLightHelper);
+ }
+
+ const dirLight = new THREE.DirectionalLight(0xffffff, 1);
+ dirLight.color.setHSL(0.1, 1, 0.95);
+ dirLight.position.set(-300, 220, 245);
+ scene.add(dirLight);
+ dirLight.castShadow = true;
+ dirLight.shadow.mapSize.width = 2048;
+ dirLight.shadow.mapSize.height = 2048;
+ const d = 350;
+ dirLight.shadow.camera.left = -d;
+ dirLight.shadow.camera.right = d;
+ dirLight.shadow.camera.top = d;
+ dirLight.shadow.camera.bottom = -d;
+ dirLight.shadow.camera.near = 100;
+ dirLight.shadow.camera.far = 950;
+ dirLight.shadow.bias = -0.005;
+
+ if (showHelpers) {
+ const dirLightHeper = new THREE.DirectionalLightHelper(dirLight, 10);
+ scene.add(dirLightHeper);
+ }
+
+ const loader = new THREE.GLTFLoader();
+ const camRadius = 600;
+ const camHeight = 160;
+ const camTarget = [0, 30, 0];
+ const fogNear = 1350;
+ const fogFar = 1500;
+ loader.load('resources/models/mountain_landscape/scene.gltf', (gltf) => {
+ gltf.scene.traverse((child) => {
+ if ( child.isMesh ) {
+ child.castShadow = true;
+ child.receiveShadow = true;
+ }
+ });
+ scene.add(gltf.scene);
+ });
+
+ window.s = scene;
+
+ if (useFog) {
+ const vertexShader = `
+ varying vec3 vWorldPosition;
+ void main() {
+ vec4 worldPosition = modelMatrix * vec4( position, 1.0 );
+ vWorldPosition = worldPosition.xyz;
+ gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
+ }
+ `;
+
+ const fragmentShader = `
+ uniform vec3 topColor;
+ uniform vec3 bottomColor;
+ uniform float offset;
+ uniform float exponent;
+ varying vec3 vWorldPosition;
+ void main() {
+ float h = normalize( vWorldPosition + offset ).y;
+ gl_FragColor = vec4( mix( bottomColor, topColor, max( pow( max( h , 0.0), exponent ), 0.0 ) ), 1.0 );
+ }
+ `;
+
+ const uniforms = {
+ topColor: { value: new THREE.Color(0x88AABB) },
+ bottomColor: { value: new THREE.Color(0xEFCB7F) },
+ offset: { value: 730 },
+ exponent: { value: 0.3 },
+ };
+ uniforms.topColor.value.copy(hemiLight.color);
+ scene.fog = new THREE.Fog(scene.background, fogNear, fogFar);
+ scene.fog.color.copy(uniforms.bottomColor.value);
+ const skyGeo = new THREE.SphereBufferGeometry(4000, 32, 15);
+ const skyMat = new THREE.ShaderMaterial( { vertexShader: vertexShader, fragmentShader: fragmentShader, uniforms: uniforms, side: THREE.BackSide } );
+ const sky = new THREE.Mesh( skyGeo, skyMat );
+ scene.add(sky);
+ }
+
+ function resizeRendererToDisplaySize(renderer) {
+ const canvas = renderer.domElement;
+ const width = canvas.clientWidth;
+ const height = canvas.clientHeight;
+ if (width === canvas.width && height === canvas.height) {
+ return false;
+ }
+
+ renderer.setSize(width, height, false);
+ return true;
+ }
+
+ function render(time) {
+ time *= 0.001;
+ time += 80;
+
+ if (resizeRendererToDisplaySize(renderer)) {
+ camera.aspect = canvas.clientWidth / canvas.clientHeight;
+ camera.updateProjectionMatrix();
+ }
+
+ if (!useOrbitCamera) {
+ const angle = Math.sin(time * camSpeed) + Math.PI * .75;
+ camera.position.set(Math.cos(angle) * camRadius, camHeight, Math.sin(angle) * camRadius);
+ camera.lookAt(...camTarget);
+ }
+
+ renderer.render(scene, camera);
+
+ requestAnimationFrame(render);
+ }
+
+ requestAnimationFrame(render);
+}
+
+main();
+</script>
+</html>
+ | true |
Other | mrdoob | three.js | 6b1afd44966074033493bc65e3a036f718d045f8.json | change main page | threejs/background.html | @@ -46,18 +46,19 @@
const near = 0.1;
const far = 5000;
const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
- camera.position.x = -0.;
- camera.position.y = 350;
- camera.position.z = 40.;
+ camera.position.set(-580, 55, 390);
+ const maxFovX = 40;
+ const numBirds = 40;
+ const minMax = 700;
+ const birdSpeed = 100;
const useFog = true;
- const useOrbitCamera = false;
+ const useOrbitCamera = true;
const showHelpers = false;
- const camSpeed = 0.2;
if (useOrbitCamera) {
const controls = new THREE.OrbitControls(camera);
- controls.target.set(0, 100.01, 0.2);
+ controls.target.set(0, 0, 0);
controls.update();
}
@@ -66,8 +67,8 @@
renderer.shadowMap.enabled = true;
const hemiLight = new THREE.HemisphereLight(0xffffff, 0xffffff, 0.6);
- hemiLight.color.setHSL(0.6, 1, 0.6);
- hemiLight.groundColor.setHSL(0.095, 1, 0.75);
+ hemiLight.color.setHSL(0.6, 1, 0.5);
+ hemiLight.groundColor.setHSL(0.095, 1, 0.5);
hemiLight.position.set(0, 50, 0);
scene.add(hemiLight);
@@ -97,20 +98,48 @@
scene.add(dirLightHeper);
}
+ const birds = [];
const loader = new THREE.GLTFLoader();
- const camRadius = 600;
- const camHeight = 160;
- const camTarget = [0, 30, 0];
const fogNear = 1350;
const fogFar = 1500;
- loader.load('resources/models/mountain_landscape/scene.gltf', (gltf) => {
- gltf.scene.traverse((child) => {
- if ( child.isMesh ) {
- child.castShadow = true;
- child.receiveShadow = true;
- }
- });
- scene.add(gltf.scene);
+
+ function rand(min, max) {
+ if (min === undefined) {
+ min = 0;
+ max = 1;
+ } else if (max === undefined) {
+ max = min;
+ min = 0;
+ }
+ return min + Math.random() * (max - min);
+ }
+
+ loader.load( 'resources/models/flamingo/Flamingo.glb', (gltf) => {
+ const orig = gltf.scene.children[0];
+ orig.castShadow = true;
+ orig.receiveShadow = true;
+
+ for (let i = 0; i < numBirds; ++i) {
+ const u = i / (numBirds - 1);
+ const mesh = orig.clone();
+ mesh.position.set(
+ rand(-150, 150),
+ (u * 2 - 1) * 200,
+ (minMax * 2 * i * 1.7) % (minMax * 2) - minMax / 2,
+ );
+ scene.add(mesh);
+ mesh.material = mesh.material.clone();
+ mesh.material.color.setHSL(rand(), 1, 0.8);
+
+ const mixer = new THREE.AnimationMixer(mesh);
+ mixer.clipAction(gltf.animations[0]).setDuration(1).play();
+ mixer.update(rand(10));
+ mixer.timeScale = rand(0.9, 1.1);
+ birds.push({
+ mixer,
+ mesh,
+ });
+ }
});
window.s = scene;
@@ -146,7 +175,7 @@
uniforms.topColor.value.copy(hemiLight.color);
scene.fog = new THREE.Fog(scene.background, fogNear, fogFar);
scene.fog.color.copy(uniforms.bottomColor.value);
- const skyGeo = new THREE.SphereBufferGeometry(4000, 32, 15);
+ const skyGeo = new THREE.SphereBufferGeometry(3000, 32, 15);
const skyMat = new THREE.ShaderMaterial( { vertexShader: vertexShader, fragmentShader: fragmentShader, uniforms: uniforms, side: THREE.BackSide } );
const sky = new THREE.Mesh( skyGeo, skyMat );
scene.add(sky);
@@ -164,19 +193,24 @@
return true;
}
- function render(time) {
- time *= 0.001;
- time += 80;
+ let then = 0;
+ function render(now) {
+ now *= 0.001;
+ const deltaTime = now - then;
+ then = now;
if (resizeRendererToDisplaySize(renderer)) {
- camera.aspect = canvas.clientWidth / canvas.clientHeight;
+ const aspect = canvas.clientWidth / canvas.clientHeight;
+ const fovX = THREE.Math.radToDeg(2 * Math.atan(Math.tan(THREE.Math.degToRad(fov) * 0.5) * aspect));
+ const newFovY = THREE.Math.radToDeg(2 * Math.atan(Math.tan(THREE.Math.degToRad(maxFovX) * .5) / aspect));
+ camera.fov = fovX > maxFovX ? newFovY : fov;
+ camera.aspect = aspect;
camera.updateProjectionMatrix();
}
- if (!useOrbitCamera) {
- const angle = Math.sin(time * camSpeed) + Math.PI * .75;
- camera.position.set(Math.cos(angle) * camRadius, camHeight, Math.sin(angle) * camRadius);
- camera.lookAt(...camTarget);
+ for (const {mesh, mixer} of birds) {
+ mixer.update(deltaTime);
+ mesh.position.z = (mesh.position.z + minMax + mixer.timeScale * birdSpeed * deltaTime) % (minMax * 2) - minMax;
}
renderer.render(scene, camera); | true |
Other | mrdoob | three.js | 9d2c2e250371697fc0f8e1e14e71d5f0215571a0.json | add data license | threejs/lessons/threejs-indexed-textures.md | @@ -53,6 +53,9 @@ to generate such a texture. Here it is.
<div class="threejs_center"><img src="../resources/data/world/country-index-texture.png" style="width: 700px;"></div>
+Note: The data used to generate this texture comes from [this website](http://thematicmapping.org/downloads/world_borders.php)
+and is therefore licensed as [CC-BY-SA](http://creativecommons.org/licenses/by-sa/3.0/).
+
It's only 217k, much better than the 14meg for the country meshes. In fact we could probably
even lower the resolution but 217k seems good enough for now.
| true |
Other | mrdoob | three.js | 9d2c2e250371697fc0f8e1e14e71d5f0215571a0.json | add data license | threejs/resources/data/world/license.md | @@ -0,0 +1,11 @@
+# CC-BY-SA
+
+All the data in this folder was generate from data from this website
+
+http://thematicmapping.org/downloads/world_borders.php
+
+The licence of that data is [CC-BY-SA](http://creativecommons.org/licenses/by-sa/3.0/).
+
+Which means this data is also [CC-BY-SA](http://creativecommons.org/licenses/by-sa/3.0/).
+
+ | true |
Other | mrdoob | three.js | bfda3c200408c6ea1165e5d93f83cdb9b8f6e045.json | remove unsued line | threejs/threejs-picking-gpu.html | @@ -165,7 +165,6 @@
1, // height
pixelBuffer);
- //const id = this.idBuffer[0];
const id =
(pixelBuffer[0] << 16) |
(pixelBuffer[1] << 8) | | false |
Other | mrdoob | three.js | e36b7bbd289ce1de56fd972be55d4f508b515b2c.json | fix image scaling | threejs/lessons/threejs-align-html-elements-to-3d.md | @@ -189,7 +189,7 @@ There are a couple of issues we probably want to deal with.
One is that if we rotate the objects so they overlap all the labels
overlap as well.
-<img src="resources/images/overlapping-labels.png" class="threejs_center" style="width: 307px;">
+<div class="threejs_center"><img src="resources/images/overlapping-labels.png" style="width: 307px;"></div>
Another is that if we zoom way out so that the objects go outside
the frustum the labels will still appear.
@@ -314,7 +314,7 @@ I [wrote some code](https://github.com/greggman/threejsfundamentals/blob/master/
to load the data, and generate country outlines and some JSON data with the names
of the countries and their locations.
-<img src="../resources/data/world/country-outlines-4k.png" style="background: black; width: 700px">
+<div class="threejs_center"><img src="../resources/data/world/country-outlines-4k.png" style="background: black; width: 700px"></div>
The JSON data is an array of entries something like this
| false |
Other | mrdoob | three.js | 59726bae96775d035fb14bb05e902567741341dc.json | add lots of objects animated article | threejs/lessons/threejs-optimize-lots-of-objects-animated.md | @@ -0,0 +1,704 @@
+Title: Three.js Optimize Lots of Objects Animated
+Description: Animated merged objects with Morphtargets
+
+This article is a continuation of [an article about optimizing lots of objects
+](threejs-optimize-lots-of-objects.html). If you haven't read that
+yet please read it before proceeding.
+
+In the previous article we merged around 19000 cubes into a
+single geometry. This had the advantage that it optimized our drawing
+of 19000 cubes but it had the disadvantage of make it harder to
+move any individual cube.
+
+Depending on what we are trying to accomplish there are different solutions.
+In this case let's graph multiple sets of data and animate between the sets.
+
+The first thing we need to do is get multiple sets of data. Ideally we'd
+probably pre-process data offline but in this case let's load 2 sets of
+data and generate 2 more
+
+Here's our old loading code
+
+```js
+loadFile('resources/data/gpw/gpw-v4-basic-demographic-characteristics-rev10_a000_014_2010_1_deg_asc/gpw_v4_basic_demographic_characteristics_rev10_a000_014mt_2010_cntm_1_deg.asc')
+ .then(parseData)
+ .then(addBoxes)
+ .then(render);
+```
+
+Let's change it to something like this
+
+```js
+async function loadData(info) {
+ const text = await loadFile(info.url);
+ info.file = parseData(text);
+}
+
+async function loadAll() {
+ const fileInfos = [
+ {name: 'men', hueRange: [0.7, 0.3], url: 'resources/data/gpw/gpw-v4-basic-demographic-characteristics-rev10_a000_014_2010_1_deg_asc/gpw_v4_basic_demographic_characteristics_rev10_a000_014mt_2010_cntm_1_deg.asc' },
+ {name: 'women', hueRange: [0.9, 1.1], url: 'resources/data/gpw/gpw-v4-basic-demographic-characteristics-rev10_a000_014_2010_1_deg_asc/gpw_v4_basic_demographic_characteristics_rev10_a000_014ft_2010_cntm_1_deg.asc' },
+ ];
+
+ await Promise.all(fileInfos.map(loadData));
+
+ ...
+}
+loadAll();
+```
+
+The code above will load all the files in `fileInfos` and when done each object
+in `fileInfos` will have a `file` property with the loaded file. `name` and `hueRange`
+we'll use later. `name` will be for a UI field. `hueRange` will be used to
+choose a range of hues to map over.
+
+The two files above are apparently the number of men per area and the number of
+women per area as of 2010. Note, I have no idea if this data is correct but
+it's not important really. The important part is showing different sets
+of data.
+
+Let's generate 2 more sets of data. One being the places where the number
+men are greater than the number of women and visa versa, the places where
+the number of women are greater than the number of men.
+
+The first thing let's write a function that given a 2 dimensional array of
+of arrays like we had before will map over it to generate a new 2 dimensional
+array of arrays
+
+```js
+function mapValues(data, fn) {
+ return data.map((row, rowNdx) => {
+ return row.map((value, colNdx) => {
+ return fn(value, rowNdx, colNdx);
+ });
+ });
+}
+```
+
+Like the normal `Array.map` function the `mapValues` function calls a function
+`fn` for each value in the array of arrays. It passes it the value and both the
+row and column indices.
+
+Now let's make some code to generate a new file that is a comparison between 2
+files
+
+```js
+function makeDiffFile(baseFile, otherFile, compareFn) {
+ let min;
+ let max;
+ const baseData = baseFile.data;
+ const otherData = otherFile.data;
+ const data = mapValues(baseData, (base, rowNdx, colNdx) => {
+ const other = otherData[rowNdx][colNdx];
+ if (base === undefined || other === undefined) {
+ return undefined;
+ }
+ const value = compareFn(base, other);
+ min = Math.min(min === undefined ? value : min, value);
+ max = Math.max(max === undefined ? value : max, value);
+ return value;
+ });
+ // make a copy of baseFile and replace min, max, and data
+ // with the new data
+ return Object.assign({}, baseFile, {
+ min,
+ max,
+ data,
+ });
+}
+```
+
+The code above uses `mapValues` to generate a new set of data that is
+a comparison based on the `compareFn` function passed in. It also tracks
+the `min` and `max` comparison results. Finally it makes a new file with
+all the same properties as `baseFile` except with a new `min`, `max` and `data`.
+
+Then let's use that to make 2 new sets of data
+
+```js
+{
+ const menInfo = fileInfos[0];
+ const womenInfo = fileInfos[1];
+ const menFile = menInfo.file;
+ const womenFile = womenInfo.file;
+
+ function amountGreaterThan(a, b) {
+ return Math.max(a - b, 0);
+ }
+ fileInfos.push({
+ name: '>50%men',
+ hueRange: [0.6, 0.6],
+ file: makeDiffFile(menFile, womenFile, (men, women) => {
+ return amountGreaterThan(men, women);
+ }),
+ });
+ fileInfos.push({
+ name: '>50% women',
+ hueRange: [0.0, 0.0],
+ file: makeDiffFile(womenFile, menFile, (women, men) => {
+ return amountGreaterThan(women, men);
+ }),
+ });
+}
+```
+
+Now let's generate a UI to select between these sets of data. First we need
+some UI html
+
+```html
+<body>
+ <canvas id="c"></canvas>
++ <div id="ui"></div>
+</body>
+```
+
+and some CSS to make it appear in the top left area
+
+```css
+#ui {
+ position: absolute;
+ left: 1em;
+ top: 1em;
+}
+#ui>div {
+ font-size: 20pt;
+ padding: 1em;
+ display: inline-block;
+}
+#ui>div.selected {
+ color: red;
+}
+```
+
+Then we can go over each file and generate a set of merged boxes per
+set of data and an element which when hovered over will show that set
+and hide all others.
+
+```js
+// show the selected data, hide the rest
+function showFileInfo(fileInfos, fileInfo) {
+ fileInfos.forEach((info) => {
+ const visible = fileInfo === info;
+ info.root.visible = visible;
+ info.elem.className = visible ? 'selected' : '';
+ });
+ requestRenderIfNotRequested();
+}
+
+const uiElem = document.querySelector('#ui');
+fileInfos.forEach((info) => {
+ const boxes = addBoxes(info.file, info.hueRange);
+ info.root = boxes;
+ const div = document.createElement('div');
+ info.elem = div;
+ div.textContent = info.name;
+ uiElem.appendChild(div);
+ div.addEventListener('mouseover', () => {
+ showFileInfo(fileInfos, info);
+ });
+});
+// show the first set of data
+showFileInfo(fileInfos, fileInfos[0]);
+```
+
+The one more change we need from the previous example is we need to make
+`addBoxes` take a `hueRange`
+
+```js
+-function addBoxes(file) {
++function addBoxes(file, hueRange) {
+
+ ...
+
+ // compute a color
+- const hue = THREE.Math.lerp(0.7, 0.3, amount);
++ const hue = THREE.Math.lerp(...hueRange, amount);
+
+ ...
+```
+
+and with that we should be able to show 4 sets of data. Hover the mouse over the labels
+or touch them to switch sets
+
+{{{example url="../threejs-lots-of-objects-multiple-data-sets.html" }}}
+
+Note, there are a few strange data points that really stick out. I wonder what's up
+with those!??! In any case how do we animate between these 4 sets of data.
+
+Lots of ideas.
+
+* Just fade between them using `Material.opacity`
+
+ The problem with this solution is the cubes perfectly overlap which
+ means there will be z-fighting issues. It's possible we could fix
+ that by changing the depth function and using blending. We should
+ probably look into it.
+
+* Scale up the set we want to see and scale down the other sets
+
+ Because all the boxes have their origin at the center of the planet
+ if we scale them below 1.0 they will sink into the planet. At first that
+ sounds like a good idea but the issue is all the low height boxes
+ will disappear almost immediately and not be replaced until the new
+ data set scales up to 1.0. This makes the transition not very pleasant.
+ We could maybe fix that with a fancy custom shader.
+
+* Use Morphtargets
+
+ Morphtargets are a way were we supply multiple values for each vertex
+ in the geometry and *morph* or lerp (linear interpolate) between them.
+ Morphtargets are most commonly used for facial animation of 3D characters
+ but that's not their only use.
+
+Let's try morphtargets.
+
+We'll still make a geometry for each set of data but we'll then extract
+the `position` attribute from each one and use them as morphtargets.
+
+First let's change `addBoxes` to just make and return the merged geometry.
+
+```js
+-function addBoxes(file, hueRange) {
++function makeBoxes(file, hueRange) {
+ const {min, max, data} = file;
+ const range = max - min;
+
+ ...
+
+
+- const mergedGeometry = THREE.BufferGeometryUtils.mergeBufferGeometries(
+- geometries, false);
+- const material = new THREE.MeshBasicMaterial({
+- vertexColors: THREE.VertexColors,
+- });
+- const mesh = new THREE.Mesh(mergedGeometry, material);
+- scene.add(mesh);
+- return mesh;
++ return THREE.BufferGeometryUtils.mergeBufferGeometries(
++ geometries, false);
+}
+```
+
+There's one more thing we need to do here though. Morphtargets are required to
+all have exactly the same number of vertices. Vertex #123 in one target needs
+have a corresponding Vertex #123 in all other targets. But, as it is now
+different data sets might have some data points with no data so no box will be
+generated for that point which would mean no corresponding vertices for another
+set. So, we need to check across all data sets and either always generate
+something if there is data in any set or, generate nothing if there is data
+missing in any set. Let's do the latter.
+
+```js
++function dataMissingInAnySet(fileInfos, latNdx, lonNdx) {
++ for (const fileInfo of fileInfos) {
++ if (fileInfo.file.data[latNdx][lonNdx] === undefined) {
++ return true;
++ }
++ }
++ return false;
++}
+
+-function makeBoxes(file, hueRange) {
++function makeBoxes(file, hueRange, fileInfos) {
+ const {min, max, data} = file;
+ const range = max - min;
+
+ ...
+
+ const geometries = [];
+ data.forEach((row, latNdx) => {
+ row.forEach((value, lonNdx) => {
++ if (dataMissingInAnySet(fileInfos, latNdx, lonNdx)) {
++ return;
++ }
+ const amount = (value - min) / range;
+
+ ...
+```
+
+Now we'll change the code that was calling `addBoxes` to use `makeBoxes`
+and setup morphtargets
+
+```js
++// make geometry for each data set
++const geometries = fileInfos.map((info) => {
++ return makeBoxes(info.file, info.hueRange, fileInfos);
++});
++
++// use the first geometry as the base
++// and add all the geometries as morphtargets
++const baseGeometry = geometries[0];
++baseGeometry.morphAttributes.position = geometries.map((geometry, ndx) => {
++ const attribute = geometry.getAttribute('position');
++ const name = `target${ndx}`;
++ attribute.name = name;
++ return attribute;
++});
++const material = new THREE.MeshBasicMaterial({
++ vertexColors: THREE.VertexColors,
++ morphTargets: true,
++});
++const mesh = new THREE.Mesh(baseGeometry, material);
++scene.add(mesh);
+
+const uiElem = document.querySelector('#ui');
+fileInfos.forEach((info) => {
+- const boxes = addBoxes(info.file, info.hueRange);
+- info.root = boxes;
+ const div = document.createElement('div');
+ info.elem = div;
+ div.textContent = info.name;
+ uiElem.appendChild(div);
+ function show() {
+ showFileInfo(fileInfos, info);
+ }
+ div.addEventListener('mouseover', show);
+ div.addEventListener('touchstart', show);
+});
+// show the first set of data
+showFileInfo(fileInfos, fileInfos[0]);
+```
+
+Above we make geometry for each data set, use the first one as the base,
+then get a `position` attribute from each geometry and add it as
+a morphtarget to the base geometry for `position`.
+
+Now we need to change how we're showing and hiding the various data sets.
+Instead of showing or hiding a mesh we need to change the influence of the
+morphtargets. For the data set we want to see we need to have an influence of 1
+and for all the ones we don't want to see to we need to have an influence of 0.
+
+We could just set them to 0 or 1 directly but if we did that we wouldn't see any
+animation, it would just snap which would be no different than what we already
+have. We could also write some custom animation code which would be easy but
+because the original webgl globe uses
+[an animation library](https://github.com/tweenjs/tween.js/) let's use the same one here.
+
+We need to include the library
+
+```html
+<script src="resources/threejs/r98/three.js"></script>
+<script src="resources/threejs/r98/js/utils/BufferGeometryUtils.js"></script>
+<script src="resources/threejs/r98/js/controls/OrbitControls.js"></script>
++<script src="resources/threejs/r98/js/libs/tween.min.js"></script>
+```
+
+And then create a `Tween` to animate the influences.
+
+```js
+// show the selected data, hide the rest
+function showFileInfo(fileInfos, fileInfo) {
+ fileInfos.forEach((info) => {
+ const visible = fileInfo === info;
+- info.root.visible = visible;
+ info.elem.className = visible ? 'selected' : '';
++ const targets = {};
++ fileInfos.forEach((info, i) => {
++ targets[i] = info === fileInfo ? 1 : 0;
++ });
++ const durationInMs = 1000;
++ new TWEEN.Tween(mesh.morphTargetInfluences)
++ .to(targets, durationInMs)
++ .start();
+ });
+ requestRenderIfNotRequested();
+}
+```
+
+We're also suppose to call `TWEEN.update` every frame inside our render loop
+but that points out a problem. "tween.js" is designed for continuous rendering
+but we are [rendering on demand](threejs-rendering-on-demand.html). We could
+switch to continuous rendering but it's sometimes nice to only render on demand
+as it well stop using the user's power when nothing is happening
+so let's see if we can make it animate on demand.
+
+We'll make a `TweenManager` to help. We'll use it to create the `Tween`s and
+track them. It will have an `update` method that will return `true`
+if we need to call it again and `false` if all the animations are finished.
+
+```js
+class TweenManger {
+ constructor() {
+ this.numTweensRunning = 0;
+ }
+ _handleComplete() {
+ --this.numTweensRunning;
+ console.assert(this.numTweensRunning >= 0);
+ }
+ createTween(targetObject) {
+ const self = this;
+ ++this.numTweensRunning;
+ let userCompleteFn = () => {};
+ // create a new tween and install our own onComplete callback
+ const tween = new TWEEN.Tween(targetObject).onComplete(function(...args) {
+ self._handleComplete();
+ userCompleteFn.call(this, ...args);
+ });
+ // replace the tween's onComplete function with our own
+ // so we can call the user's callback if they supply one.
+ tween.onComplete = (fn) => {
+ userCompleteFn = fn;
+ return tween;
+ };
+ return tween;
+ }
+ update() {
+ TWEEN.update();
+ return this.numTweensRunning > 0;
+ }
+}
+```
+
+To use it we'll create one
+
+```js
+function main() {
+ const canvas = document.querySelector('#c');
+ const renderer = new THREE.WebGLRenderer({canvas: canvas});
++ const tweenManager = new TweenManger();
+
+ ...
+```
+
+We'll use it to create our `Tween`s.
+
+```js
+// show the selected data, hide the rest
+function showFileInfo(fileInfos, fileInfo) {
+ fileInfos.forEach((info) => {
+ const visible = fileInfo === info;
+ info.elem.className = visible ? 'selected' : '';
+ const targets = {};
+ fileInfos.forEach((info, i) => {
+ targets[i] = info === fileInfo ? 1 : 0;
+ });
+ const durationInMs = 1000;
+- new TWEEN.Tween(mesh.morphTargetInfluences)
++ tweenManager.createTween(mesh.morphTargetInfluences)
+ .to(targets, durationInMs)
+ .start();
+ });
+ requestRenderIfNotRequested();
+}
+```
+
+Then we'll update our render loop to update the tweens and keep rendering
+if there are still animations running.
+
+```js
+function render() {
+ renderRequested = undefined;
+
+ if (resizeRendererToDisplaySize(renderer)) {
+ const canvas = renderer.domElement;
+ camera.aspect = canvas.clientWidth / canvas.clientHeight;
+ camera.updateProjectionMatrix();
+ }
+
++ if (tweenManager.update()) {
++ requestRenderIfNotRequested();
++ }
+
+ controls.update();
+ renderer.render(scene, camera);
+}
+render();
+```
+
+And with that we should be animating between data sets.
+
+{{{example url="../threejs-lots-of-objects-morphtargets.html" }}}
+
+That seems to work but unfortunately we lost the colors.
+
+Three.js does not support morphtarget colors and in fact this is an issue
+with the original [webgl globe](https://github.com/dataarts/webgl-globe).
+Basically it just makes colors for the first data set. Any other datasets
+use the same colors even if they are vastly different.
+
+Let's see if we can add support for morphing the colors. This might
+be brittle. The least brittle way would probably be to 100% write our own
+shaders but I think it would be useful to see how to modify the built
+in shaders.
+
+The first thing we need to do is make the code extract color a `BufferAttribute` from
+each data set's geometry.
+
+```js
+// use the first geometry as the base
+// and add all the geometries as morphtargets
+const baseGeometry = geometries[0];
+baseGeometry.morphAttributes.position = geometries.map((geometry, ndx) => {
+ const attribute = geometry.getAttribute('position');
+ const name = `target${ndx}`;
+ attribute.name = name;
+ return attribute;
+});
++const colorAttributes = geometries.map((geometry, ndx) => {
++ const attribute = geometry.getAttribute('color');
++ const name = `morphColor${ndx}`;
++ attribute.name = `color${ndx}`; // just for debugging
++ return {name, attribute};
++});
+const material = new THREE.MeshBasicMaterial({
+ vertexColors: THREE.VertexColors,
+ morphTargets: true,
+});
+```
+
+We then need to modify the three.js shader. Three.js materials have an
+`Material.onBeforeCompile` property we can assign a function. It gives us a
+chance to modify the material's shader before it is passed to WebGL. In fact the
+shader that is provided is actually a special three.js only syntax of shader
+that lists a bunch of shader *chunks* that three.js will substitute with the
+actual GLSL code for each chunk. Here is what the unmodified vertex shader code
+looks like as passed to `onBeforeCompile`.
+
+```glsl
+#include <common>
+#include <uv_pars_vertex>
+#include <uv2_pars_vertex>
+#include <envmap_pars_vertex>
+#include <color_pars_vertex>
+#include <fog_pars_vertex>
+#include <morphtarget_pars_vertex>
+#include <skinning_pars_vertex>
+#include <logdepthbuf_pars_vertex>
+#include <clipping_planes_pars_vertex>
+void main() {
+ #include <uv_vertex>
+ #include <uv2_vertex>
+ #include <color_vertex>
+ #include <skinbase_vertex>
+ #ifdef USE_ENVMAP
+ #include <beginnormal_vertex>
+ #include <morphnormal_vertex>
+ #include <skinnormal_vertex>
+ #include <defaultnormal_vertex>
+ #endif
+ #include <begin_vertex>
+ #include <morphtarget_vertex>
+ #include <skinning_vertex>
+ #include <project_vertex>
+ #include <logdepthbuf_vertex>
+ #include <worldpos_vertex>
+ #include <clipping_planes_vertex>
+ #include <envmap_vertex>
+ #include <fog_vertex>
+}
+```
+
+Digging through the various chunks we want to replace
+the [`morphtarget_pars_vertex` chunk](https://github.com/mrdoob/three.js/blob/dev/src/renderers/shaders/ShaderChunk/morphtarget_pars_vertex.glsl.js)
+the [`morphnormal_vertex` chunk](https://github.com/mrdoob/three.js/blob/dev/src/renderers/shaders/ShaderChunk/morphnormal_vertex.glsl.js)
+the [`morphtarget_vertex` chunk](https://github.com/mrdoob/three.js/blob/dev/src/renderers/shaders/ShaderChunk/morphtarget_vertex.glsl.js)
+the [`color_pars_vertex` chunk](https://github.com/mrdoob/three.js/blob/dev/src/renderers/shaders/ShaderChunk/color_pars_vertex.glsl.js)
+and the [`color_vertex` chunk](https://github.com/mrdoob/three.js/blob/dev/src/renderers/shaders/ShaderChunk/color_vertex.glsl.js)
+
+To do that we'll make a simple array of replacements and apply them in `Material.onBeforeCompile`
+
+```js
+const material = new THREE.MeshBasicMaterial({
+ vertexColors: THREE.VertexColors,
+ morphTargets: true,
+});
++const vertexShaderReplacements = [
++ {
++ from: '#include <morphtarget_pars_vertex>',
++ to: `
++ uniform float morphTargetInfluences[8];
++ `,
++ },
++ {
++ from: '#include <morphnormal_vertex>',
++ to: `
++ `,
++ },
++ {
++ from: '#include <morphtarget_vertex>',
++ to: `
++ transformed += (morphTarget0 - position) * morphTargetInfluences[0];
++ transformed += (morphTarget1 - position) * morphTargetInfluences[1];
++ transformed += (morphTarget2 - position) * morphTargetInfluences[2];
++ transformed += (morphTarget3 - position) * morphTargetInfluences[3];
++ `,
++ },
++ {
++ from: '#include <color_pars_vertex>',
++ to: `
++ varying vec3 vColor;
++ attribute vec3 morphColor0;
++ attribute vec3 morphColor1;
++ attribute vec3 morphColor2;
++ attribute vec3 morphColor3;
++ `,
++ },
++ {
++ from: '#include <color_vertex>',
++ to: `
++ vColor.xyz = morphColor0 * morphTargetInfluences[0] +
++ morphColor1 * morphTargetInfluences[1] +
++ morphColor2 * morphTargetInfluences[2] +
++ morphColor3 * morphTargetInfluences[3];
++ `,
++ },
++];
++material.onBeforeCompile = (shader) => {
++ vertexShaderReplacements.forEach((rep) => {
++ shader.vertexShader = shader.vertexShader.replace(rep.from, rep.to);
++ });
++};
+```
+
+Three.js also sorts morphtargets and applies only the highest influence.
+This lets it allow many more morphtargets as long as only a few are used at
+a time. We need to figure out how it sorted the targets and then set
+our color attributes to match. We can do this by first removing all our
+color attributes and then checking the `morphTarget` attributes and and
+seeing which `BufferAttribute` was assigned. Using the name of the
+`BufferAttribute` we can tell which corresponding color attribute needed.
+
+We do this in `Object3D.onBeforeRender` which is a property of our `Mesh`.
+Three.js will call it just before rendering giving us a chance to fix things
+up.
+
+```js
+const mesh = new THREE.Mesh(baseGeometry, material);
+scene.add(mesh);
++mesh.onBeforeRender = function(renderer, scene, camera, geometry) {
++ // remove all the color attributes
++ for (const {name} of colorAttributes) {
++ geometry.removeAttribute(name);
++ }
++
++ for (let i = 0; i < colorAttributes.length; ++i) {
++ const attrib = geometry.getAttribute(`morphTarget${i}`);
++ if (!attrib) {
++ break;
++ }
++ const ndx = parseInt(/\d+$/.exec(attrib.name)[0]);
++ const name = `morphColor${i}`;
++ geometry.addAttribute(name, colorAttributes[ndx].attribute);
++ }
++};
+```
+
+And with that we should have the colors animating as well as the boxes.
+
+{{{example url="../threejs-lots-of-objects-morphtargets-w-colors.html" }}}
+
+I hope going through this was helpful. Using morphtargets either through the
+services three.js provides or by writing custom shaders is a common technique to
+move lots of objects. As an example we could give every cube a random place in
+another target and morph from that to their first positions on the globe. That
+might be a cool way to introduce the globe.
+
+Note: We could try to just graph percent of men or percent of women or the raw
+difference but based on how we are displaying the info, cubes that grow from the
+surface of the earth, we'd prefer most cubes to be low. If we used one of these
+other comparisons most cubes would be about 1/2 their maximum height which would
+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 | 59726bae96775d035fb14bb05e902567741341dc.json | add lots of objects animated article | threejs/lessons/threejs-optimize-lots-of-objects.md | @@ -527,7 +527,8 @@ faces that are never visible.
The problem with making everything one mesh though is it's no longer easy
to move any part that was previously separate. Depending on our use case
-though there are creative solutions. We'll explore one in another article.
+though there are creative solutions. We'll explore one in
+[another article](threejs-optimize-lots-of-objects-animated.html).
<canvas id="c"></canvas>
<script src="../resources/threejs/r98/three.min.js"></script> | true |
Other | mrdoob | three.js | 59726bae96775d035fb14bb05e902567741341dc.json | add lots of objects animated article | threejs/lessons/toc.html | @@ -20,6 +20,7 @@
<li>Optimization</li>
<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>
</ul>
<li>Tips</li>
<ul> | true |
Other | mrdoob | three.js | 59726bae96775d035fb14bb05e902567741341dc.json | add lots of objects animated article | threejs/threejs-lots-of-objects-animated.html | @@ -0,0 +1,410 @@
+<!-- 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 - Lots of Objects - Animated</title>
+ <style>
+ body {
+ margin: 0;
+ color: white;
+ }
+ #c {
+ width: 100vw;
+ height: 100vh;
+ display: block;
+ }
+ #ui {
+ position: absolute;
+ left: 1em;
+ top: 1em;
+ }
+ #ui>div {
+ font-size: 20pt;
+ padding: 1em;
+ display: inline-block;
+ }
+ #ui>div.selected {
+ color: red;
+ }
+ @media (max-width: 700px) {
+ #ui>div {
+ display: block;
+ padding: .25em;
+ }
+ }
+ </style>
+ </head>
+ <body>
+ <canvas id="c"></canvas>
+ <div id="ui"></div>
+ </body>
+<script src="resources/threejs/r98/three.js"></script>
+<script src="resources/threejs/r98/js/utils/BufferGeometryUtils.js"></script>
+<script src="resources/threejs/r98/js/controls/OrbitControls.js"></script>
+<script src="resources/threejs/r98/js/libs/tween.min.js"></script>
+<script>
+'use strict';
+
+/* global THREE, TWEEN */
+
+class TweenManger {
+ constructor() {
+ this.numTweensRunning = 0;
+ }
+ _handleComplete() {
+ --this.numTweensRunning;
+ console.assert(this.numTweensRunning >= 0); /* eslint no-console: off */
+ }
+ createTween(targetObject) {
+ const self = this;
+ ++this.numTweensRunning;
+ let userCompleteFn = () => {};
+ // create a new tween and install our own onComplete callback
+ const tween = new TWEEN.Tween(targetObject).onComplete(function(...args) {
+ self._handleComplete();
+ userCompleteFn.call(this, ...args);
+ });
+ // replace the tween's onComplete function with our own
+ // so we can call the user's callback if they supply one.
+ tween.onComplete = (fn) => {
+ userCompleteFn = fn;
+ return tween;
+ };
+ return tween;
+ }
+ update() {
+ TWEEN.update();
+ return this.numTweensRunning > 0;
+ }
+}
+
+function main() {
+ const canvas = document.querySelector('#c');
+ const renderer = new THREE.WebGLRenderer({canvas: canvas});
+ const tweenManager = new TweenManger();
+
+ const fov = 60;
+ const aspect = 2; // the canvas default
+ const near = 0.1;
+ const far = 10;
+ const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
+ camera.position.z = 2.5;
+
+ const controls = new THREE.OrbitControls(camera, canvas);
+ controls.enableDamping = true;
+ controls.dampingFactor = 0.05;
+ controls.rotateSpeed = 0.1;
+ controls.enablePan = false;
+ controls.minDistance = 1.2;
+ controls.maxDistance = 4;
+ controls.update();
+
+ const scene = new THREE.Scene();
+ scene.background = new THREE.Color('black');
+
+ {
+ const loader = new THREE.TextureLoader();
+ const texture = loader.load('resources/images/world.jpg', render);
+ const geometry = new THREE.SphereBufferGeometry(1, 64, 32);
+ const material = new THREE.MeshBasicMaterial({map: texture});
+ scene.add(new THREE.Mesh(geometry, material));
+ }
+
+ async function loadFile(url) {
+ const req = await fetch(url);
+ return req.text();
+ }
+
+ function parseData(text) {
+ const data = [];
+ const settings = {data};
+ let max;
+ let min;
+ // split into lines
+ text.split('\n').forEach((line) => {
+ // split the line by whitespace
+ const parts = line.trim().split(/\s+/);
+ if (parts.length === 2) {
+ // only 2 parts, must be a key/value pair
+ settings[parts[0]] = parseFloat(parts[1]);
+ } else if (parts.length > 2) {
+ // more than 2 parts, must be data
+ const values = parts.map((v) => {
+ const value = parseFloat(v);
+ if (value === settings.NODATA_value) {
+ return undefined;
+ }
+ max = Math.max(max === undefined ? value : max, value);
+ min = Math.min(min === undefined ? value : min, value);
+ return value;
+ });
+ data.push(values);
+ }
+ });
+ return Object.assign(settings, {min, max});
+ }
+
+ function addBoxes(file, hueRange) {
+ const {min, max, data} = file;
+ const range = max - min;
+
+ // these helpers will make it easy to position the boxes
+ // We can rotate the lon helper on its Y axis to the longitude
+ const lonHelper = new THREE.Object3D();
+ scene.add(lonHelper);
+ // We rotate the latHelper on its X axis to the latitude
+ const latHelper = new THREE.Object3D();
+ lonHelper.add(latHelper);
+ // The position helper moves the object to the edge of the sphere
+ const positionHelper = new THREE.Object3D();
+ positionHelper.position.z = 1;
+ latHelper.add(positionHelper);
+ // Used to move the center of the cube so it scales from the position Z axis
+ const originHelper = new THREE.Object3D();
+ originHelper.position.z = 0.5;
+ positionHelper.add(originHelper);
+
+ const color = new THREE.Color();
+
+ const lonFudge = Math.PI * .5;
+ const latFudge = Math.PI * -0.135;
+ const geometries = [];
+ data.forEach((row, latNdx) => {
+ row.forEach((value, lonNdx) => {
+ if (value === undefined) {
+ return;
+ }
+ const amount = (value - min) / range;
+
+ const boxWidth = 1;
+ const boxHeight = 1;
+ const boxDepth = 1;
+ const geometry = new THREE.BoxBufferGeometry(boxWidth, boxHeight, boxDepth);
+
+ // adjust the helpers to point to the latitude and longitude
+ lonHelper.rotation.y = THREE.Math.degToRad(lonNdx + file.xllcorner) + lonFudge;
+ latHelper.rotation.x = THREE.Math.degToRad(latNdx + file.yllcorner) + latFudge;
+
+ // use the world matrix of the origin helper to
+ // position this geometry
+ positionHelper.scale.set(0.005, 0.005, THREE.Math.lerp(0.01, 0.5, amount));
+ originHelper.updateWorldMatrix(true, false);
+ geometry.applyMatrix(originHelper.matrixWorld);
+
+ // compute a color
+ const hue = THREE.Math.lerp(...hueRange, amount);
+ const saturation = 1;
+ const lightness = THREE.Math.lerp(0.4, 1.0, amount);
+ color.setHSL(hue, saturation, lightness);
+ // get the colors as an array of values from 0 to 255
+ const rgb = color.toArray().map(v => v * 255);
+
+ // make an array to store colors for each vertex
+ const numVerts = geometry.getAttribute('position').count;
+ const itemSize = 3; // r, g, b
+ const colors = new Uint8Array(itemSize * numVerts);
+
+ // copy the color into the colors array for each vertex
+ colors.forEach((v, ndx) => {
+ colors[ndx] = rgb[ndx % 3];
+ });
+
+ const normalized = true;
+ const colorAttrib = new THREE.BufferAttribute(colors, itemSize, normalized);
+ geometry.addAttribute('color', colorAttrib);
+
+ geometries.push(geometry);
+ });
+ });
+
+ const mergedGeometry = THREE.BufferGeometryUtils.mergeBufferGeometries(
+ geometries, false);
+ const material = new THREE.MeshBasicMaterial({
+ vertexColors: THREE.VertexColors,
+ transparent: true,
+ opacity: 0,
+ });
+ const mesh = new THREE.Mesh(mergedGeometry, material);
+ scene.add(mesh);
+ return mesh;
+ }
+
+ async function loadData(info) {
+ const text = await loadFile(info.url);
+ info.file = parseData(text);
+ }
+
+ async function loadAll() {
+ const fileInfos = [
+ {name: 'men', hueRange: [0.7, 0.3], url: 'resources/data/gpw/gpw-v4-basic-demographic-characteristics-rev10_a000_014_2010_1_deg_asc/gpw_v4_basic_demographic_characteristics_rev10_a000_014mt_2010_cntm_1_deg.asc' },
+ {name: 'women', hueRange: [0.9, 1.1], url: 'resources/data/gpw/gpw-v4-basic-demographic-characteristics-rev10_a000_014_2010_1_deg_asc/gpw_v4_basic_demographic_characteristics_rev10_a000_014ft_2010_cntm_1_deg.asc' },
+ ];
+
+ await Promise.all(fileInfos.map(loadData));
+
+ function mapValues(data, fn) {
+ return data.map((row, rowNdx) => {
+ return row.map((value, colNdx) => {
+ return fn(value, rowNdx, colNdx);
+ });
+ });
+ }
+
+ function makeDiffFile(baseFile, otherFile, compareFn) {
+ let min;
+ let max;
+ const baseData = baseFile.data;
+ const otherData = otherFile.data;
+ const data = mapValues(baseData, (base, rowNdx, colNdx) => {
+ const other = otherData[rowNdx][colNdx];
+ if (base === undefined || other === undefined) {
+ return undefined;
+ }
+ const value = compareFn(base, other);
+ min = Math.min(min === undefined ? value : min, value);
+ max = Math.max(max === undefined ? value : max, value);
+ return value;
+ });
+ // make a copy of baseFile and replace min, max, and data
+ // with the new data
+ return Object.assign({}, baseFile, {
+ min,
+ max,
+ data,
+ });
+ }
+
+ // generate a new set of data
+ {
+ const menInfo = fileInfos[0];
+ const womenInfo = fileInfos[1];
+ const menFile = menInfo.file;
+ const womenFile = womenInfo.file;
+
+ function amountGreaterThan(a, b) {
+ return Math.max(a - b, 0);
+ }
+ fileInfos.push({
+ name: '>50%men',
+ hueRange: [0.6, 0.6],
+ file: makeDiffFile(menFile, womenFile, (men, women) => {
+ return amountGreaterThan(men, women);
+ }),
+ });
+ fileInfos.push({
+ name: '>50% women',
+ hueRange: [0.0, 0.0],
+ file: makeDiffFile(womenFile, menFile, (women, men) => {
+ return amountGreaterThan(women, men);
+ }),
+ });
+ }
+
+ function showFileInfo(fileInfos, fileInfo) {
+ fileInfos.forEach((info) => {
+ const durationInMs = 1000;
+ const visible = fileInfo === info;
+// const scale = visible ? 1 : 0.1;
+ const opacity = visible ? 1 : 0;
+ info.elem.className = visible ? 'selected' : '';
+ info.root.visible = visible || info.root.material.opacity > 0;
+ tweenManager.createTween(info.root.material)
+ .to({opacity}, durationInMs)
+ .start()
+ .onComplete(() => {
+ info.root.visible = visible;
+ });
+// tweenManager.createTween(info.root.material)
+// .to({depthWrite: visible}, 0)
+// .delay(durationInMs * .5)
+// .start();
+// tweenManager.createTween(info.root)
+// .to({visible}, 0)
+// .delay(durationInMs)
+// .start();
+// tweenManager.createTween(info.root.scale)
+// .to({x: scale, y: scale, z: scale}, durationInMs)
+// .start();
+ });
+ requestRenderIfNotRequested();
+ }
+
+ const uiElem = document.querySelector('#ui');
+ fileInfos.forEach((info) => {
+ const boxes = addBoxes(info.file, info.hueRange);
+ info.root = boxes;
+// boxes.scale.set(0.1, 0.1, 0.1);
+ const div = document.createElement('div');
+ info.elem = div;
+ div.textContent = info.name;
+ uiElem.appendChild(div);
+ function show() {
+ showFileInfo(fileInfos, info);
+ }
+ div.addEventListener('mouseover', show);
+ div.addEventListener('touchstart', show);
+ });
+ // show the first set of data
+ showFileInfo(fileInfos, fileInfos[0]);
+ }
+ loadAll();
+
+ 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;
+ }
+
+ let renderRequested = false;
+
+ function render() {
+ renderRequested = undefined;
+
+ if (resizeRendererToDisplaySize(renderer)) {
+ const canvas = renderer.domElement;
+ camera.aspect = canvas.clientWidth / canvas.clientHeight;
+ camera.updateProjectionMatrix();
+ }
+
+ if (tweenManager.update()) {
+ requestRenderIfNotRequested();
+ }
+
+ controls.update();
+ renderer.render(scene, camera);
+ }
+ render();
+
+ function requestRenderIfNotRequested() {
+ if (!renderRequested) {
+ renderRequested = true;
+ requestAnimationFrame(render);
+ }
+ }
+
+ controls.addEventListener('change', requestRenderIfNotRequested);
+ window.addEventListener('resize', requestRenderIfNotRequested);
+
+ // note: this is a workaround for an OrbitControls issue
+ // in an iframe. Will remove once the issue is fixed in
+ // three.js
+ window.addEventListener('mousedown', (e) => {
+ e.preventDefault();
+ window.focus();
+ });
+ window.addEventListener('keydown', (e) => {
+ e.preventDefault();
+ });
+}
+
+main();
+</script>
+</html>
+ | true |
Other | mrdoob | three.js | 59726bae96775d035fb14bb05e902567741341dc.json | add lots of objects animated article | threejs/threejs-lots-of-objects-morphtargets-w-colors.html | @@ -0,0 +1,485 @@
+<!-- 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 - Lots of Objects - MorphTargets w/colors</title>
+ <style>
+ body {
+ margin: 0;
+ color: white;
+ }
+ #c {
+ width: 100vw;
+ height: 100vh;
+ display: block;
+ }
+ #ui {
+ position: absolute;
+ left: 1em;
+ top: 1em;
+ }
+ #ui>div {
+ font-size: 20pt;
+ padding: 1em;
+ display: inline-block;
+ }
+ #ui>div.selected {
+ color: red;
+ }
+ @media (max-width: 700px) {
+ #ui>div {
+ display: block;
+ padding: .25em;
+ }
+ }
+ </style>
+ </head>
+ <body>
+ <canvas id="c"></canvas>
+ <div id="ui"></div>
+ </body>
+<script src="resources/threejs/r98/three.js"></script>
+<script src="resources/threejs/r98/js/utils/BufferGeometryUtils.js"></script>
+<script src="resources/threejs/r98/js/controls/OrbitControls.js"></script>
+<script src="resources/threejs/r98/js/libs/tween.min.js"></script>
+<script>
+'use strict';
+
+/* global THREE, TWEEN */
+
+class TweenManger {
+ constructor() {
+ this.numTweensRunning = 0;
+ }
+ _handleComplete() {
+ --this.numTweensRunning;
+ console.assert(this.numTweensRunning >= 0); /* eslint no-console: off */
+ }
+ createTween(targetObject) {
+ const self = this;
+ ++this.numTweensRunning;
+ let userCompleteFn = () => {};
+ // create a new tween and install our own onComplete callback
+ const tween = new TWEEN.Tween(targetObject).onComplete(function(...args) {
+ self._handleComplete();
+ userCompleteFn.call(this, ...args);
+ });
+ // replace the tween's onComplete function with our own
+ // so we can call the user's callback if they supply one.
+ tween.onComplete = (fn) => {
+ userCompleteFn = fn;
+ return tween;
+ };
+ return tween;
+ }
+ update() {
+ TWEEN.update();
+ return this.numTweensRunning > 0;
+ }
+}
+
+function main() {
+ const canvas = document.querySelector('#c');
+ const renderer = new THREE.WebGLRenderer({canvas: canvas});
+ const tweenManager = new TweenManger();
+
+ const fov = 60;
+ const aspect = 2; // the canvas default
+ const near = 0.1;
+ const far = 10;
+ const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
+ camera.position.z = 2.5;
+
+ const controls = new THREE.OrbitControls(camera, canvas);
+ controls.enableDamping = true;
+ controls.dampingFactor = 0.05;
+ controls.rotateSpeed = 0.1;
+ controls.enablePan = false;
+ controls.minDistance = 1.2;
+ controls.maxDistance = 4;
+ controls.update();
+
+ const scene = new THREE.Scene();
+ scene.background = new THREE.Color('black');
+
+ {
+ const loader = new THREE.TextureLoader();
+ const texture = loader.load('resources/images/world.jpg', render);
+ const geometry = new THREE.SphereBufferGeometry(1, 64, 32);
+ const material = new THREE.MeshBasicMaterial({map: texture});
+ scene.add(new THREE.Mesh(geometry, material));
+ }
+
+ async function loadFile(url) {
+ const req = await fetch(url);
+ return req.text();
+ }
+
+ function parseData(text) {
+ const data = [];
+ const settings = {data};
+ let max;
+ let min;
+ // split into lines
+ text.split('\n').forEach((line) => {
+ // split the line by whitespace
+ const parts = line.trim().split(/\s+/);
+ if (parts.length === 2) {
+ // only 2 parts, must be a key/value pair
+ settings[parts[0]] = parseFloat(parts[1]);
+ } else if (parts.length > 2) {
+ // more than 2 parts, must be data
+ const values = parts.map((v) => {
+ const value = parseFloat(v);
+ if (value === settings.NODATA_value) {
+ return undefined;
+ }
+ max = Math.max(max === undefined ? value : max, value);
+ min = Math.min(min === undefined ? value : min, value);
+ return value;
+ });
+ data.push(values);
+ }
+ });
+ return Object.assign(settings, {min, max});
+ }
+
+ function dataMissingInAnySet(fileInfos, latNdx, lonNdx) {
+ for (const fileInfo of fileInfos) {
+ if (fileInfo.file.data[latNdx][lonNdx] === undefined) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ function makeBoxes(file, hueRange, fileInfos) {
+ const {min, max, data} = file;
+ const range = max - min;
+
+ // these helpers will make it easy to position the boxes
+ // We can rotate the lon helper on its Y axis to the longitude
+ const lonHelper = new THREE.Object3D();
+ scene.add(lonHelper);
+ // We rotate the latHelper on its X axis to the latitude
+ const latHelper = new THREE.Object3D();
+ lonHelper.add(latHelper);
+ // The position helper moves the object to the edge of the sphere
+ const positionHelper = new THREE.Object3D();
+ positionHelper.position.z = 1;
+ latHelper.add(positionHelper);
+ // Used to move the center of the cube so it scales from the position Z axis
+ const originHelper = new THREE.Object3D();
+ originHelper.position.z = 0.5;
+ positionHelper.add(originHelper);
+
+ const color = new THREE.Color();
+
+ const lonFudge = Math.PI * .5;
+ const latFudge = Math.PI * -0.135;
+ const geometries = [];
+ data.forEach((row, latNdx) => {
+ row.forEach((value, lonNdx) => {
+ if (dataMissingInAnySet(fileInfos, latNdx, lonNdx)) {
+ return;
+ }
+ const amount = (value - min) / range;
+
+ const boxWidth = 1;
+ const boxHeight = 1;
+ const boxDepth = 1;
+ const geometry = new THREE.BoxBufferGeometry(boxWidth, boxHeight, boxDepth);
+
+ // adjust the helpers to point to the latitude and longitude
+ lonHelper.rotation.y = THREE.Math.degToRad(lonNdx + file.xllcorner) + lonFudge;
+ latHelper.rotation.x = THREE.Math.degToRad(latNdx + file.yllcorner) + latFudge;
+
+ // use the world matrix of the origin helper to
+ // position this geometry
+ positionHelper.scale.set(0.005, 0.005, THREE.Math.lerp(0.01, 0.5, amount));
+ originHelper.updateWorldMatrix(true, false);
+ geometry.applyMatrix(originHelper.matrixWorld);
+
+ // compute a color
+ const hue = THREE.Math.lerp(...hueRange, amount);
+ const saturation = 1;
+ const lightness = THREE.Math.lerp(0.4, 1.0, amount);
+ color.setHSL(hue, saturation, lightness);
+ // get the colors as an array of values from 0 to 255
+ const rgb = color.toArray().map(v => v * 255);
+
+ // make an array to store colors for each vertex
+ const numVerts = geometry.getAttribute('position').count;
+ const itemSize = 3; // r, g, b
+ const colors = new Uint8Array(itemSize * numVerts);
+
+ // copy the color into the colors array for each vertex
+ colors.forEach((v, ndx) => {
+ colors[ndx] = rgb[ndx % 3];
+ });
+
+ const normalized = true;
+ const colorAttrib = new THREE.BufferAttribute(colors, itemSize, normalized);
+ geometry.addAttribute('color', colorAttrib);
+
+ geometries.push(geometry);
+ });
+ });
+
+ return THREE.BufferGeometryUtils.mergeBufferGeometries(
+ geometries, false);
+ }
+
+ async function loadData(info) {
+ const text = await loadFile(info.url);
+ info.file = parseData(text);
+ }
+
+ async function loadAll() {
+ const fileInfos = [
+ {name: 'men', hueRange: [0.7, 0.3], url: 'resources/data/gpw/gpw-v4-basic-demographic-characteristics-rev10_a000_014_2010_1_deg_asc/gpw_v4_basic_demographic_characteristics_rev10_a000_014mt_2010_cntm_1_deg.asc' },
+ {name: 'women', hueRange: [0.9, 1.1], url: 'resources/data/gpw/gpw-v4-basic-demographic-characteristics-rev10_a000_014_2010_1_deg_asc/gpw_v4_basic_demographic_characteristics_rev10_a000_014ft_2010_cntm_1_deg.asc' },
+ ];
+
+ await Promise.all(fileInfos.map(loadData));
+
+ function mapValues(data, fn) {
+ return data.map((row, rowNdx) => {
+ return row.map((value, colNdx) => {
+ return fn(value, rowNdx, colNdx);
+ });
+ });
+ }
+
+ function makeDiffFile(baseFile, otherFile, compareFn) {
+ let min;
+ let max;
+ const baseData = baseFile.data;
+ const otherData = otherFile.data;
+ const data = mapValues(baseData, (base, rowNdx, colNdx) => {
+ const other = otherData[rowNdx][colNdx];
+ if (base === undefined || other === undefined) {
+ return undefined;
+ }
+ const value = compareFn(base, other);
+ min = Math.min(min === undefined ? value : min, value);
+ max = Math.max(max === undefined ? value : max, value);
+ return value;
+ });
+ // make a copy of baseFile and replace min, max, and data
+ // with the new data
+ return Object.assign({}, baseFile, {
+ min,
+ max,
+ data,
+ });
+ }
+
+ // generate a new set of data
+ {
+ const menInfo = fileInfos[0];
+ const womenInfo = fileInfos[1];
+ const menFile = menInfo.file;
+ const womenFile = womenInfo.file;
+
+ function amountGreaterThan(a, b) {
+ return Math.max(a - b, 0);
+ }
+ fileInfos.push({
+ name: '>50%men',
+ hueRange: [0.6, 0.6],
+ file: makeDiffFile(menFile, womenFile, (men, women) => {
+ return amountGreaterThan(men, women);
+ }),
+ });
+ fileInfos.push({
+ name: '>50% women',
+ hueRange: [0.0, 0.0],
+ file: makeDiffFile(womenFile, menFile, (women, men) => {
+ return amountGreaterThan(women, men);
+ }),
+ });
+ }
+
+ // make geometry for each data set
+ const geometries = fileInfos.map((info) => {
+ return makeBoxes(info.file, info.hueRange, fileInfos);
+ });
+
+ // use the first geometry as the base
+ // and add all the geometries as morphtargets
+ const baseGeometry = geometries[0];
+ baseGeometry.morphAttributes.position = geometries.map((geometry, ndx) => {
+ const attribute = geometry.getAttribute('position');
+ const name = `target${ndx}`;
+ attribute.name = name;
+ return attribute;
+ });
+ const colorAttributes = geometries.map((geometry, ndx) => {
+ const attribute = geometry.getAttribute('color');
+ const name = `morphColor${ndx}`;
+ attribute.name = `color${ndx}`; // just for debugging
+ return {name, attribute};
+ });
+ const material = new THREE.MeshBasicMaterial({
+ vertexColors: THREE.VertexColors,
+ morphTargets: true,
+ });
+ const vertexShaderReplacements = [
+ {
+ from: '#include <morphtarget_pars_vertex>',
+ to: `
+ uniform float morphTargetInfluences[8];
+ `,
+ },
+ {
+ from: '#include <morphnormal_vertex>',
+ to: `
+ `,
+ },
+ {
+ from: '#include <morphtarget_vertex>',
+ to: `
+ transformed += (morphTarget0 - position) * morphTargetInfluences[0];
+ transformed += (morphTarget1 - position) * morphTargetInfluences[1];
+ transformed += (morphTarget2 - position) * morphTargetInfluences[2];
+ transformed += (morphTarget3 - position) * morphTargetInfluences[3];
+ `,
+ },
+ {
+ from: '#include <color_pars_vertex>',
+ to: `
+ varying vec3 vColor;
+ attribute vec3 morphColor0;
+ attribute vec3 morphColor1;
+ attribute vec3 morphColor2;
+ attribute vec3 morphColor3;
+ `,
+ },
+ {
+ from: '#include <color_vertex>',
+ to: `
+ vColor.xyz = morphColor0 * morphTargetInfluences[0] +
+ morphColor1 * morphTargetInfluences[1] +
+ morphColor2 * morphTargetInfluences[2] +
+ morphColor3 * morphTargetInfluences[3];
+ `,
+ },
+ ];
+ material.onBeforeCompile = (shader) => {
+ vertexShaderReplacements.forEach((rep) => {
+ shader.vertexShader = shader.vertexShader.replace(rep.from, rep.to);
+ });
+ };
+ const mesh = new THREE.Mesh(baseGeometry, material);
+ scene.add(mesh);
+ mesh.onBeforeRender = function(renderer, scene, camera, geometry) {
+ // remove all the color attributes
+ for (const {name} of colorAttributes) {
+ geometry.removeAttribute(name);
+ }
+
+ for (let i = 0; i < colorAttributes.length; ++i) {
+ const attrib = geometry.getAttribute(`morphTarget${i}`);
+ if (!attrib) {
+ break;
+ }
+ const ndx = parseInt(/\d+$/.exec(attrib.name)[0]);
+ const name = `morphColor${i}`;
+ geometry.addAttribute(name, colorAttributes[ndx].attribute);
+ }
+ };
+
+ // show the selected data, hide the rest
+ function showFileInfo(fileInfos, fileInfo) {
+ fileInfos.forEach((info) => {
+ const visible = fileInfo === info;
+ info.elem.className = visible ? 'selected' : '';
+ const targets = {};
+ fileInfos.forEach((info, i) => {
+ targets[i] = info === fileInfo ? 1 : 0;
+ });
+ const durationInMs = 1000;
+ tweenManager.createTween(mesh.morphTargetInfluences)
+ .to(targets, durationInMs)
+ .start();
+ });
+ requestRenderIfNotRequested();
+ }
+
+ const uiElem = document.querySelector('#ui');
+ fileInfos.forEach((info) => {
+ const div = document.createElement('div');
+ info.elem = div;
+ div.textContent = info.name;
+ uiElem.appendChild(div);
+ function show() {
+ showFileInfo(fileInfos, info);
+ }
+ div.addEventListener('mouseover', show);
+ div.addEventListener('touchstart', show);
+ });
+ // show the first set of data
+ showFileInfo(fileInfos, fileInfos[0]);
+ }
+ loadAll();
+
+ 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;
+ }
+
+ let renderRequested = false;
+
+ function render() {
+ renderRequested = undefined;
+
+ if (resizeRendererToDisplaySize(renderer)) {
+ const canvas = renderer.domElement;
+ camera.aspect = canvas.clientWidth / canvas.clientHeight;
+ camera.updateProjectionMatrix();
+ }
+
+ if (tweenManager.update()) {
+ requestRenderIfNotRequested();
+ }
+
+ controls.update();
+ renderer.render(scene, camera);
+ }
+ render();
+
+ function requestRenderIfNotRequested() {
+ if (!renderRequested) {
+ renderRequested = true;
+ requestAnimationFrame(render);
+ }
+ }
+
+ controls.addEventListener('change', requestRenderIfNotRequested);
+ window.addEventListener('resize', requestRenderIfNotRequested);
+
+ // note: this is a workaround for an OrbitControls issue
+ // in an iframe. Will remove once the issue is fixed in
+ // three.js
+ window.addEventListener('mousedown', (e) => {
+ e.preventDefault();
+ window.focus();
+ });
+ window.addEventListener('keydown', (e) => {
+ e.preventDefault();
+ });
+}
+
+main();
+</script>
+</html>
+ | true |
Other | mrdoob | three.js | 59726bae96775d035fb14bb05e902567741341dc.json | add lots of objects animated article | threejs/threejs-lots-of-objects-morphtargets.html | @@ -0,0 +1,417 @@
+<!-- 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 - Lots of Objects - Morphtargets</title>
+ <style>
+ body {
+ margin: 0;
+ color: white;
+ }
+ #c {
+ width: 100vw;
+ height: 100vh;
+ display: block;
+ }
+ #ui {
+ position: absolute;
+ left: 1em;
+ top: 1em;
+ }
+ #ui>div {
+ font-size: 20pt;
+ padding: 1em;
+ display: inline-block;
+ }
+ #ui>div.selected {
+ color: red;
+ }
+ @media (max-width: 700px) {
+ #ui>div {
+ display: block;
+ padding: .25em;
+ }
+ }
+ </style>
+ </head>
+ <body>
+ <canvas id="c"></canvas>
+ <div id="ui"></div>
+ </body>
+<script src="resources/threejs/r98/three.js"></script>
+<script src="resources/threejs/r98/js/utils/BufferGeometryUtils.js"></script>
+<script src="resources/threejs/r98/js/controls/OrbitControls.js"></script>
+<script src="resources/threejs/r98/js/libs/tween.min.js"></script>
+<script>
+'use strict';
+
+/* global THREE, TWEEN */
+
+class TweenManger {
+ constructor() {
+ this.numTweensRunning = 0;
+ }
+ _handleComplete() {
+ --this.numTweensRunning;
+ console.assert(this.numTweensRunning >= 0); /* eslint no-console: off */
+ }
+ createTween(targetObject) {
+ const self = this;
+ ++this.numTweensRunning;
+ let userCompleteFn = () => {};
+ // create a new tween and install our own onComplete callback
+ const tween = new TWEEN.Tween(targetObject).onComplete(function(...args) {
+ self._handleComplete();
+ userCompleteFn.call(this, ...args);
+ });
+ // replace the tween's onComplete function with our own
+ // so we can call the user's callback if they supply one.
+ tween.onComplete = (fn) => {
+ userCompleteFn = fn;
+ return tween;
+ };
+ return tween;
+ }
+ update() {
+ TWEEN.update();
+ return this.numTweensRunning > 0;
+ }
+}
+
+function main() {
+ const canvas = document.querySelector('#c');
+ const renderer = new THREE.WebGLRenderer({canvas: canvas});
+ const tweenManager = new TweenManger();
+
+ const fov = 60;
+ const aspect = 2; // the canvas default
+ const near = 0.1;
+ const far = 10;
+ const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
+ camera.position.z = 2.5;
+
+ const controls = new THREE.OrbitControls(camera, canvas);
+ controls.enableDamping = true;
+ controls.dampingFactor = 0.05;
+ controls.rotateSpeed = 0.1;
+ controls.enablePan = false;
+ controls.minDistance = 1.2;
+ controls.maxDistance = 4;
+ controls.update();
+
+ const scene = new THREE.Scene();
+ scene.background = new THREE.Color('black');
+
+ {
+ const loader = new THREE.TextureLoader();
+ const texture = loader.load('resources/images/world.jpg', render);
+ const geometry = new THREE.SphereBufferGeometry(1, 64, 32);
+ const material = new THREE.MeshBasicMaterial({map: texture});
+ scene.add(new THREE.Mesh(geometry, material));
+ }
+
+ async function loadFile(url) {
+ const req = await fetch(url);
+ return req.text();
+ }
+
+ function parseData(text) {
+ const data = [];
+ const settings = {data};
+ let max;
+ let min;
+ // split into lines
+ text.split('\n').forEach((line) => {
+ // split the line by whitespace
+ const parts = line.trim().split(/\s+/);
+ if (parts.length === 2) {
+ // only 2 parts, must be a key/value pair
+ settings[parts[0]] = parseFloat(parts[1]);
+ } else if (parts.length > 2) {
+ // more than 2 parts, must be data
+ const values = parts.map((v) => {
+ const value = parseFloat(v);
+ if (value === settings.NODATA_value) {
+ return undefined;
+ }
+ max = Math.max(max === undefined ? value : max, value);
+ min = Math.min(min === undefined ? value : min, value);
+ return value;
+ });
+ data.push(values);
+ }
+ });
+ return Object.assign(settings, {min, max});
+ }
+
+ function dataMissingInAnySet(fileInfos, latNdx, lonNdx) {
+ for (const fileInfo of fileInfos) {
+ if (fileInfo.file.data[latNdx][lonNdx] === undefined) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ function makeBoxes(file, hueRange, fileInfos) {
+ const {min, max, data} = file;
+ const range = max - min;
+
+ // these helpers will make it easy to position the boxes
+ // We can rotate the lon helper on its Y axis to the longitude
+ const lonHelper = new THREE.Object3D();
+ scene.add(lonHelper);
+ // We rotate the latHelper on its X axis to the latitude
+ const latHelper = new THREE.Object3D();
+ lonHelper.add(latHelper);
+ // The position helper moves the object to the edge of the sphere
+ const positionHelper = new THREE.Object3D();
+ positionHelper.position.z = 1;
+ latHelper.add(positionHelper);
+ // Used to move the center of the cube so it scales from the position Z axis
+ const originHelper = new THREE.Object3D();
+ originHelper.position.z = 0.5;
+ positionHelper.add(originHelper);
+
+ const color = new THREE.Color();
+
+ const lonFudge = Math.PI * .5;
+ const latFudge = Math.PI * -0.135;
+ const geometries = [];
+ data.forEach((row, latNdx) => {
+ row.forEach((value, lonNdx) => {
+ if (dataMissingInAnySet(fileInfos, latNdx, lonNdx)) {
+ return;
+ }
+ const amount = (value - min) / range;
+
+ const boxWidth = 1;
+ const boxHeight = 1;
+ const boxDepth = 1;
+ const geometry = new THREE.BoxBufferGeometry(boxWidth, boxHeight, boxDepth);
+
+ // adjust the helpers to point to the latitude and longitude
+ lonHelper.rotation.y = THREE.Math.degToRad(lonNdx + file.xllcorner) + lonFudge;
+ latHelper.rotation.x = THREE.Math.degToRad(latNdx + file.yllcorner) + latFudge;
+
+ // use the world matrix of the origin helper to
+ // position this geometry
+ positionHelper.scale.set(0.005, 0.005, THREE.Math.lerp(0.01, 0.5, amount));
+ originHelper.updateWorldMatrix(true, false);
+ geometry.applyMatrix(originHelper.matrixWorld);
+
+ // compute a color
+ const hue = THREE.Math.lerp(...hueRange, amount);
+ const saturation = 1;
+ const lightness = THREE.Math.lerp(0.4, 1.0, amount);
+ color.setHSL(hue, saturation, lightness);
+ // get the colors as an array of values from 0 to 255
+ const rgb = color.toArray().map(v => v * 255);
+
+ // make an array to store colors for each vertex
+ const numVerts = geometry.getAttribute('position').count;
+ const itemSize = 3; // r, g, b
+ const colors = new Uint8Array(itemSize * numVerts);
+
+ // copy the color into the colors array for each vertex
+ colors.forEach((v, ndx) => {
+ colors[ndx] = rgb[ndx % 3];
+ });
+
+ const normalized = true;
+ const colorAttrib = new THREE.BufferAttribute(colors, itemSize, normalized);
+ geometry.addAttribute('color', colorAttrib);
+
+ geometries.push(geometry);
+ });
+ });
+
+ return THREE.BufferGeometryUtils.mergeBufferGeometries(
+ geometries, false);
+ }
+
+ async function loadData(info) {
+ const text = await loadFile(info.url);
+ info.file = parseData(text);
+ }
+
+ async function loadAll() {
+ const fileInfos = [
+ {name: 'men', hueRange: [0.7, 0.3], url: 'resources/data/gpw/gpw-v4-basic-demographic-characteristics-rev10_a000_014_2010_1_deg_asc/gpw_v4_basic_demographic_characteristics_rev10_a000_014mt_2010_cntm_1_deg.asc' },
+ {name: 'women', hueRange: [0.9, 1.1], url: 'resources/data/gpw/gpw-v4-basic-demographic-characteristics-rev10_a000_014_2010_1_deg_asc/gpw_v4_basic_demographic_characteristics_rev10_a000_014ft_2010_cntm_1_deg.asc' },
+ ];
+
+ await Promise.all(fileInfos.map(loadData));
+
+ function mapValues(data, fn) {
+ return data.map((row, rowNdx) => {
+ return row.map((value, colNdx) => {
+ return fn(value, rowNdx, colNdx);
+ });
+ });
+ }
+
+ function makeDiffFile(baseFile, otherFile, compareFn) {
+ let min;
+ let max;
+ const baseData = baseFile.data;
+ const otherData = otherFile.data;
+ const data = mapValues(baseData, (base, rowNdx, colNdx) => {
+ const other = otherData[rowNdx][colNdx];
+ if (base === undefined || other === undefined) {
+ return undefined;
+ }
+ const value = compareFn(base, other);
+ min = Math.min(min === undefined ? value : min, value);
+ max = Math.max(max === undefined ? value : max, value);
+ return value;
+ });
+ // make a copy of baseFile and replace min, max, and data
+ // with the new data
+ return Object.assign({}, baseFile, {
+ min,
+ max,
+ data,
+ });
+ }
+
+ // generate a new set of data
+ {
+ const menInfo = fileInfos[0];
+ const womenInfo = fileInfos[1];
+ const menFile = menInfo.file;
+ const womenFile = womenInfo.file;
+
+ function amountGreaterThan(a, b) {
+ return Math.max(a - b, 0);
+ }
+ fileInfos.push({
+ name: '>50%men',
+ hueRange: [0.6, 0.6],
+ file: makeDiffFile(menFile, womenFile, (men, women) => {
+ return amountGreaterThan(men, women);
+ }),
+ });
+ fileInfos.push({
+ name: '>50% women',
+ hueRange: [0.0, 0.0],
+ file: makeDiffFile(womenFile, menFile, (women, men) => {
+ return amountGreaterThan(women, men);
+ }),
+ });
+ }
+
+ // make geometry for each data set
+ const geometries = fileInfos.map((info) => {
+ return makeBoxes(info.file, info.hueRange, fileInfos);
+ });
+
+ // use the first geometry as the base
+ // and add all the geometries as morphtargets
+ const baseGeometry = geometries[0];
+ baseGeometry.morphAttributes.position = geometries.map((geometry, ndx) => {
+ const attribute = geometry.getAttribute('position');
+ const name = `target${ndx}`;
+ attribute.name = name;
+ return attribute;
+ });
+ const material = new THREE.MeshBasicMaterial({
+ vertexColors: THREE.VertexColors,
+ morphTargets: true,
+ });
+ const mesh = new THREE.Mesh(baseGeometry, material);
+ scene.add(mesh);
+
+ // show the selected data, hide the rest
+ function showFileInfo(fileInfos, fileInfo) {
+ fileInfos.forEach((info) => {
+ const visible = fileInfo === info;
+ info.elem.className = visible ? 'selected' : '';
+ const targets = {};
+ fileInfos.forEach((info, i) => {
+ targets[i] = info === fileInfo ? 1 : 0;
+ });
+ const durationInMs = 1000;
+ tweenManager.createTween(mesh.morphTargetInfluences)
+ .to(targets, durationInMs)
+ .start();
+ });
+ requestRenderIfNotRequested();
+ }
+
+ const uiElem = document.querySelector('#ui');
+ fileInfos.forEach((info) => {
+ const div = document.createElement('div');
+ info.elem = div;
+ div.textContent = info.name;
+ uiElem.appendChild(div);
+ function show() {
+ showFileInfo(fileInfos, info);
+ }
+ div.addEventListener('mouseover', show);
+ div.addEventListener('touchstart', show);
+ });
+ // show the first set of data
+ showFileInfo(fileInfos, fileInfos[0]);
+ }
+ loadAll();
+
+ 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;
+ }
+
+ let renderRequested = false;
+
+ function render() {
+ renderRequested = undefined;
+
+ if (resizeRendererToDisplaySize(renderer)) {
+ const canvas = renderer.domElement;
+ camera.aspect = canvas.clientWidth / canvas.clientHeight;
+ camera.updateProjectionMatrix();
+ }
+
+ if (tweenManager.update()) {
+ requestRenderIfNotRequested();
+ }
+
+ controls.update();
+ renderer.render(scene, camera);
+ }
+ render();
+
+ function requestRenderIfNotRequested() {
+ if (!renderRequested) {
+ renderRequested = true;
+ requestAnimationFrame(render);
+ }
+ }
+
+ controls.addEventListener('change', requestRenderIfNotRequested);
+ window.addEventListener('resize', requestRenderIfNotRequested);
+
+ // note: this is a workaround for an OrbitControls issue
+ // in an iframe. Will remove once the issue is fixed in
+ // three.js
+ window.addEventListener('mousedown', (e) => {
+ e.preventDefault();
+ window.focus();
+ });
+ window.addEventListener('keydown', (e) => {
+ e.preventDefault();
+ });
+}
+
+main();
+</script>
+</html>
+ | true |
Other | mrdoob | three.js | 59726bae96775d035fb14bb05e902567741341dc.json | add lots of objects animated article | threejs/threejs-lots-of-objects-multiple-data-sets.html | @@ -0,0 +1,351 @@
+<!-- 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 - Lots of Objects - Multiple Datasets</title>
+ <style>
+ body {
+ margin: 0;
+ color: white;
+ }
+ #c {
+ width: 100vw;
+ height: 100vh;
+ display: block;
+ }
+ #ui {
+ position: absolute;
+ left: 1em;
+ top: 1em;
+ }
+ #ui>div {
+ font-size: 20pt;
+ padding: 1em;
+ display: inline-block;
+ }
+ #ui>div.selected {
+ color: red;
+ }
+ @media (max-width: 700px) {
+ #ui>div {
+ display: block;
+ padding: .25em;
+ }
+ }
+ </style>
+ </head>
+ <body>
+ <canvas id="c"></canvas>
+ <div id="ui"></div>
+ </body>
+<script src="resources/threejs/r98/three.js"></script>
+<script src="resources/threejs/r98/js/utils/BufferGeometryUtils.js"></script>
+<script src="resources/threejs/r98/js/controls/OrbitControls.js"></script>
+<script>
+'use strict';
+
+/* global THREE */
+
+function main() {
+ const canvas = document.querySelector('#c');
+ const renderer = new THREE.WebGLRenderer({canvas: canvas});
+
+ const fov = 60;
+ const aspect = 2; // the canvas default
+ const near = 0.1;
+ const far = 10;
+ const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
+ camera.position.z = 2.5;
+
+ const controls = new THREE.OrbitControls(camera, canvas);
+ controls.enableDamping = true;
+ controls.dampingFactor = 0.05;
+ controls.rotateSpeed = 0.1;
+ controls.enablePan = false;
+ controls.minDistance = 1.2;
+ controls.maxDistance = 4;
+ controls.update();
+
+ const scene = new THREE.Scene();
+ scene.background = new THREE.Color('black');
+
+ {
+ const loader = new THREE.TextureLoader();
+ const texture = loader.load('resources/images/world.jpg', render);
+ const geometry = new THREE.SphereBufferGeometry(1, 64, 32);
+ const material = new THREE.MeshBasicMaterial({map: texture});
+ scene.add(new THREE.Mesh(geometry, material));
+ }
+
+ async function loadFile(url) {
+ const req = await fetch(url);
+ return req.text();
+ }
+
+ function parseData(text) {
+ const data = [];
+ const settings = {data};
+ let max;
+ let min;
+ // split into lines
+ text.split('\n').forEach((line) => {
+ // split the line by whitespace
+ const parts = line.trim().split(/\s+/);
+ if (parts.length === 2) {
+ // only 2 parts, must be a key/value pair
+ settings[parts[0]] = parseFloat(parts[1]);
+ } else if (parts.length > 2) {
+ // more than 2 parts, must be data
+ const values = parts.map((v) => {
+ const value = parseFloat(v);
+ if (value === settings.NODATA_value) {
+ return undefined;
+ }
+ max = Math.max(max === undefined ? value : max, value);
+ min = Math.min(min === undefined ? value : min, value);
+ return value;
+ });
+ data.push(values);
+ }
+ });
+ return Object.assign(settings, {min, max});
+ }
+
+ function addBoxes(file, hueRange) {
+ const {min, max, data} = file;
+ const range = max - min;
+
+ // these helpers will make it easy to position the boxes
+ // We can rotate the lon helper on its Y axis to the longitude
+ const lonHelper = new THREE.Object3D();
+ scene.add(lonHelper);
+ // We rotate the latHelper on its X axis to the latitude
+ const latHelper = new THREE.Object3D();
+ lonHelper.add(latHelper);
+ // The position helper moves the object to the edge of the sphere
+ const positionHelper = new THREE.Object3D();
+ positionHelper.position.z = 1;
+ latHelper.add(positionHelper);
+ // Used to move the center of the cube so it scales from the position Z axis
+ const originHelper = new THREE.Object3D();
+ originHelper.position.z = 0.5;
+ positionHelper.add(originHelper);
+
+ const color = new THREE.Color();
+
+ const lonFudge = Math.PI * .5;
+ const latFudge = Math.PI * -0.135;
+ const geometries = [];
+ data.forEach((row, latNdx) => {
+ row.forEach((value, lonNdx) => {
+ if (value === undefined) {
+ return;
+ }
+ const amount = (value - min) / range;
+
+ const boxWidth = 1;
+ const boxHeight = 1;
+ const boxDepth = 1;
+ const geometry = new THREE.BoxBufferGeometry(boxWidth, boxHeight, boxDepth);
+
+ // adjust the helpers to point to the latitude and longitude
+ lonHelper.rotation.y = THREE.Math.degToRad(lonNdx + file.xllcorner) + lonFudge;
+ latHelper.rotation.x = THREE.Math.degToRad(latNdx + file.yllcorner) + latFudge;
+
+ // use the world matrix of the origin helper to
+ // position this geometry
+ positionHelper.scale.set(0.005, 0.005, THREE.Math.lerp(0.01, 0.5, amount));
+ originHelper.updateWorldMatrix(true, false);
+ geometry.applyMatrix(originHelper.matrixWorld);
+
+ // compute a color
+ const hue = THREE.Math.lerp(...hueRange, amount);
+ const saturation = 1;
+ const lightness = THREE.Math.lerp(0.4, 1.0, amount);
+ color.setHSL(hue, saturation, lightness);
+ // get the colors as an array of values from 0 to 255
+ const rgb = color.toArray().map(v => v * 255);
+
+ // make an array to store colors for each vertex
+ const numVerts = geometry.getAttribute('position').count;
+ const itemSize = 3; // r, g, b
+ const colors = new Uint8Array(itemSize * numVerts);
+
+ // copy the color into the colors array for each vertex
+ colors.forEach((v, ndx) => {
+ colors[ndx] = rgb[ndx % 3];
+ });
+
+ const normalized = true;
+ const colorAttrib = new THREE.BufferAttribute(colors, itemSize, normalized);
+ geometry.addAttribute('color', colorAttrib);
+
+ geometries.push(geometry);
+ });
+ });
+
+ const mergedGeometry = THREE.BufferGeometryUtils.mergeBufferGeometries(
+ geometries, false);
+ const material = new THREE.MeshBasicMaterial({
+ vertexColors: THREE.VertexColors,
+ });
+ const mesh = new THREE.Mesh(mergedGeometry, material);
+ scene.add(mesh);
+ return mesh;
+ }
+
+ async function loadData(info) {
+ const text = await loadFile(info.url);
+ info.file = parseData(text);
+ }
+
+ async function loadAll() {
+ const fileInfos = [
+ {name: 'men', hueRange: [0.7, 0.3], url: 'resources/data/gpw/gpw-v4-basic-demographic-characteristics-rev10_a000_014_2010_1_deg_asc/gpw_v4_basic_demographic_characteristics_rev10_a000_014mt_2010_cntm_1_deg.asc' },
+ {name: 'women', hueRange: [0.9, 1.1], url: 'resources/data/gpw/gpw-v4-basic-demographic-characteristics-rev10_a000_014_2010_1_deg_asc/gpw_v4_basic_demographic_characteristics_rev10_a000_014ft_2010_cntm_1_deg.asc' },
+ ];
+
+ await Promise.all(fileInfos.map(loadData));
+
+ function mapValues(data, fn) {
+ return data.map((row, rowNdx) => {
+ return row.map((value, colNdx) => {
+ return fn(value, rowNdx, colNdx);
+ });
+ });
+ }
+
+ function makeDiffFile(baseFile, otherFile, compareFn) {
+ let min;
+ let max;
+ const baseData = baseFile.data;
+ const otherData = otherFile.data;
+ const data = mapValues(baseData, (base, rowNdx, colNdx) => {
+ const other = otherData[rowNdx][colNdx];
+ if (base === undefined || other === undefined) {
+ return undefined;
+ }
+ const value = compareFn(base, other);
+ min = Math.min(min === undefined ? value : min, value);
+ max = Math.max(max === undefined ? value : max, value);
+ return value;
+ });
+ // make a copy of baseFile and replace min, max, and data
+ // with the new data
+ return Object.assign({}, baseFile, {
+ min,
+ max,
+ data,
+ });
+ }
+
+ // generate a new set of data
+ {
+ const menInfo = fileInfos[0];
+ const womenInfo = fileInfos[1];
+ const menFile = menInfo.file;
+ const womenFile = womenInfo.file;
+
+ function amountGreaterThan(a, b) {
+ return Math.max(a - b, 0);
+ }
+ fileInfos.push({
+ name: '>50%men',
+ hueRange: [0.6, 0.6],
+ file: makeDiffFile(menFile, womenFile, (men, women) => {
+ return amountGreaterThan(men, women);
+ }),
+ });
+ fileInfos.push({
+ name: '>50% women',
+ hueRange: [0.0, 0.0],
+ file: makeDiffFile(womenFile, menFile, (women, men) => {
+ return amountGreaterThan(women, men);
+ }),
+ });
+ }
+
+ // show the selected data, hide the rest
+ function showFileInfo(fileInfos, fileInfo) {
+ fileInfos.forEach((info) => {
+ const visible = fileInfo === info;
+ info.root.visible = visible;
+ info.elem.className = visible ? 'selected' : '';
+ });
+ requestRenderIfNotRequested();
+ }
+
+ const uiElem = document.querySelector('#ui');
+ fileInfos.forEach((info) => {
+ const boxes = addBoxes(info.file, info.hueRange);
+ info.root = boxes;
+ const div = document.createElement('div');
+ info.elem = div;
+ div.textContent = info.name;
+ uiElem.appendChild(div);
+ function show() {
+ showFileInfo(fileInfos, info);
+ }
+ div.addEventListener('mouseover', show);
+ div.addEventListener('touchstart', show);
+ });
+ // show the first set of data
+ showFileInfo(fileInfos, fileInfos[0]);
+ }
+ loadAll();
+
+ 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;
+ }
+
+ let renderRequested = false;
+
+ function render() {
+ renderRequested = undefined;
+
+ if (resizeRendererToDisplaySize(renderer)) {
+ const canvas = renderer.domElement;
+ camera.aspect = canvas.clientWidth / canvas.clientHeight;
+ camera.updateProjectionMatrix();
+ }
+
+ controls.update();
+ renderer.render(scene, camera);
+ }
+ render();
+
+ function requestRenderIfNotRequested() {
+ if (!renderRequested) {
+ renderRequested = true;
+ requestAnimationFrame(render);
+ }
+ }
+
+ controls.addEventListener('change', requestRenderIfNotRequested);
+ window.addEventListener('resize', requestRenderIfNotRequested);
+
+ // note: this is a workaround for an OrbitControls issue
+ // in an iframe. Will remove once the issue is fixed in
+ // three.js
+ window.addEventListener('mousedown', (e) => {
+ e.preventDefault();
+ window.focus();
+ });
+ window.addEventListener('keydown', (e) => {
+ e.preventDefault();
+ });
+}
+
+main();
+</script>
+</html>
+ | true |
Other | mrdoob | three.js | 374dfeedf294143ec128cd59236fdfaf6ecbace7.json | fix long words being too long on mobile | threejs/lessons/resources/lesson.css | @@ -24,6 +24,11 @@ pre.prettyprint li {
white-space: pre;
}
+/* to handle long words in paragraph */
+p code {
+ word-break: break-word;
+ white-space: normal;
+}
div[data-diagram] {
height: 100%; | false |
Other | mrdoob | three.js | 525b441f039af23429e06196b96e6097affb49d2.json | add missing example | threejs/lessons/threejs-backgrounds.md | @@ -274,4 +274,6 @@ let bgMesh;
}
```
+{{{example url="../threejs-background-equirectangularmap.html" }}}
+
Using equirectagular images requires more complicated shaders and so is slower than using cubemaps. Fortunately it's easy to convert from an equirectangular image to a cubemap. [Here's a site that will do it for you](https://matheowis.github.io/HDRI-to-CubeMap/).
\ No newline at end of file | false |
Other | mrdoob | three.js | 12024a76a25f6424b56063165841c7d6153ed265.json | handle extra whitespace | threejs/resources/editor.js | @@ -58,7 +58,7 @@ function fixSourceLinks(url, source) {
const srcRE = /(src=)"(.*?)"/g;
const linkRE = /(href=)"(.*?")/g;
const imageSrcRE = /((?:image|img)\.src = )"(.*?)"/g;
- const loaderLoadRE = /(loader\.load[a-z]*\()('|")(.*?)('|")/ig;
+ const loaderLoadRE = /(loader\.load[a-z]*\s*\(\s*)('|")(.*?)('|")/ig;
const loaderArrayLoadRE = /(loader\.load[a-z]*\(\[)([\s\S]*?)(\])/ig;
const arrayLineRE = /^(\s*["|'])([\s\S]*?)(["|']*$)/;
const urlPropRE = /(url:\s*)('|")(.*?)('|")/g; | false |
Other | mrdoob | three.js | ae614345b0c391c627827aed8c5aafcc0b5aa966.json | remove unused lines | threejs/threejs-background-cubemap.html | @@ -86,8 +86,6 @@
'resources/images/cubemaps/computer-history-museum/pos-z.jpg',
'resources/images/cubemaps/computer-history-museum/neg-z.jpg',
]);
-// texture.format = THREE.RGBFormat;
-// texture.mapping = THREE.CubeReflectionMapping;
const shader = THREE.ShaderLib.cube;
const material = new THREE.ShaderMaterial({ | false |
Other | mrdoob | three.js | 65ae4afc8fce25dae226d9a367902339dbd94403.json | handle arrays of images | threejs/resources/editor.js | @@ -58,7 +58,9 @@ function fixSourceLinks(url, source) {
const srcRE = /(src=)"(.*?)"/g;
const linkRE = /(href=)"(.*?")/g;
const imageSrcRE = /((?:image|img)\.src = )"(.*?)"/g;
- const loaderLoadRE = /(loader.load[a-z]*\()('|")(.*?)('|")/ig;
+ const loaderLoadRE = /(loader\.load[a-z]*\()('|")(.*?)('|")/ig;
+ const loaderArrayLoadRE = /(loader\.load[a-z]*\(\[)([\s\S]*?)(\])/ig;
+ const arrayLineRE = /^(\s*["|'])([\s\S]*?)(["|']*$)/;
const urlPropRE = /(url:\s*)('|")(.*?)('|")/g;
const prefix = getPrefix(url);
@@ -71,12 +73,22 @@ function fixSourceLinks(url, source) {
function makeLinkFDedQuotes(match, fn, q1, url, q2) {
return fn + q1 + addPrefix(url) + q2;
}
+ 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(loaderLoadRE, makeLinkFDedQuotes);
+ source = source.replace(loaderArrayLoadRE, makeArrayLinksFDed);
return source;
} | false |
Other | mrdoob | three.js | 325d29bad377f2c9d871160abc67578132278f88.json | fix image size | threejs/lessons/threejs-post-processing-3dlut.md | @@ -46,7 +46,7 @@ We'll also add a background image like we covered in [backgrounds and skyboxs](t
Now that we have a scene we need a 3DLUT. The simplest 3DLUT is a 2x2x2 identity LUT where *identity* means nothing happens. It's like multiplying by 1 or doing nothign, even though we're looking up colors in the LUT each color in maps to the same color out.
-<div class="threejs_center"><img src="resources/images/3dlut-standard-2x2.svg" style="width: 100px"></div>
+<div class="threejs_center"><img src="resources/images/3dlut-standard-2x2.svg" style="width: 200px"></div>
WebGL1 doesn't support 3D textures so we'll use 4x2 2D texture and treat it as a 3D texture inside a custom shader where each slice of the cube is spread out horizontally across the texture.
| false |
Other | mrdoob | three.js | 5e204c261f4dd697c0509ab903c6ef320c450618.json | fix PBR material order | threejs/lessons/resources/threejs-materials.js | @@ -76,7 +76,7 @@ import {threejsLessonUtils} from './threejs-lesson-utils.js';
const material = new MatCtor({
color,
roughness: r / (numRough - 1),
- metalness: m / (numMetal - 1),
+ metalness: 1 - m / (numMetal - 1),
});
const mesh = new THREE.Mesh(highPolySphereGeometry, material);
row.push(mesh); | true |
Other | mrdoob | three.js | 5e204c261f4dd697c0509ab903c6ef320c450618.json | fix PBR material order | threejs/lessons/threejs-materials.md | @@ -169,9 +169,8 @@ 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
-how metal the material is. Metals behave differently than non-metals. For
-some reason this setting is un-intuitive and goes from 1, not metal at all,
-to 0, most metal like.
+how metal the material is. Metals behave differently than non-metals. 0
+for non-metal and 1 for metal.
Here's a quick sample of `MeshStandardMaterial` with `roughness` from 0 to 1
across and `metalness` from 0 to 1 down. | true |
Other | mrdoob | three.js | e1450376e24f043dd0c6035363bac5b0f05b4a10.json | fix metalness description | threejs/lessons/threejs-materials.md | @@ -169,8 +169,9 @@ 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
-how metal the material is. Metals behave differently than non-metals
-and so this setting goes from 0, not metal at all, to 1, 100% metal.
+how metal the material is. Metals behave differently than non-metals. For
+some reason this setting is un-intuitive and goes from 1, not metal at all,
+to 0, most metal like.
Here's a quick sample of `MeshStandardMaterial` with `roughness` from 0 to 1
across and `metalness` from 0 to 1 down. | false |
Other | mrdoob | three.js | 4aecaeb33e8d70297d73e7bb12eea948dce99e8c.json | add id for es6 module breakout | threejs/lessons/threejs-fundamentals.md | @@ -406,7 +406,7 @@ a different color.
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">
+<div id="es6" 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> | false |
Other | mrdoob | three.js | ffcaab3189e0c50957956a15bf268c8d5215ce85.json | add another extrude example | threejs/lessons/resources/threejs-primitives.js | @@ -110,7 +110,7 @@ import {threejsLessonUtils} from './threejs-lesson-utils.js';
},
ExtrudeBufferGeometry: {
ui: {
- steps: { type: 'range', min: 1, max: 10, },
+ steps: { type: 'range', min: 1, max: 100, },
depth: { type: 'range', min: 1, max: 20, precision: 1, },
bevelEnabled: { type: 'bool', },
bevelThickness: { type: 'range', min: 0.1, max: 3, },
@@ -165,6 +165,68 @@ const extrudeSettings = {
const geometry = THREE.ExtrudeBufferGeometry(shape, extrudeSettings);
`,
+ create2(steps = 100) {
+ const outline = new THREE.Shape([
+ [ -2, -0.1], [ 2, -0.1], [ 2, 0.6],
+ [1.6, 0.6], [1.6, 0.1], [-2, 0.1],
+ ].map(p => new THREE.Vector2(...p)));
+
+ const x = -2.5;
+ const y = -5;
+ const shape = new THREE.CurvePath();
+ const points = [
+ [x + 2.5, y + 2.5],
+ [x + 2.5, y + 2.5], [x + 2, y], [x, y],
+ [x - 3, y], [x - 3, y + 3.5], [x - 3, y + 3.5],
+ [x - 3, y + 5.5], [x - 1.5, y + 7.7], [x + 2.5, y + 9.5],
+ [x + 6, y + 7.7], [x + 8, y + 4.5], [x + 8, y + 3.5],
+ [x + 8, y + 3.5], [x + 8, y], [x + 5, y],
+ [x + 3.5, y], [x + 2.5, y + 2.5], [x + 2.5, y + 2.5],
+ ].map(p => new THREE.Vector3(...p, 0));
+ for (let i = 0; i < points.length; i += 3) {
+ shape.add(new THREE.CubicBezierCurve3(...points.slice(i, i + 4)));
+ }
+
+ const extrudeSettings = {
+ steps,
+ bevelEnabled: false,
+ extrudePath: shape,
+ };
+
+ const geometry = new THREE.ExtrudeBufferGeometry(outline, extrudeSettings);
+ return geometry;
+ },
+ src2: `
+const outline = new THREE.Shape([
+ [ -2, -0.1], [ 2, -0.1], [ 2, 0.6],
+ [1.6, 0.6], [1.6, 0.1], [-2, 0.1],
+].map(p => new THREE.Vector2(...p)));
+
+const x = -2.5;
+const y = -5;
+const shape = new THREE.CurvePath();
+const points = [
+ [x + 2.5, y + 2.5],
+ [x + 2.5, y + 2.5], [x + 2, y ], [x, y ],
+ [x - 3, y ], [x - 3, y + 3.5], [x - 3, y + 3.5],
+ [x - 3, y + 5.5], [x - 1.5, y + 7.7], [x + 2.5, y + 9.5],
+ [x + 6, y + 7.7], [x + 8, y + 4.5], [x + 8, y + 3.5],
+ [x + 8, y + 3.5], [x + 8, y ], [x + 5, y ],
+ [x + 3.5, y ], [x + 2.5, y + 2.5], [x + 2.5, y + 2.5],
+].map(p => new THREE.Vector3(...p, 0));
+for (let i = 0; i < points.length; i += 3) {
+ shape.add(new THREE.CubicBezierCurve3(...points.slice(i, i + 4)));
+}
+
+const extrudeSettings = {
+ steps: 100, // ui: steps
+ bevelEnabled: false,
+ extrudePath: shape,
+};
+
+const geometry = new THREE.ExtrudeBufferGeometry(outline, extrudeSettings);
+return geometry;
+ `,
},
IcosahedronBufferGeometry: {
ui: { | false |
Other | mrdoob | three.js | fcc4337ba47069c5fef5bfa0931721aaf66c14b3.json | add deep links to primitives | threejs/lessons/resources/lesson.css | @@ -27,6 +27,10 @@ table {
.footnotes {
font-size: smaller;
}
+.deep-link {
+ position: absolute;
+ transform: translateX(-1em);
+}
pre {
background: rgb(143, 140, 140); | true |
Other | mrdoob | three.js | fcc4337ba47069c5fef5bfa0931721aaf66c14b3.json | add deep links to primitives | threejs/lessons/resources/threejs-lesson-utils.js | @@ -1,5 +1,5 @@
import * as THREE from '../../resources/threejs/r115/build/three.module.js';
-import {TrackballControls} from '../../resources/threejs/r115/examples/jsm/controls/TrackballControls.js';
+import {OrbitControls} from '../../resources/threejs/r115/examples/jsm/controls/OrbitControls.js';
export const threejsLessonUtils = {
_afterPrettifyFuncs: [],
@@ -147,10 +147,13 @@ export const threejsLessonUtils = {
targetFOVDeg = camera.fov;
if (settings.trackball !== false) {
- const controls = new TrackballControls(camera, elem);
- controls.noZoom = true;
- controls.noPan = true;
- resizeFunctions.push(controls.handleResize.bind(controls));
+ const controls = new OrbitControls(camera, elem);
+ controls.rotateSpeed = 1 / 6;
+ controls.enableZoom = false;
+ controls.enablePan = false;
+ controls.enableKeys = false;
+ elem.removeAttribute('tabIndex');
+ //resizeFunctions.push(controls.handleResize.bind(controls));
updateFunctions.push(controls.update.bind(controls));
}
| true |
Other | mrdoob | three.js | fcc4337ba47069c5fef5bfa0931721aaf66c14b3.json | add deep links to primitives | threejs/lessons/resources/threejs-primitives.js | @@ -642,16 +642,25 @@ const geometry = new THREE.WireframeGeometry(
},
};
- function addLink(parent, name) {
+ function addLink(parent, name, href) {
const a = document.createElement('a');
- a.href = `https://threejs.org/docs/#api/geometries/${name}`;
+ a.href = href || `https://threejs.org/docs/#api/geometries/${name}`;
const code = document.createElement('code');
code.textContent = name;
a.appendChild(code);
parent.appendChild(a);
return a;
}
+ function addDeepLink(parent, name, href) {
+ const a = document.createElement('a');
+ a.href = href || `https://threejs.org/docs/#api/geometries/${name}`;
+ a.textContent = name;
+ a.className = 'deep-link';
+ parent.appendChild(a);
+ return a;
+ }
+
function addElem(parent, type, className, text) {
const elem = document.createElement(type);
elem.className = className;
@@ -680,6 +689,7 @@ const geometry = new THREE.WireframeGeometry(
const elem = addDiv(pair, 'shape');
const right = addDiv(pair, 'desc');
+ addDeepLink(right, '#', `#${base.id}`);
addLink(right, name);
if (info.nonBuffer !== false) {
addElem(right, 'span', '', ', '); | true |
Other | mrdoob | three.js | fcc4337ba47069c5fef5bfa0931721aaf66c14b3.json | add deep links to primitives | threejs/lessons/ru/threejs-primitives.md | @@ -18,30 +18,30 @@ Three.js имеет большое количество примитивов. П
создание и загрузку данных из нескольких программ 3D-моделирования.
А сейчас давайте рассмотрим некоторые из доступных примитивов.
-<div data-primitive="BoxBufferGeometry">Прямоугольный параллелепипед</div>
-<div data-primitive="CircleBufferGeometry">Круг</div>
-<div data-primitive="ConeBufferGeometry">Конус</div>
-<div data-primitive="CylinderBufferGeometry">Цилиндр</div>
-<div data-primitive="DodecahedronBufferGeometry">Додекаэдр (12 граней)</div>
-<div data-primitive="ExtrudeBufferGeometry">Выдавленная 2d фигура с скругленными краями.
+<div id="Diagram-BoxBufferGeometry" data-primitive="BoxBufferGeometry">Прямоугольный параллелепипед</div>
+<div id="Diagram-CircleBufferGeometry" data-primitive="CircleBufferGeometry">Круг</div>
+<div id="Diagram-ConeBufferGeometry" data-primitive="ConeBufferGeometry">Конус</div>
+<div id="Diagram-CylinderBufferGeometry" data-primitive="CylinderBufferGeometry">Цилиндр</div>
+<div id="Diagram-DodecahedronBufferGeometry" data-primitive="DodecahedronBufferGeometry">Додекаэдр (12 граней)</div>
+<div id="Diagram-ExtrudeBufferGeometry" data-primitive="ExtrudeBufferGeometry">Выдавленная 2d фигура с скругленными краями.
Здесь мы выдавливаем форму сердца. Обратите внимание, это основа
для <code>TextBufferGeometry</code> и <code>TextGeometry</code> соответственно.</div>
-<div data-primitive="IcosahedronBufferGeometry">Икосаэдр (20 граней)</div>
-<div data-primitive="LatheBufferGeometry">Форма, созданная вращением линии. Например, лампы, кегли для боулинга, свечи, подсвечники, бокалы для вина, стаканы для питья и т. Д. Вы указываете 2-мерный силуэт в виде серии точек, а затем указываете three.js , сколько секций нужно сделать, когда он вращает силуэт вокруг оси.</div>
-<div data-primitive="OctahedronBufferGeometry">Октаэдр (8 граней)</div>
-<div data-primitive="ParametricBufferGeometry">Поверхность, созданная путем предоставления функции, которая берет 2d точку из сетки и возвращает соответствующую 3d точку.</div>
-<div data-primitive="PlaneBufferGeometry">2D плоскость</div>
-<div data-primitive="PolyhedronBufferGeometry">Берет набор треугольников с центром вокруг точки и проецирует их на сферу</div>
-<div data-primitive="RingBufferGeometry">2D диск с отверстием в центре</div>
-<div data-primitive="ShapeBufferGeometry">2D контур, который строится из треугольников</div>
-<div data-primitive="SphereBufferGeometry">Сфера</div>
-<div data-primitive="TetrahedronBufferGeometry">Тераэдр (4 грани)</div>
-<div data-primitive="TextBufferGeometry">3D-текст, сгенерированный из 3D-шрифта и строки</div>
-<div data-primitive="TorusBufferGeometry">Тор (пончик)</div>
-<div data-primitive="TorusKnotBufferGeometry">Торический узел</div>
-<div data-primitive="TubeBufferGeometry">Труба - круг проходящий путь</div>
-<div data-primitive="EdgesGeometry">Вспомогательный объект, который принимает другую геометрию в качестве входных данных и генерирует ребра, только если угол между гранями больше некоторого порога. Например, если вы посмотрите на прямоугольник сверху, он показывает линию, проходящую через каждую грань, показывая каждый треугольник, из которого состоит прямоугольник. Используя EdgesGeometry, вместо этого удаляются средние линии.</div>
-<div data-primitive="WireframeGeometry">Создает геометрию, которая содержит один отрезок (2 точки) на ребро в заданной геометрии. Без этого вы часто теряете ребра или получаете дополнительные ребра, поскольку WebGL обычно требует 2 точки на отрезок. Например, если бы у вас был только один треугольник, было бы только 3 очка. Если вы попытаетесь нарисовать его, используя материал с <code>wireframe: true</code> вы получите только одну линию. А передача этой triangle geometry в <code>WireframeGeometry</code> создаст новую геометрию, которая имеет 3 отрезка линий, используя 6 точек..</div>
+<div id="Diagram-IcosahedronBufferGeometry" data-primitive="IcosahedronBufferGeometry">Икосаэдр (20 граней)</div>
+<div id="Diagram-LatheBufferGeometry" data-primitive="LatheBufferGeometry">Форма, созданная вращением линии. Например, лампы, кегли для боулинга, свечи, подсвечники, бокалы для вина, стаканы для питья и т. Д. Вы указываете 2-мерный силуэт в виде серии точек, а затем указываете three.js , сколько секций нужно сделать, когда он вращает силуэт вокруг оси.</div>
+<div id="Diagram-OctahedronBufferGeometry" data-primitive="OctahedronBufferGeometry">Октаэдр (8 граней)</div>
+<div id="Diagram-ParametricBufferGeometry" data-primitive="ParametricBufferGeometry">Поверхность, созданная путем предоставления функции, которая берет 2d точку из сетки и возвращает соответствующую 3d точку.</div>
+<div id="Diagram-PlaneBufferGeometry" data-primitive="PlaneBufferGeometry">2D плоскость</div>
+<div id="Diagram-PolyhedronBufferGeometry" data-primitive="PolyhedronBufferGeometry">Берет набор треугольников с центром вокруг точки и проецирует их на сферу</div>
+<div id="Diagram-RingBufferGeometry" data-primitive="RingBufferGeometry">2D диск с отверстием в центре</div>
+<div id="Diagram-ShapeBufferGeometry" data-primitive="ShapeBufferGeometry">2D контур, который строится из треугольников</div>
+<div id="Diagram-SphereBufferGeometry" data-primitive="SphereBufferGeometry">Сфера</div>
+<div id="Diagram-TetrahedronBufferGeometry" data-primitive="TetrahedronBufferGeometry">Тераэдр (4 грани)</div>
+<div id="Diagram-TextBufferGeometry" data-primitive="TextBufferGeometry">3D-текст, сгенерированный из 3D-шрифта и строки</div>
+<div id="Diagram-TorusBufferGeometry" data-primitive="TorusBufferGeometry">Тор (пончик)</div>
+<div id="Diagram-TorusKnotBufferGeometry" data-primitive="TorusKnotBufferGeometry">Торический узел</div>
+<div id="Diagram-TubeBufferGeometry" data-primitive="TubeBufferGeometry">Труба - круг проходящий путь</div>
+<div id="Diagram-EdgesGeometry" data-primitive="EdgesGeometry">Вспомогательный объект, который принимает другую геометрию в качестве входных данных и генерирует ребра, только если угол между гранями больше некоторого порога. Например, если вы посмотрите на прямоугольник сверху, он показывает линию, проходящую через каждую грань, показывая каждый треугольник, из которого состоит прямоугольник. Используя EdgesGeometry, вместо этого удаляются средние линии.</div>
+<div id="Diagram-WireframeGeometry" data-primitive="WireframeGeometry">Создает геометрию, которая содержит один отрезок (2 точки) на ребро в заданной геометрии. Без этого вы часто теряете ребра или получаете дополнительные ребра, поскольку WebGL обычно требует 2 точки на отрезок. Например, если бы у вас был только один треугольник, было бы только 3 очка. Если вы попытаетесь нарисовать его, используя материал с <code>wireframe: true</code> вы получите только одну линию. А передача этой triangle geometry в <code>WireframeGeometry</code> создаст новую геометрию, которая имеет 3 отрезка линий, используя 6 точек..</div>
Вы можете заметить, что большинство из них приходят парами `Geometry`
или `BufferGeometry`. Разница между этими двумя типами заключается | true |
Other | mrdoob | three.js | fcc4337ba47069c5fef5bfa0931721aaf66c14b3.json | add deep links to primitives | threejs/lessons/threejs-primitives.md | @@ -24,30 +24,30 @@ primitives.
Many of the primitives below have defaults for some or all of their
parameters so you can use more or less depending on your needs.
-<div data-primitive="BoxBufferGeometry">A Box</div>
-<div data-primitive="CircleBufferGeometry">A flat circle</div>
-<div data-primitive="ConeBufferGeometry">A Cone</div>
-<div data-primitive="CylinderBufferGeometry">A Cylinder</div>
-<div data-primitive="DodecahedronBufferGeometry">A dodecahedron (12 sides)</div>
-<div data-primitive="ExtrudeBufferGeometry">An extruded 2d shape with optional bevelling.
+<div id="Diagram-BoxBufferGeometry" data-primitive="BoxBufferGeometry">A Box</div>
+<div id="Diagram-CircleBufferGeometry" data-primitive="CircleBufferGeometry">A flat circle</div>
+<div id="Diagram-ConeBufferGeometry" data-primitive="ConeBufferGeometry">A Cone</div>
+<div id="Diagram-CylinderBufferGeometry" data-primitive="CylinderBufferGeometry">A Cylinder</div>
+<div id="Diagram-DodecahedronBufferGeometry" data-primitive="DodecahedronBufferGeometry">A dodecahedron (12 sides)</div>
+<div id="Diagram-ExtrudeBufferGeometry" data-primitive="ExtrudeBufferGeometry">An extruded 2d shape with optional bevelling.
Here we are extruding a heart shape. Note this is the basis
for <code>TextBufferGeometry</code> and <code>TextGeometry</code> respectively.</div>
-<div data-primitive="IcosahedronBufferGeometry">An icosahedron (20 sides)</div>
-<div data-primitive="LatheBufferGeometry">A shape generated by spinning a line. Examples would be: 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="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="SphereBufferGeometry">A sphere</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 <code>EdgesGeometry</code> instead the middle lines are removed. Adjust the thresholdAngle below and you'll see the edges below that threshold disappear.</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>
+<div id="Diagram-IcosahedronBufferGeometry" data-primitive="IcosahedronBufferGeometry">An icosahedron (20 sides)</div>
+<div id="Diagram-LatheBufferGeometry" data-primitive="LatheBufferGeometry">A shape generated by spinning a line. Examples would be: 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 id="Diagram-OctahedronBufferGeometry" data-primitive="OctahedronBufferGeometry">An Octahedron (8 sides)</div>
+<div id="Diagram-ParametricBufferGeometry" 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 id="Diagram-PlaneBufferGeometry" data-primitive="PlaneBufferGeometry">A 2D plane</div>
+<div id="Diagram-PolyhedronBufferGeometry" data-primitive="PolyhedronBufferGeometry">Takes a set of triangles centered around a point and projects them onto a sphere</div>
+<div id="Diagram-RingBufferGeometry" data-primitive="RingBufferGeometry">A 2D disc with a hole in the center</div>
+<div id="Diagram-ShapeBufferGeometry" data-primitive="ShapeBufferGeometry">A 2D outline that gets triangulated</div>
+<div id="Diagram-SphereBufferGeometry" data-primitive="SphereBufferGeometry">A sphere</div>
+<div id="Diagram-TetrahedronBufferGeometry" data-primitive="TetrahedronBufferGeometry">A tetrahedron (4 sides)</div>
+<div id="Diagram-TextBufferGeometry" data-primitive="TextBufferGeometry">3D text generated from a 3D font and a string</div>
+<div id="Diagram-TorusBufferGeometry" data-primitive="TorusBufferGeometry">A torus (donut)</div>
+<div id="Diagram-TorusKnotBufferGeometry" data-primitive="TorusKnotBufferGeometry">A torus knot</div>
+<div id="Diagram-TubeBufferGeometry" data-primitive="TubeBufferGeometry">A circle traced down a path</div>
+<div id="Diagram-EdgesGeometry" 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. Adjust the thresholdAngle below and you'll see the edges below that threshold disappear.</div>
+<div id="Diagram-WireframeGeometry" 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 | true |
Other | mrdoob | three.js | 92767a1adaf103a83c9164633be0b604ca642480.json | Fix french sentences | threejs/lessons/fr/threejs-fundamentals.md | @@ -51,9 +51,9 @@ Voici ce qui est à remarquer dans le diagramme ci-dessus :
la couleur d'arrière plan et le brouillard. L'ensemble de ces objets définissent une structure
hiérarchique de type parent/enfant, arborescente, et indique où les objets apparaissent et
comment ils sont orientés. Les enfants sont positionnés et orientés par rapport à leur parent.
- Par exemple, les roues d'une voiture peuvent les enfants du châssis impliquant que le déplacement
- et l'orientation de la voiture déplace automatiquement les roues. Plus de détails sont donnés
- dans [l'article sur les graphes de scène](threejs-scenegraph.html).
+ Par exemple, les roues d'une voiture sont les enfants du châssis impliquant que si l'on déplace
+ ou oriente la voiture, les roues suiveront automatiquement son déplacement. Plus de
+ détails sont donnés dans [l'article sur les graphes de scène](threejs-scenegraph.html).
Il est à noter sur que ce diagramme `Camera` est patiellement placée dans le graphe de scène.
Cela permet d'attirer l'attention qu'en three.js, contrairement aux autres objets, une `Camera` ne doit
@@ -67,7 +67,7 @@ Voici ce qui est à remarquer dans le diagramme ci-dessus :
simultanément. Par exemple, pour dessiner deux cubes bleus à des positions différentes, nous
pouvons soit utiliser deux objets `Mesh` pour spécifier les positions et orientations de
chaque cube; soit nous pouvons utiliser seulement une géométrie unique (`Geometry`) pour décrire les
- données spatiales du cube et un matériau unique (`Material`) pour spécifier la couleur bleu.
+ données spatiales du cube et un matériau unique (`Material`) pour spécifier la couleur bleue.
Les deux objets `Mesh` peuvent ainsi référencer les mêmes objets `Geometry` et `Material`.
* Les objets `Geometry` représentent les données associées aux sommets d'une géométrie telle qu'une
@@ -78,7 +78,7 @@ Voici ce qui est à remarquer dans le diagramme ci-dessus :
* Les objets `Material` représentent les
[propriétés de surface utilisées pour dessiner la géométrie](threejs-materials.html)
- telles que le couleur à utiliser ou leur pouvoir réfléchissant (brillance). Un matériau (`Material`)
+ telles que la couleur à utiliser ou le pouvoir réfléchissant (brillance). Un matériau (`Material`)
peut aussi se référer à un ou plusieurs objets `Texture` dont l'utilité est, par exemple, de plaquer
une image sur la surface d'un géométrie.
@@ -88,7 +88,7 @@ Voici ce qui est à remarquer dans le diagramme ci-dessus :
* Les objets `Light` représentent [différentes sortent de lumière](threejs-lights.html).
-Maintenant que tout cela a été défini, nous allons présenter un exemple de type *"Hello Cube"* utilisant au
+Maintenant que tout cela a été défini, nous allons présenter un exemple de type *"Hello Cube"* utilisant un
nombre minimum d'élements three.js :
<div class="threejs_center"><img src="resources/images/threejs-1cube-no-light-scene.svg" style="width: 500px;"></div>
@@ -156,7 +156,7 @@ const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
```
`fov` est le raccourci pour `field of view` ou champ de vision.
-Dans ce cas, 75 d'ouverture verticale. Il est à noter que
+Dans ce cas, 75 degrés d'ouverture verticale. Il est à noter que
la plupart des angles dans three.js sont exprimés en radians à l'exception
de la caméra perspective.
@@ -174,7 +174,7 @@ cubes et prismes.
<img src="resources/frustum-3d.svg" width="500" class="threejs_center"/>
-L'espacement entre les plans *near* et *far* est déterminée
+L'espacement entre les plans *near* et *far* est déterminé
par le champ de vue. La largeur est fixée par le champ de vue et l'aspect.
Tout ce qui est dans le *frustum* est dessiné. Ce qui est à l'extérieur ne l'est pas.
@@ -200,7 +200,7 @@ est plus grand que les 75 degrés spécifié pour le champ vertical.
Ensuite, nous créons une `Scene`. Dans three.js, une `Scene` est la racine
du graphe de scène. Tout ce que nous voulons que three.js dessine doit être ajouté
-à la scene. Cela est davantage détaillé dans [un futur article sur le fonctionnement des scènes](threejs-scenegraph.html).
+à la scène. Cela sera davantage détaillé dans [un futur article sur le fonctionnement des scènes](threejs-scenegraph.html).
```js
const scene = new THREE.Scene();
@@ -285,7 +285,7 @@ qui dessinera notre scène.
Il est mesuré en millisecondes. Il est parfois plus facile de travailler
avec des secondes. C'est pourquoi, nous l'avons converti.
-A présent, nous appliquons sur le cube des rotations sur les axes X et Y en fonction du temps écoulé.
+A présent, nous appliquons sur le cube des rotations le long des axes X et Y en fonction du temps écoulé.
Les angles de rotation sont exprimés en [radians](https://en.wikipedia.org/wiki/Radian).
Sachant que 2 pi radians fait faire un tour complet, notre cube effectuera une rotation complète
sur chaque axe en à peu près 6.28 secondes.
@@ -297,7 +297,7 @@ A l'extérieur de la boucle, nous appelons `requestAnimationFrame` une première
{{{example url="../threejs-fundamentals-with-animation.html" }}}
-C'est un peu mieux mais il est toujours difficile de percevoir la 3d.
+C'est un peu mieux mais il est toujours difficile de percevoir la 3D.
Ce qui aiderait serait d'ajouter de la lumière.
Three.js propose plusieurs type de lumière que nous détaillerons dans
[un futur article](threejs-lights.html). Pour le moment, créons une lumière directionnelle.
@@ -337,7 +337,7 @@ Cela devrait à présent apparaître très clairement en 3D.
Pour le sport, ajoutons 2 cubes supplémentaires.
-Nous partageons la même géométrie pour chaque cube mais un matériau différente par cube
+Nous partageons la même géométrie pour chaque cube mais un matériau différent par cube
de sorte que chacun d'eux soit affecté d'une couleur différente.
Tout d'abord, nous définissons une fonction qui crée une nouveau matériau
@@ -395,7 +395,7 @@ sont partiellement en dehors du *frustum*. Ils sont également
exagérément déformés puisque le champ de vue dépeint au travers du
canevas est extrême.
-A présent, notre programme est représenté par la structure suivante :
+A présent, notre programme est schématisé par la figure suivante :
<div class="threejs_center"><img src="resources/images/threejs-3cubes-scene.svg" style="width: 610px;"></div>
| false |
Other | mrdoob | three.js | 0ea4e6c3f2655407b1670e48c9f32941330f3eb0.json | Fix french sentences for #51 | threejs/lessons/fr/langinfo.hanson | @@ -6,16 +6,14 @@
description: 'Apprendre à utiliser Three.js.',
link: 'http://threejsfundamentals.org/',
commentSectionHeader: '<div>Questions ? <a href="http://stackoverflow.com/questions/tagged/three.js">Les poser sur stackoverflow</a>.</div>\n <div>Problèmes / bug ? <a href="http://github.com/gfxfundamentals/threejsfundamentals/issues">Les reporter sur github</a>.</div>',
- missing: "Désolé, cet article n'a pas encore été traduit. [Les traductions sont bienvenue](https://github.com/gfxfundamentals/threejsfundamentals)! 😄\n\n[Voici l'article anglais originel pour le moment]({{{origLink}}}).",
+ missing: "Désolé, cet article n'a pas encore été traduit. [Les traductions sont le bienvenue](https://github.com/gfxfundamentals/threejsfundamentals)! 😄\n\n[Voici l'article anglais originel pour le moment]({{{origLink}}}).",
toc: 'Table des matières',
categoryMapping: {
'basics': 'Bases',
- 'optimization' : 'Optimisation',
+ 'optimization' : 'Optimisation',
'solutions': 'Solutions',
'tips': 'Сonseils',
'fundamentals': 'Principes de base',
'reference': 'Référence',
},
}
-
- | true |
Other | mrdoob | three.js | 0ea4e6c3f2655407b1670e48c9f32941330f3eb0.json | Fix french sentences for #51 | threejs/lessons/fr/threejs-fundamentals.md | @@ -10,7 +10,7 @@ Three.js est souvent confondu avec WebGL puisque la plupart du temps, mais
pas toujours, elle exploite WebGL pour dessiner en 3D.
[WebGL est un système très bas niveau qui ne dessine que des points, des lignes et des triangles](https://webglfundamentals.org).
Faire quelque chose d'exploitable avec WebGL requiert une certaine quantité de code
-et c'est là que three.hs intervient. Elle prend en charge des choses
+et c'est là que three.js intervient. Elle prend en charge des choses
telles que les scènes, lumières, ombres, matériaux, textures, mathématiques 3D, en bref,
tout ce que vous avez à écrire par vous même si vous aviez à utiliser WebGL directement.
@@ -19,14 +19,14 @@ se conforment au style ES6. [Consultez ici une brève liste des choses que vous
déjà censés connaître](threejs-prerequisites.html).
La plupart des navigateurs qui supportent three.js se mettent à jour automatiquement
-donc la plupart des utilisateurs devraient être capables d'exécuter ce code.
-Si vous souhaitez exécuter ce code sur un très vieux navigateur, nous vous recommandons
+donc la plupart des utilisateurs devraient être capables d'exécuter ce code.
+Si vous souhaitez exécuter ce code sur un très vieux navigateur, nous vous recommandons
un transpileur tel que [Babel](https://babel.io).
-Bien sûr, les utilisateurs exécutant de très vieux navigateurs ont probablement
+Bien sûr, les utilisateurs exécutant de très vieux navigateurs ont probablement
des machines incapables de faire tourner three.js.
Lors de l'apprentissage de la plupart des langages de programmation,
-la première tâche que les gens font est de faire afficher à l'ordinateur
+la première tâche que les gens font est de faire afficher à l'ordinateur
`"Hello World!"`. Pour la programmation 3D, l'équivalent est de faire afficher
un cube en 3D. Donc, nous commencerons par "Hello Cube!".
@@ -41,73 +41,72 @@ Voici ce qui est à remarquer dans le diagramme ci-dessus :
* Il y a un `Renderer`. C'est sans doute l'objet principal de three.js. Vous passez
une `Scene` et une `Camera` à un `Renderer` et il effectue le rendu (dessine) de la
- partie de la scene 3D qui est à l'intérieur de l'espace visible (en réalité une pyramide tronquée ou *frustum*)
+ partie de la scène 3D qui est à l'intérieur de l'espace visible (en réalité une pyramide tronquée ou *frustum*)
de la caméra dans une image 2D affichée dans un canevas (*canvas*).
* Il y a un [graphe de scène](threejs-scenegraph.html) qui est une structure arborescente,
- constituée de divers objets tel qu'un objet `Scene`, de multiple maillages (`Mesh`),
+ constituée de divers objets tel qu'un objet `Scene`, de multiple maillages (`Mesh`),
des lumières (`Light`), des groupes (`Group`), des objets 3D `Object3D` et des objets `Camera`.
- Un objet `Scene` définit la racine d'un graphe de scène et contient des propriétés telles que
+ Un objet `Scene` définit la racine d'un graphe de scène et contient des propriétés telles que
la couleur d'arrière plan et le brouillard. L'ensemble de ces objets définissent une structure
- hiérarchique de type parent/enfant, arborescente, et indique où les objets apparaissent et
+ hiérarchique de type parent/enfant, arborescente, et indique où les objets apparaissent et
comment ils sont orientés. Les enfants sont positionnés et orientés par rapport à leur parent.
- Par exemple, les roues d'une voiture peuvent les enfants d'une voiture de sorte que le déplacement
+ Par exemple, les roues d'une voiture peuvent les enfants du châssis impliquant que le déplacement
et l'orientation de la voiture déplace automatiquement les roues. Plus de détails sont donnés
dans [l'article sur les graphes de scène](threejs-scenegraph.html).
- Il est à noter que `Camera` est à moitié dans le graphe de scène sur le diagramme.
- Cela représente qu'en three.js, contrairement aux autres objets, une `Camera` ne doit
- pas forcément faire partie du graphe de scène pour être opérationnelle. Tout comme les
- autres objets, une `Camera`, comme tout enfant d'un autre objet, se déplace et s'oriente
- par rapport à son objet parent. Il y a un exemple d'inclusion de multiples objets `Camera`
- dans un graphe de scène à la fin de [l'article sur les graphes de scène](threejs-scenegraph.html).
+ Il est à noter sur que ce diagramme `Camera` est patiellement placée dans le graphe de scène.
+ Cela permet d'attirer l'attention qu'en three.js, contrairement aux autres objets, une `Camera` ne doit
+ pas forcément faire partie du graphe de scène pour être opérationnelle. Une `Camera`, de la même
+ façon que les autres objets, enfant d'un autre objet, se déplace et s'oriente par rapport à son
+ objet parent. A la fin de [l'article sur les graphes de scène](threejs-scenegraph.html), l'inclusion
+ de multiples objets `Camera` dans un unique graphe de scène est donné en exemple.
-* Les objets de type `Mesh` représentent une géométrie (`Geometry`) liée à un matériau (`Material`)
- spécifique. Les objets `Material` et `Geometry` peuvent liés à plusieurs objets `Mesh`
+* Les objets de type `Mesh` représentent une géométrie (`Geometry`) liée à un matériau (`Material`)
+ spécifique. Les objets `Material` et `Geometry` peuvent être liés à plusieurs objets `Mesh`
simultanément. Par exemple, pour dessiner deux cubes bleus à des positions différentes, nous
- pouvons utiliser deux objets `Mesh` pour spécifier les positions et orientations de
- chaque cube. Nous pouvons utiliser seulement une géométrie (`Geometry`) pour décrire les données
- spatiales du cube et seulement un matériau (`Material`) pour spécifier la couleur bleu.
+ pouvons soit utiliser deux objets `Mesh` pour spécifier les positions et orientations de
+ chaque cube; soit nous pouvons utiliser seulement une géométrie unique (`Geometry`) pour décrire les
+ données spatiales du cube et un matériau unique (`Material`) pour spécifier la couleur bleu.
Les deux objets `Mesh` peuvent ainsi référencer les mêmes objets `Geometry` et `Material`.
-* Les objets `Geometry` représentent les données associés aux sommets d'une géométrie telle qu'une
- sphère, un cube, un avion, un chien, un chat, un humain, un arbre, un bâtiment, etc...
+* Les objets `Geometry` représentent les données associées aux sommets d'une géométrie telle qu'une
+ sphère, un cube, un avion, un chien, un chat, un humain, un arbre, un bâtiment, etc...
Three.js fournit plusieurs types intégrés de [primitives géométriques](threejs-primitives.html).
- Vous pouvez aussi [créer vos propres géométries](threejs-custom-geometry.html) ou
+ Vous pouvez aussi [créer vos propres géométries](threejs-custom-geometry.html) ou
[charger des géométries à partir d'un fichier](threejs-load-obj.html).
-* Les objets `Material` représentent les
+* Les objets `Material` représentent les
[propriétés de surface utilisées pour dessiner la géométrie](threejs-materials.html)
- telles que le couleur à utiliser ou à quel point elle est brillante. Un matériau (`Material`) peut
- aussi se référer à un ou plusieurs objets `Texture` dont l'utilité est, par exemple, de plaquer
+ telles que le couleur à utiliser ou leur pouvoir réfléchissant (brillance). Un matériau (`Material`)
+ peut aussi se référer à un ou plusieurs objets `Texture` dont l'utilité est, par exemple, de plaquer
une image sur la surface d'un géométrie.
-
+
* Les objets `Texture` représentent généralement des images soit [chargées de fichiers image](threejs-textures.html),
- soit [générées par le biais d'un canevas](threejs-canvas-textures.html) ou
+ soit [générées par le biais d'un canevas](threejs-canvas-textures.html) ou
[résultent du rendu d'une autre scène](threejs-rendertargets.html).
* Les objets `Light` représentent [différentes sortent de lumière](threejs-lights.html).
-Maintenant que tout cela est présente, nous allons mettre en place le plus petit *"Hello Cube"* possible
-qui ressemble à ceci :
+Maintenant que tout cela a été défini, nous allons présenter un exemple de type *"Hello Cube"* utilisant au
+nombre minimum d'élements three.js :
<div class="threejs_center"><img src="resources/images/threejs-1cube-no-light-scene.svg" style="width: 500px;"></div>
-Tout d'abord, chargeons three.js
+Tout d'abord, chargeons three.js :
```html
<script type="module">
import * as THREE from './resources/threejs/r114/build/three.module.js';
</script>
```
-Il est important d'écrire `type="module"` dans la balise script.
-Cela nous autorise l'utilisation du mot-clé `import` pour charger three.js.
-Il y a d'autres manières de le réaliser, mais depuis la version 106 (r106),
+Il est important d'écrire `type="module"` dans la balise script.
+Cela nous autorise l'utilisation du mot-clé `import` pour charger three.js.
+Il y a d'autres manières de le réaliser, mais depuis la version 106 (r106),
l'utilisation des modules est recommandée. Ils ont l'avantage de pouvoir
-facilement importer les autres modules dont ils ont besoin. Cela nous
-épargne d'avoir à charger les scripts supplémentaires dont ils dépendent
-à la main.
+facilement importer les autres modules dont ils ont besoin. Cela nous
+épargne d'avoir à charger à la main les scripts supplémentaires dont ils dépendent.
Ensuite, nous avons besoin d'une balise `<canvas>` :
@@ -138,13 +137,13 @@ dans le canevas. Par le passé, il y a eu aussi d'autre *renderers* tels que
`WebGL2Renderer` ou `WebGPURenderer`. Pour le moment, il y a un `WebGLRenderer`
qui utiliser WebGL pour effectuer une rendu 3D dans le canevas.
-Notez qu'il y a quelques détails ésotériques ici. Si vous ne passez pas un
-canevas à three.js, il va en créer un pour vous mais vous aurez à l'ajouter
+Notez qu'il y a quelques détails ésotériques ici. Si vous ne passez pas un
+canevas à three.js, il va en créer un pour vous mais vous aurez à l'ajouter
au document. Où l'ajouter peut dépendre de contexte d'utilisation et vous aurez
à modifier votre code en conséquence. Passer un canevas à three.js nous apparaît donc
-plus flexible. Nous pouvons mettre le canevas n'importe où et le code le retrouveras.
-Dans le cas contraire, nous aurons à coder où insérer le canevas, ce qui amènera
-probablement à changer le code si le contexte d'utilisation change.
+plus flexible. Nous pouvons mettre le canevas n'importe où et le code le retrouvera.
+Dans le cas contraire, nous aurons à coder où insérer le canevas, ce qui amènera
+probablement à changer le code si le contexte d'utilisation change.
Ensuite, nous avons besoin d'une caméra. Nous créerons une `PerspectiveCamera`.
@@ -157,31 +156,31 @@ const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
```
`fov` est le raccourci pour `field of view` ou champ de vision.
-Dans ce cas, 75 degrés est dans la direction verticale. Il est à noter que
-la plupart des angles dans three.js sont exprimés en radians à l'exception
-de la caméra perspective.
+Dans ce cas, 75 d'ouverture verticale. Il est à noter que
+la plupart des angles dans three.js sont exprimés en radians à l'exception
+de la caméra perspective.
`aspect` est l'aspect de l'affichage dans le canevas. Cela sera détaillé
[dans un autre article](threejs-responsive.html). Toutefois, par défaut,
un canevas est de taille 300x150 pixels ce qui lui confère l'aspect 300/150 ou 2.
-`near` et `far` délimitent la portion de l'espace devant la caméra dont
+`near` et `far` délimitent la portion de l'espace devant la caméra dont
le rendu est effectué. Tout ce qui est avant ou après est découpé (*clipped*),
donc non dessiné.
-Ces 4 paramètres définissent une pyramide tronquée ou *"frustum"*.
+Ces 4 paramètres définissent une pyramide tronquée ou *"frustum"*.
En d'autres termes, il s'agit d'une autre forme 3D à l'instar des sphères,
cubes et prismes.
<img src="resources/frustum-3d.svg" width="500" class="threejs_center"/>
-La hauteur de l'espace entre les plans *near* et *far* est déterminée
+L'espacement entre les plans *near* et *far* est déterminée
par le champ de vue. La largeur est fixée par le champ de vue et l'aspect.
Tout ce qui est dans le *frustum* est dessiné. Ce qui est à l'extérieur ne l'est pas.
La caméra regarde par défaut suivant l'axe -Z, +Y pointant le haut.
-Nous mettons notre cube à l'origine donc nous devons déplacer la caméra de l'origine légèrement vers son arrière
+Nous mettons notre cube à l'origine donc nous devons déplacer la caméra de l'origine légèrement vers son arrière
pour voir quelque chose.
```js
@@ -192,14 +191,14 @@ Voici ce que nous voudrions voir :
<img src="resources/scene-down.svg" width="500" class="threejs_center"/>
-Dans le schéma ci-dessous, nous pouvons voir que notre caméra est placée
-en `z = 2`. Elle regarde le long de la direction -Z.
+Dans le schéma ci-dessous, nous pouvons voir que notre caméra est placée
+en `z = 2`. Elle regarde le long de la direction -Z.
Notre *frustum* démarre à 0.1 unités de la caméra et s'étend jusqu'à 5 unités devant elle.
Comme le schéma est vu du haut, le champ de vue est affecté par l'aspect.
Notre canvas est deux fois plus large que haut donc le champ de vue horizontal
est plus grand que les 75 degrés spécifié pour le champ vertical.
-Ensuite, nous créons une `Scene`. Dans three.js, une `Scene` est la racine
+Ensuite, nous créons une `Scene`. Dans three.js, une `Scene` est la racine
du graphe de scène. Tout ce que nous voulons que three.js dessine doit être ajouté
à la scene. Cela est davantage détaillé dans [un futur article sur le fonctionnement des scènes](threejs-scenegraph.html).
@@ -208,7 +207,7 @@ const scene = new THREE.Scene();
```
Ensuite nous créons une géométrie de type `BoxGeometry` qui contient les données pour un parallélépipède.
-Quasimment tout ce que nous souhaitons afficher avec Three.js nécessite une
+Quasiment tout ce que nous souhaitons afficher avec Three.js nécessite une
géométrie qui définit les sommets qui composent nos objets 3D.
```js
@@ -224,7 +223,7 @@ Elle peut être spécifiée au format hexadécimal (6 chiffres) du standard CSS.
const material = new THREE.MeshBasicMaterial({color: 0x44aa88});
```
-Nous créons ensuite un maillage (`Mesh`). Dans three.js, il représente la combinaison
+Nous créons ensuite un maillage (`Mesh`). Dans three.js, il représente la combinaison
d'une `Geometry` (forme de l'objet) et d'un matériau (`Material` - aspect
d'un objet, brillant ou plat, quelle couleur, quelle texture appliquer, etc.)
ainsi que la position, l'orientation et l'échelle de l'objet dans la scène.
@@ -250,13 +249,13 @@ Voici un exemple fonctionnel :
{{{example url="../threejs-fundamentals.html" }}}
-Il est difficile de déterminer s'il s'agit d'un cube 3D puisque nous
-l'observons suivant l'axe -Z auquel le cube est lui même aligné.
+Il est difficile de déterminer s'il s'agit d'un cube 3D puisque nous
+l'observons suivant l'axe -Z auquel le cube est lui même aligné.
Nous n'en voyons donc qu'une face.
-Nous nous proposons de l'animer en le faisant tourner et cela fera clairement
-apparaître qu'il est dessiné en 3D. Pour l'animation, nous effectuerons son rendu
-dans une boucle de rendu en utilisant
+Nous nous proposons de l'animer en le faisant tourner et cela fera clairement
+apparaître qu'il est dessiné en 3D. Pour l'animation, nous effectuerons son rendu
+dans une boucle de rendu en utilisant
[`requestAnimationFrame`](https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame).
Voici notre boucle :
@@ -278,29 +277,29 @@ requestAnimationFrame(render);
`requestAnimationFrame` est une requête auprès du navigateur dans le cas où vous
voulez animer quelque chose. Nous lui passons une fonction à appeler.
Dans notre cas, c'est la fonction `render`. Le navigateur appellera cette fonction
-et, si nous mettons à jour l'affichage de la page, le navigateur refera le rendu
-de la page. Dans notre cas, nous appelons la fonction `renderer.render` de three
+et, si nous mettons à jour l'affichage de la page, le navigateur refera le rendu
+de la page. Dans notre cas, nous appelons la fonction `renderer.render` de three
qui dessinera notre scène.
-`requestAnimationFrame` passe à notre fonction le temps depuis lequel la page est chargée.
-Il est mesuré en millisecondes. Il est parfois plus facile de travailler
+`requestAnimationFrame` passe à notre fonction le temps depuis lequel la page est chargée.
+Il est mesuré en millisecondes. Il est parfois plus facile de travailler
avec des secondes. C'est pourquoi, nous l'avons converti.
-Nous affectons à présent le temps écoulé aux rotations X et Y du cube.
-Elle sont exprimées en [radians](https://en.wikipedia.org/wiki/Radian).
-2 pi radians font un tour complet donc notre cube effectue une rotation complète
+A présent, nous appliquons sur le cube des rotations sur les axes X et Y en fonction du temps écoulé.
+Les angles de rotation sont exprimés en [radians](https://en.wikipedia.org/wiki/Radian).
+Sachant que 2 pi radians fait faire un tour complet, notre cube effectuera une rotation complète
sur chaque axe en à peu près 6.28 secondes.
-Nous effectuons alors le rendu de la scène et
+Nous effectuons alors le rendu de la scène et
demandons une autre image pour l'animation afin de poursuivre notre boucle.
A l'extérieur de la boucle, nous appelons `requestAnimationFrame` une première fois pour activer la boucle.
{{{example url="../threejs-fundamentals-with-animation.html" }}}
-C'est un peu mieux mais il est toujours difficile de percevoir la 3d.
+C'est un peu mieux mais il est toujours difficile de percevoir la 3d.
Ce qui aiderait serait d'ajouter de la lumière.
-Three.js propose plusieurs type de lumière que nous détaillerons dans
+Three.js propose plusieurs type de lumière que nous détaillerons dans
[un futur article](threejs-lights.html). Pour le moment, créons une lumière directionnelle.
```js
@@ -313,13 +312,13 @@ Three.js propose plusieurs type de lumière que nous détaillerons dans
}
```
-Les lumières directionnelles ont une position et une cible. Les deux sont par défaut en 0, 0, 0.
-Dans notre cas, nous positionnons la lumière en -1, 2, 4, de manière à ce qu'elle soit légèrement
+Les lumières directionnelles ont une position et une cible. Les deux sont par défaut en 0, 0, 0.
+Dans notre cas, nous positionnons la lumière en -1, 2, 4, de manière à ce qu'elle soit légèrement
sur la gauche, au dessus et derrière notre caméra. La cible est toujours 0, 0, 0 donc elle va
éclairer vers l'origine.
-Nous avons également besoin de changer le matériau. `MeshBasicMaterial` ne réagit pas à la
-lumière. Nous le changerons par un `MeshPhongMaterial` qui y réagit.
+Nous avons également besoin de changer le matériau car `MeshBasicMaterial` ne s'applique pas aux
+lumières. Nous le remplaçons par un `MeshPhongMaterial` qui est affecté par les sources lumineuses.
```js
-const material = new THREE.MeshBasicMaterial({color: 0x44aa88}); // cyan
@@ -338,10 +337,10 @@ Cela devrait à présent apparaître très clairement en 3D.
Pour le sport, ajoutons 2 cubes supplémentaires.
-Nous partagerons la même géométrie pour chaque cube mais un matériau différent
-de sorte que chacun soit d'une couleur différente.
+Nous partageons la même géométrie pour chaque cube mais un matériau différente par cube
+de sorte que chacun d'eux soit affecté d'une couleur différente.
-Tout d'abord, nous définissons une fonction qui créé un nouveau matériau
+Tout d'abord, nous définissons une fonction qui crée une nouveau matériau
avec la couleur spécifiée. Ensuite, elle créé un maillage à partir de la
géométrie spécifiée, l'ajoute à la scène et change sa position en X.
@@ -358,7 +357,7 @@ function makeInstance(geometry, color, x) {
}
```
-Ensuite, nous l'appelerons à 3 reprises avec 3 différentes couleurs
+Ensuite, nous l'appellerons à 3 reprises avec 3 différentes couleurs
et positions en X, puis nous conserverons ces instances de `Mesh` dans un tableau.
```js
@@ -369,8 +368,8 @@ const cubes = [
];
```
-Enfin, nous ferons tourner ces 3 cubes dans notre fonction de rendu.
-Nous calculons une rotation légèrement différente pour chacun.
+Enfin, nous ferons tourner ces 3 cubes dans notre fonction de rendu.
+Nous calculons une rotation légèrement différente pour chacun d'eux.
```js
function render(time) {
@@ -390,29 +389,29 @@ et voilà le résultat.
{{{example url="../threejs-fundamentals-3-cubes.html" }}}
-Si nous le comparons au schéma précédent, nous constatons qu'il
-est conforme à nos attentes. Les cubes en X = -2 et X = +2
-sont partiellement en dehors du *frustum*. Ils sont également
-exagérément déformés puisque le champ de vue dépeint au travers du
+Si nous le comparons au schéma précédent, nous constatons qu'il
+est conforme à nos attentes. Les cubes en X = -2 et X = +2
+sont partiellement en dehors du *frustum*. Ils sont également
+exagérément déformés puisque le champ de vue dépeint au travers du
canevas est extrême.
-Notre programme a à présent cette structure :
+A présent, notre programme est représenté par la structure suivante :
<div class="threejs_center"><img src="resources/images/threejs-3cubes-scene.svg" style="width: 610px;"></div>
-Comme nous pouvons le constater, nous avons 3 objets de type `Mesh`, chacun référençant
+Comme nous pouvons le constater, nous avons 3 objets de type `Mesh`, chacun référençant
la même `BoxGeometry`. Chaque `Mesh` référence également un `MeshPhongMaterial` unique
de sorte que chaque cube possède une couleur différente.
-Nous espérons que cette courte introduction vous aide à débuter.
+Nous espérons que cette courte introduction vous aide à débuter.
[La prochaine étape consiste à rendre notre code réactif et donc adaptable à de multiples situations](threejs-responsive.html).
<div class="threejs_bottombar">
<h3>es6 modules, three.js et structure de dossiers</h3>
<p>Depuis la version 106 (r106), l'utilisation de three.js privilégie les <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import">modules es6</a>.</p>
<p>
Ils sont chargés via le mot-clé <code>import</code> dans un script ou en ligne
-par le biais d'une balise <code><script type="module"></code>. Voici un exemple d'utilisation des deux
+par le biais d'une balise <code><script type="module"></code>. Voici un exemple d'utilisation avec les deux :
</p>
<pre class=prettyprint>
<script type="module">
@@ -423,15 +422,15 @@ import * as THREE from './resources/threejs/r114/build/three.module.js';
</script>
</pre>
<p>
-Les chemins doivent être absolus ou relatifs. Les deuxièmes commencent toujours par
-<code>./</code> ou <code>../</code>,
+Les chemins doivent être absolus ou relatifs. Un chemin relatif commencent toujours par
+<code>./</code> ou par <code>../</code>,
ce qui est différent des autres balises telles que <code><img></code> et <code><a></code>.
</p>
<p>
-Les références à un même script ne seront chargées qu'une seule fois à partir du
-moment où leur chemin absolu est exactement identique. Pour three.js, cela veut
+Les références à un même script ne seront chargées qu'une seule fois à partir du
+moment où leur chemin absolu est exactement identique. Pour three.js, cela veut
dire qu'il est nécessaire de mettre toutes les bibliothèques d'exemples dans une
-structure correcte pour les dossiers
+structure correcte pour les dossiers :
</p>
<pre class="dos">
unDossier
@@ -460,14 +459,14 @@ unDossier
<p>
La raison nécessitant cette structuration des dossiers est parce que les scripts
des exemples tels que <a href="https://github.com/mrdoob/three.js/blob/master/examples/jsm/controls/OrbitControls.js"><code>OrbitControls.js</code></a>
-ont des chemins relatifs tels que
+ont des chemins relatifs tels que :
</p>
<pre class="prettyprint">
import * as THREE from '../../../build/three.module.js';
</pre>
<p>
-Utiliser la même structure permet de s'assurer lors de l'import à la fois de
-three et d'une autre bibliothèque des exemples qu'ils référenceront le même fichier
+Utiliser la même structure permet de s'assurer, lors de l'importation de
+three et d'une autre bibliothèque d'exemple, qu'ils référenceront le même fichier
three.module.js.
</p>
<pre class="prettyprint">
@@ -480,14 +479,15 @@ import {OrbitControls} from './someFolder/examples/jsm/controls/OrbitControls.js
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>
-<p>Si vous préférez la vieille manière<code><script src="path/to/three.js"></script></code>,
+<p>Si vous préférez la vieille manière <code><script src="path/to/three.js"></script></code>,
vous pouvez consulter <a href="https://r105.threejsfundamentals.org">une version plus ancienne de ce site</a>.
-Three.js a pour politique de ne pas s'embarrasser avec la rétrocompatibilité.
-Cela suppose que vous utilisiez une version spécifique de la bibliothèque que vous télécharger et
-incorporez à votre projet. Lors de la mise à jour vers une nouvelle version, vous pouvez lire le<a href="https://github.com/mrdoob/three.js/wiki/Migration-Guide">guide de migration</a>
+Three.js a pour politique de ne pas s'embarrasser avec la rétro compatibilité.
+Cela suppose que vous utilisez une version spécifique de la bibliothèque que vous aurez téléchargé et
+incorporé à votre projet. Lors de la mise à jour vers une nouvelle version de three.js,
+vous pouvez lire le <a href="https://github.com/mrdoob/three.js/wiki/Migration-Guide">guide de migration</a>
pour voir ce que vous avez à changer. Cela nécessiterait beaucoup de travail de maintenir
-à la fois une version de ce site avec les modules es6 et une autre avec le script global.
-Aussi, nous n'utiliserons que les modules es6. Comme dit par ailleurs,
-pour le support des anciens navigateurs, vous pouvez utiliser un
+à la fois une version de ce site avec les modules es6 et une autre avec le script global.
+Pour cela, nous n'utiliserons que les modules es6. Comme dit par ailleurs,
+pour le support des anciens navigateurs, vous pouvez utiliser un
<a href="https://babeljs.io">transpileur</a>.</p>
-</div>
\ No newline at end of file
+</div> | true |
Other | mrdoob | three.js | 0ea4e6c3f2655407b1670e48c9f32941330f3eb0.json | Fix french sentences for #51 | threejs/lessons/fr/threejs-prerequisites.md | @@ -7,21 +7,21 @@ Ils supposent que :
* vous savez programmer en Javascript ;
* vous savez ce que c'est qu'un *DOM*, comment écrire du HTML, ainsi que créer des éléments *DOM*
en Javascript ;
- * vous savez exploiter les
-[modules es6](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import)
-que ce soit via le mot clé import ou via les balises `<script type="module">` ;
- * vous avez des connaissances en CSS et savez ce que sont
-[les sélecteurs CSS](https://developer.mozilla.org/en-US/docs/Learn/CSS/Introduction_to_CSS/Selectors).
+ * vous savez exploiter les
+[modules es6](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import)
+que ce soit via le mot clef import ou via les balises `<script type="module">` ;
+ * vous avez des connaissances en CSS et savez ce que sont
+[les sélecteurs CSS](https://developer.mozilla.org/en-US/docs/Learn/CSS/Introduction_to_CSS/Selectors).
* vous connaissez ES5, ES6, voire ES7 ;
- * vous savez que le navigateur n'exécute que du Javascript de façon évènementiel via des fonctions de rappel (*callbacks*) ;
+ * vous savez que le navigateur n'exécute que du Javascript de façon événementiel via des fonctions de rappel (*callbacks*) ;
* vous savez ce qu'est une fonction de clôture (*closure*).
Voici ci-dessous quelques rappels et notes.
## Modules es6
Les modules es6 peuvent être chargé via le mot-clé `import` dans un script
-ou en ligne via une balise `<script type="module">`. Voici un exemple des deux
+ou en ligne via une balise `<script type="module">`. Voici un exemple des deux
```html
<script type="module">
@@ -39,14 +39,14 @@ Davantage de détails se trouvent à la fin de [cet article](threejs-fundamental
## `document.querySelector` et `document.querySelectorAll`
-Vous pouvez utiliser `document.querySelector` pour sélectionner le
+Vous pouvez utiliser `document.querySelector` pour sélectionner le
premier élément qui correspond à un sélecteur CSS.
`document.querySelectorAll` retourne tous les éléments qui correspondent
à un sélecteur CSS.
## `onbody` n'est pas nécessaire
-Beaucoup de pages vielles d'il y a 20 ans utilisent
+Beaucoup de pages vielles d'il y a 20 ans utilisent
<body onload="somefunction()">
@@ -89,7 +89,7 @@ Cette fonction se *clôt* sur la variable `foo`. Voici [davantage d'information]
## Comprendre le fonctionnement de `this`
-`this` est une variable passée automatiquement aux fonctions tout comme les arguments y sont passé.
+`this` est une variable passée automatiquement aux fonctions tout comme les arguments y sont passés.
Une explication simple est que quand vous appelez une fonction directement comme ceci :
somefunction(a, b, c);
@@ -109,7 +109,7 @@ Ce fonctionnement peut dérouter lorsqu'il est combiné avec les fonctions de ra
Ceci ne fonctionne pas comme s'y attendrait une personne inexpérimentée parce que, quand
`loader.load` appelle la fonction de rappel, il n'utilise pas l'opérateur `.` et donc
par défaut `this` est null (à moins que loader le fixe arbitrairement à une valeur).
-Si vous souhaitez que `this` se rapporte à `someobject` quand la fonction de rappelle
+Si vous souhaitez que `this` se rapporte à `someobject` quand la fonction de rappelle
est activée, vous devez dire à Javascript de le lier à la fonction.
const callback = someobject.somefunction.bind(someobject);
@@ -122,15 +122,15 @@ est activée, vous devez dire à Javascript de le lier à la fonction.
### `var` est déprécié. Privilégiez l'usage de `const` et/ou `let`
Il n'y a **PLUS AUCUNE** raison d'utiliser `var`. L'utiliser est dorénavant considéré
-comme une mauvaise pratique. Utilisez `const` si la variable ne sera jamais réaffectée,
+comme une mauvaise pratique. Utilisez `const` si la variable n'est jamais réaffectée,
ce qui se passe dans la majorité des cas. Utilisez `let` dans le cas où la valeur change.
Cela aidera à éviter beaucoup de bogues.
### Utilisez `for(elem of collection)` jamais `for(elem in collection)`
`for of` est récent, `for in` est ancien. `for in` avait des problèmes résolus par `for of`
-Voici un exemple où vous pouvez itérer au travers de toutes les paires clé/valeur
+Voici un exemple où vous pouvez itérer au travers de toutes les paires clef/valeur
d'un objet :
```js
@@ -141,7 +141,7 @@ for (const [key, value] of Object.entries(someObject)) {
### Utilisez `forEach`, `map`, et `filter` quand c'est utile
-Les fonctions [`forEach`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach),
+Les fonctions [`forEach`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach),
[`map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map), et
[`filter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) ont
été ajoutées aux tableaux (*arrays*) et sont utilisés de manière assez intensives en JavaScript moderne.
@@ -161,7 +161,7 @@ nouveau code
### Utilisez les raccourcis pour la déclaration des objets
-ancien code
+ancien code :
```js
const width = 300;
@@ -175,7 +175,7 @@ ancien code
};
```
-nouveau code
+nouveau code :
```js
const width = 300;
@@ -191,7 +191,7 @@ nouveau code
### Utilisez l'opérateur d'expansion `...`
-L'opérateur d'expansion a de multiples usages. Voici un exemple
+L'opérateur d'expansion a de multiples usages. Voici un exemple :
```js
function log(className, ...args) {
@@ -202,7 +202,7 @@ L'opérateur d'expansion a de multiples usages. Voici un exemple
}
```
-et un autre exemple
+et un autre exemple :
```js
const position = [1, 2, 3];
@@ -211,9 +211,9 @@ somemesh.position.set(...position);
### Utilisez `class`
-La syntaxe pour créer des objets au comportement de classe avant ES5
-n'était connu que des programmeurs chevronnés. Depuis ES5, vous pouvez
-à présent [utiliser le mot-clé `class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes)
+La syntaxe pour créer des objets au comportement de classe avant ES5
+n'était connue que des programmeurs chevronnés. Depuis ES5, vous pouvez
+à présent [utiliser le mot-clef `class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes)
qui est plus proche du style C++/C#/Java.
### Comprendre les accesseurs (*getters* et *setters*)
@@ -250,13 +250,13 @@ const foo = (function(args) {/* code */}).bind(this));
Les promesses (*promises*) aident à l'utilisation de code asynchrone.
Async/await aident à l'utilisation des promesses.
-Cela nécessiterait des développements trop long à détailler ici.
+Cela nécessiterait des développements trop long à détailler ici.
Toutefois, vous pouvez [en lire davantage sur les promesses ici](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises)
et sur [async/await ici](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await).
### Utilisez les gabarits de libellés (*template Literals*)
-Les gabarits de libellés sont des chaînes de caractères délimités par
+Les gabarits de libellés sont des chaînes de caractères délimitées par
des accents graves au lieu d'apostrophes doubles (*quotes*).
const foo = `this is a template literal`;
@@ -274,9 +274,9 @@ const bar = "this\nis\na\ntemplate\nliteral";
ainsi `foo` et `bar` ci-dessus sont similaires.
-L'autre est que vous pouvez sortir du mode chaîne et insérer des fragments
-de code Javascript en utilisant `${javascript-expression}`.
-C'est l'objet des gabarits. Par exemple,
+L'autre particularité est que vous pouvez sortir du mode chaîne et insérer des fragments
+de code Javascript en utilisant `${javascript-expression}`.
+C'est l'objet des gabarits. Par exemple :
```js
const r = 192;
@@ -302,20 +302,20 @@ someElement.style.width = `${aWidth + bWidth}px`;
# Apprenez les conventions de codage JavaScript
-Alors que vous êtes libres de formater votre code comme vous le souhaitez, il
+Alors que vous êtes libre de formater votre code comme vous le souhaitez, il
y a au moins une convention dont vous devez avoir connaissance. Les variables,
-les noms de fonctions et de méthodes sont toutes en *lowerCasedCamelCase* (
-c'est à dire que les mots formant les noms des entités sont collés les uns aux autres et leur première lettre
-est en majuscule, les autres en minuscules à l'exception de la toute première lettre du nom qui
-est également en minuscule -- NDT).
+les noms de fonctions et de méthodes sont toutes en *lowerCasedCamelCase* (c'est
+à dire que les mots formant les noms des entités sont collés les uns aux autres et leur première lettre
+est en majuscule, les autres en minuscules à l'exception de la toute première lettre du nom qui
+est également en minuscule -- NDT).
Les constructeurs, les noms des classes sont en *CapitalizedCamelCase* (
les mots formant les noms des entités sont collés les uns aux autres et leur première lettre
est en majuscule, les autres en minuscules -- NDT).
Si vous suivez cette règle, votre code ressemblera à la plupart des autres
-écrits en JavaScript. Beaucoup de [linters](https://eslint.org), qui sont
+écrits en JavaScript. Beaucoup de [linters](https://eslint.org), qui sont
des programmes vérifiant les erreurs dans votre code,
mettrons en évidence des erreurs si vous utiliser la mauvaise casse puisqu'en
-suivant la convention ci-dessus ils sauront que ces lignes ci-dessous sont
+suivant la convention ci-dessus ils sauront que ces lignes ci-dessous sont
mauvaises :
```js
@@ -326,57 +326,56 @@ const v = Vector(); // évidemment une erreur si toutes les fonctions commen
<!-- JYD -->
# Envisagez l'utilisation de Visual Studio Code
-Bien sûr, vous pouvez utiliser l'éditeur de votre choix mais, si vous ne l'avez pas
-encore essayé, envisagez d'utliser [Visual Studio Code](https://code.visualstudio.com/)
+Bien sûr, vous pouvez utiliser l'éditeur de votre choix mais, si vous ne l'avez pas
+encore essayé, envisagez d'utiliser [Visual Studio Code](https://code.visualstudio.com/)
pour JavaScript et après l'avoir installé, [intégrez-y eslint](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint).
-Cela vous prendra quelques minutes à installer mais vous aidera grandement pour
+Cela vous prendra quelques minutes à installer mais vous aidera grandement pour
trouver les bogues de votre JavaScript.
Quelques exemples
-Si vous activez [la règle `no-undef`](https://eslint.org/docs/rules/no-undef)
+Si vous activez [la règle `no-undef`](https://eslint.org/docs/rules/no-undef)
alors VSCode via ESLint vous avertira de l'utilisation de nombreuses variables non définies.
<div class="threejs_center"><img style="width: 615px;" src="resources/images/vscode-eslint-not-defined.png"></div>
Ci-dessous vous pouvez voir que nous avons écrit `doTheThing` à la place `doThing`.
-`doThing` se retrouve souligné en rouge et un passage au dessus me dira que
+`doThing` se retrouve souligné en rouge et un passage au dessus me dira que
c'est non défini. Une erreur est donc évitée.
-Vous aurez des avertissements (*warnings*) en utilisant `THREE` donc ajoutez `/* global THREE */`
+Vous aurez des avertissements (*warnings*) en utilisant `THREE` donc ajoutez `/* global THREE */`
en haut de vos fichiers JavaScript pour notifier à eslint que `THREE` existe.
<div class="threejs_center"><img style="width: 615px;" src="resources/images/vscode-eslint-not-a-constructor.png"></div>
-Ci-dessus, vous pouvez voir que eslint connaît la règle que les noms commençant par
-une majuscule `UpperCaseNames` sont des constructeurs et vous devez donc utiliser `new`.
+Ci-dessus, vous pouvez voir que eslint connaît la règle que les noms commençant par
+une majuscule `UpperCaseNames` sont des constructeurs et vous devez donc utiliser `new`.
Une autre erreur évitée. C'est [la règle `new-cap` rule](https://eslint.org/docs/rules/new-cap).
-Il y a [des centaines de règles que vous pouvez activer, désactiver ou personnaliser](https://eslint.org/docs/rules/).
+Il y a [des centaines de règles que vous pouvez activer, désactiver ou personnaliser](https://eslint.org/docs/rules/).
Par exemple, précédemment nous avons indiquer que nous devions utiliser `const` et `let` à la place de `var`.
Ici nous avons utilisé `var` et nous avons été avertis que nous devions utiliser `let` ou `const`
<div class="threejs_center"><img style="width: 615px;" src="resources/images/vscode-eslint-var.png"></div>
-Ici nous avons utilisé `let` mais comme la valeur de la variable ne change jamais, nous
+Ici nous avons utilisé `let` mais comme la valeur de la variable ne change jamais, nous
nous voyons suggérer l'utilisation de `const`.
<div class="threejs_center"><img style="width: 615px;" src="resources/images/vscode-eslint-let.png"></div>
Bien sûr, si vous préférez conserver `var`, vous pouvez désactiver cette règle.
-Comme écrit plus haut, nous préférons privilégier `const` et `let` à la place de `var`
+Comme écrit plus haut, nous préférons privilégier `const` et `let` à la place de `var`
puisqu'ils sont plus efficaces et évitent les bogues.
-Pour les cas où vous avez vraiment besoin d'outrepasser une règle,
-[vous pouvez ajouter un commentaire pour les désactiver](https://eslint.org/docs/user-guide/configuring#disabling-rules-with-inline-comments)
-pour une seul ligne ou une section de code.
+Pour les cas où vous avez vraiment besoin d'outrepasser une règle,
+[vous pouvez ajouter un commentaire pour les désactiver](https://eslint.org/docs/user-guide/configuring#disabling-rules-with-inline-comments)
+pour une seule ligne ou une section de code.
# Si vous avez vraiment besoin d'assurer le support de vieux navigateurs, utilisez un transpileur
La plupart des navigateurs se mettent à jour automatiquement donc utiliser les subtilités
-vues plus haut vous aiderons à être productifs et éviter les bogues.
-Ceci étant écrit, si vous êtes dans un projet qui doit absolument supporter des
+vues plus haut vous aiderons à être productif et éviter les bogues.
+Ceci étant dit, si vous êtes dans un projet qui doit absolument supporter des
vieux navigateurs, il y a des [outils qui interpréterons votre code ES5/ES6/ES7
et le transpilent en code JavaScript pre-ES5](https://babeljs.io).
- | true |
Other | mrdoob | three.js | 0ea4e6c3f2655407b1670e48c9f32941330f3eb0.json | Fix french sentences for #51 | threejs/lessons/fr/threejs-responsive.md | @@ -1,23 +1,23 @@
-Title: Design réactif et Three.js
+Title: Design réactif et Three.js
Description: Comment rendre three.js adaptable à des affichages de taille différente.
TOC: Design réactif
-Ceci est le second article dans une série à propos de three.js.
-Le premier était [à propos des principes de base](threejs-fundamentals.html).
-Si vous ne l'avez pas encore lu, vous voudrez peut-être commencer par là.
+Ceci est le second article dans une série traitant de three.js.
+Le premier traitait [des principes de base](threejs-fundamentals.html).
+Si vous ne l'avez pas encore lu, vous deviriez peut-être commencer par le lire.
-Cet article indique comment rendre votre application three.js adaptable
+Ce présent article explique comment rendre votre application three.js adaptable
à n'importe quelle situation. Rendre une page web adaptable (*responsive*)
se réfère généralement à faire en sorte que la page s'affiche de manière
appropriée sur des affichages de taille différente, des ordinateurs de bureau
aux *smart-phones*, en passant par les tablettes.
Concernant three.js, il y a d'ailleurs davantage de situations à traiter.
Par exemple, un éditeur 3D avec des contrôles à gauche, droite, en haut ou
-en bas est quelque chose que nous voudrions gérer. Un schéma interactif
+en bas est quelque chose que nous voudrions gérer. Un schéma interactif
au milieu d'un document en est un autre exemple.
-Le dernier exemple que nous avions utilisé est un canevas sans CSS et
+Le dernier exemple que nous avions utilisé est un canevas sans CSS et
sans taille :
```html
@@ -28,8 +28,8 @@ Ce canevas a par défaut une taille de 300x150 pixels CSS.
Dans le navigateur, la manière recommandée de fixer la taille
de quelque chose est d'utiliser CSS.
-Paramétrons le canevas pour occuper complètement la page en ajoutant
-du CSS
+Paramétrons le canevas pour occuper complètement la page en ajoutant
+du CSS :
```html
<style>
@@ -47,38 +47,38 @@ html, body {
En HTML, la balise *body* a une marge fixée à 5 pixels par défaut donc
la changer à 0 la retire. Modifier la hauteur de *html* et *body* à 100%
-leur fait occuper toute la fenêtre. Sinon, ils ne sont seulement aussi large
+leur fait occuper toute la fenêtre. Sinon, ils ne sont seulement aussi large
que leur contenu.
-Ensuite, nous faisons en sort que l'élément `id=c` fasse
+Ensuite, nous faisons en sorte que l'élément `id=c` fasse
100% de la taille de son conteneur qui, dans ce cas, est le corps du document.
Finalement, nous le passons du mode `display` à celui de `block`.
Le mode par défaut d'affichage d'un canevas est `inline`, ce qui implique
que des espaces peuvent y être ajoutés à l'affichage.
En passant le canevas à `block`, ce problème est supprimé.
-Voici le résultat
+Voici le résultat :
{{{example url="../threejs-responsive-no-resize.html" }}}
-Le canevas, comme nous le voyons, remplit maintenant la page mais il y a 2
-problèmes. Tout d'abord, nos cubes sont étirés et ressemblent à des boîtes, trop
-hautes et trop larges. Ouvrez l'exemple dans sa propre fenêtre et
-redimensionnez la, vous verrez comment les cubes se retrouvent déformés
+Le canevas, comme nous le voyons, remplit maintenant la page mais il y a deux
+problèmes. Tout d'abord, nos cubes sont étirés et ressemblent à des boîtes trop
+hautes et trop larges. Ouvrez l'exemple dans sa propre fenêtre et
+redimensionnez la, vous verrez comment les cubes s'en trouvent déformés
en hauteur et en largeur.
<img src="resources/images/resize-incorrect-aspect.png" width="407" class="threejs_center nobg">
-Le second problème est qu'ils semblent affichés en basse résolution ou
+Le second problème est qu'ils semblent affichés en basse résolution ou
à la fois flous et pixellisés. Si vous étirez beaucoup la fenêtre, vous verrez
pleinement le problème.
<img src="resources/images/resize-low-res.png" class="threejs_center nobg">
Tout d'abord, nous allons résoudre le problème d'étirement.
Pour cela, nous devons calquer l'aspect de la caméra sur celui
-de la taille d'affichage du canevas. Nous pouvons le faire
+de la taille d'affichage du canevas. Nous pouvons le faire
en utilisant les propriétés `clientWidth` et `clientHeight` du canevas.
Nous mettons alors notre boucle de rendu comme cela :
@@ -99,7 +99,7 @@ A présent les cubes ne devraient plus être déformés.
{{{example url="../threejs-responsive-update-camera.html" }}}
Ouvrez l'exemple dans une fenêtre séparée et redimensionnez là.
-Vous devriez voir que les cubes ne sont plus étirés, que ce soit
+Vous devriez voir que les cubes ne sont plus étirés, que ce soit
en hauteur ou en largeur.
Ils restent corrects quelque soit l'aspect de la taille de la fenêtre.
@@ -108,25 +108,25 @@ Ils restent corrects quelque soit l'aspect de la taille de la fenêtre.
Maintenant résolvons le problème de la pixellisation.
Les éléments de type *canvas* ont deux tailles. La première
-est celle du canevas affiché dans la page. C'est ce que nous paramétrons avec le CSS.
-L'autre taille est le nombre de pixels dont est constitué le canevas lui-même.
-Ceci n'est pas différent d'une image.
-Par exemple, nous pouvons avoir une image de taille 128x64 et, en utilisant le CSS,
+est celle du canevas affiché dans la page. C'est ce que nous paramétrons avec le CSS.
+L'autre taille est le nombre de pixels dont est constitué le canevas lui-même.
+Ceci n'est pas différent d'une image.
+Par exemple, nous pouvons avoir une image de taille 128x64 et, en utilisant le CSS,
nous pouvons l'afficher avec une taille de 400x200.
```html
<img src="some128x64image.jpg" style="width:400px; height:200px">
```
-La taille interne d'un canevas, sa résolution, est souvent appelé sa taille de tampon
-de dessin (*drawingbuffer*). Dans three.js, nous pouvons ajuster cette taille
+La taille interne d'un canevas, sa résolution, est souvent appelée sa taille de tampon
+de dessin (*drawingbuffer*). Dans three.js, nous pouvons ajuster cette taille
de canevas en appelant `renderer.setSize`.
-Quelle taille devons nous choisir ? La réponse la plus évident est "la même taille que
+Quelle taille devons nous choisir ? La réponse la plus évidente est "la même taille que
celle d'affichage du canevas". A nouveau, pour le faire, nous pouvons avoir recours
au propriétés `clientWidth` et `clientHeight`.
Ecrivons une fonction qui vérifie si le canevas du *renderer* est ou non à la taille
-qui est affiché et l'ajuste en conséquence.
+qui est affichée et l'ajuste en conséquence.
```js
function resizeRendererToDisplaySize(renderer) {
@@ -142,16 +142,16 @@ function resizeRendererToDisplaySize(renderer) {
```
Remarquez que nous vérifions sur le canevas a réellement besoin d'être redimensionné.
-Le redimensionnement est une partie intéressante de la spécification du canevas
+Le redimensionnement est une partie intéressante de la spécification du canevas
et il est mieux de ne pas lui donner à nouveau la même taille s'il est déjà
à la dimension que nous voulons.
-Une fois que nous savons si le redimensionnement est nécessaire ou non, nous
+Une fois que nous savons si le redimensionnement est nécessaire ou non, nous
appelons `renderer.setSize` et lui passons les nouvelles largeur et hauteur.
-Il est important de passer `false` en troisième.
+Il est important de passer `false` en troisième.
`render.setSize` modifie par défaut la taille du canevas CSS, mais ce n'est
pas ce que nous voulons. Nous souhaitons que le navigateur continue à fonctionner
-comme pour les autres éléments, qui est d'utiliser CSS pour déterminer la
+comme pour les autres éléments, qui est d'utiliser CSS pour déterminer la
taille d'affichage d'un élément. Nous ne voulons pas que les canevas utilisés
par three aient un comportement différent des autres éléments.
@@ -206,43 +206,43 @@ autrement dit, les écrans à haute densité d'affichage.
C'est le cas de la plupart des Macs, des machines sous Windows
ainsi que des smartphones.
-La façon dont cela fonctionne dans le navigateur est
-qu'il utilise les pixels CSS pour mettre à jour la taille
-qui est supposée être la même quelque soit la résolution de
+La façon dont cela fonctionne dans le navigateur est
+qu'il utilise les pixels CSS pour mettre à jour la taille
+qui est supposée être la même quelque soit la résolution de
l'affichage. Le navigateur effectue le rendu du texte avec davantage
de détails mais la même taille physique.
Il y a plusieurs façons de gérer les HD-DPI avec three.js.
-La première façon est de ne rien faire de spécial. Cela
-est, de manière discutable, le plus commun. Effectuer le
+La première façon est de ne rien faire de spécial. Cela
+est, de manière discutable, le plus commun. Effectuer le
rendu de graphismes 3D prend beaucoup de puissance de calcul GPU
(*Graphics Processing Units*, les processeurs dédiés de carte graphique).
Les GPUs mobiles ont moins de puissance que les ordinateurs de bureau,
-du moins en 2018, et pourtant les téléphones mobules ont des affichages
+du moins en 2018, et pourtant les téléphones mobiles ont des affichages
haute résolution. Le haut de gamme actuel pour les smartphones a un ratio
HD-DPI de 3x, ce qui signifie que pour chaque pixel d'un affichage non HD-DPI,
ces téléphones ont 9 pixels. Il y a donc 9 fois plus de travail
pour le rendu.
-Calculer pour 9 pixels nécessite des ressources donc, si
+Calculer pour 9 pixels nécessite des ressources donc, si
nous laissons le code comme cela, nous calculerons pour 1 pixel
et le navigateur le dessinera avec 3 fois sa taille (3 x 3 = 9 pixels).
-Pour toute application three.js lourde, c'est probablement ce que vous
-voulez sinon vous risquez d'avoir un taux de rafraîssement faible (*framerate*).
+Pour toute application three.js lourde, c'est probablement ce que vous
+voulez sinon vous risquez d'avoir un taux de rafraîchissement faible (*framerate*).
Ceci étant dit, si vous préférez effectuer le rendu à la résolution de l'appareil,
voici quelques façons de le faire en three.js.
La première est d'indiquer à three.js le facteur de multiplication de la résolution
-en utilisant `renderer.setPixelRatio`. Nous pouvons demander au navigateur ce
+en utilisant `renderer.setPixelRatio`. Nous pouvons demander au navigateur ce
facteur entre les pixels CSS et les pixels du périphérique et les passer à three.js
renderer.setPixelRatio(window.devicePixelRatio);
Après cela, tout appel à `renderer.setSize` va automatiquement
-utiliser la taille que vous avez demandée, multipliée par le
+utiliser la taille que vous avez demandée, multipliée par le
ratio que vous avez demandé.
**Ceci est fortement DÉCONSEILLÉ**. Voir ci-dessous.
@@ -266,26 +266,25 @@ Cette seconde façon est objectivement meilleure. Pourquoi ? Parce que cela sign
que nous avons ce que nous avons demandé. Il y a plusieurs cas où,
quand on utilise three.js, nous avons besoin de savoir la taille effective
du tampon d'affichage du canevas. Par exemple, quand on réalise un filtre de
-post-processing, ou si nous faisons un *shader* qui accède à `gl_FragCoord`,
+post-processing, ou si nous faisons un *shader* qui accède à `gl_FragCoord`,
si nous sommes en train de faire une capture d'écran, ou en train de lire les pixels
pour une sélection par GPU, pour dessiner dans un canevas 2D, etc...
Il y a plusieurs cas où, si nous utilisons `setPixelRatio` alors notre
-taille effective est différente de la taille que nous avons demandé et nous
+taille effective est différente de la taille que nous avons demandé et nous
aurons alors à deviner quand utiliser la taille demandée ou la taille utilisée
-par three.js.
+par three.js.
En le faisant par soi-même, nous savons toujours que la taille utilisée
-est celle que nous avons demandé. Il n'y a aucun cas où cela se fait tout
+est celle que nous avons demandé. Il n'y a aucun cas où cela se fait tout
seul autrement.
Voici un exemple utilisant le code vu plus haut.
{{{example url="../threejs-responsive-hd-dpi.html" }}}
-Cela devrait être difficile de voir la différence, mais si vous avez
+Cela devrait être difficile de voir la différence, mais si vous avez
un affichage HD-DPI et que vous comparez cet exemple aux autres plus
-haut, vous devriez remarquer que les arêtes sont plus vives.
+haut, vous devriez remarquer que les arêtes sont plus vives.
-Cet article a couvert un sujet très basique mais fondamental.
-Ensuite, nous allons rapidement
+Cet article a couvert un sujet très basique mais fondamental.
+Ensuite, nous allons rapidement
[passer en revue les primitives de base proposées par three.js](threejs-primitives.html).
- | true |
Other | mrdoob | three.js | e22c820d6f1af6c34e628f499642a54a7ace1c60.json | fix horizontal scrollbar on certain pages | threejs/lessons/resources/lesson.css | @@ -80,7 +80,7 @@ div[data-diagram] {
position: absolute;
top: 0;
left: 0;
- width: 100vw;
+ width: 100%;
height: 100vh;
z-index: -100;
} | true |
Other | mrdoob | three.js | e22c820d6f1af6c34e628f499642a54a7ace1c60.json | fix horizontal scrollbar on certain pages | threejs/lessons/resources/threejs-lesson-utils.js | @@ -7,7 +7,10 @@ export const threejsLessonUtils = {
if (this.renderer) {
return;
}
- const canvas = document.querySelector('#c');
+
+ const canvas = document.createElement('canvas');
+ canvas.id = 'c';
+ document.body.appendChild(canvas);
const renderer = new THREE.WebGLRenderer({
canvas,
alpha: true,
@@ -36,7 +39,7 @@ export const threejsLessonUtils = {
const render = (time) => {
time *= 0.001;
- resizeRendererToDisplaySize(renderer);
+ const resized = resizeRendererToDisplaySize(renderer);
renderer.setScissorTest(false);
@@ -62,7 +65,7 @@ export const threejsLessonUtils = {
renderer.domElement.style.transform = transform;
this.renderFuncs.forEach((fn) => {
- fn(renderer, time);
+ fn(renderer, time, resized);
});
requestAnimationFrame(render);
@@ -177,8 +180,8 @@ export const threejsLessonUtils = {
return;
}
- renderInfo.width = (rect.right - rect.left) * this.pixelRatio;
- renderInfo.height = (rect.bottom - rect.top) * this.pixelRatio;
+ renderInfo.width = rect.width * this.pixelRatio;
+ renderInfo.height = rect.height * this.pixelRatio;
renderInfo.left = rect.left * this.pixelRatio;
renderInfo.bottom = (renderer.domElement.clientHeight - rect.bottom) * this.pixelRatio;
| true |
Other | mrdoob | three.js | e22c820d6f1af6c34e628f499642a54a7ace1c60.json | fix horizontal scrollbar on certain pages | threejs/lessons/ru/threejs-primitives.md | @@ -329,6 +329,5 @@ function addLineGeometry(x, y, geometry) {
Далее давайте рассмотрим [как работает граф сцены и как его использовать](threejs-scenegraph.html).
-<canvas id="c"></canvas>
<script type="module" src="../resources/threejs-primitives.js"></script>
<link rel="stylesheet" href="../resources/threejs-primitives.css"> | true |
Other | mrdoob | three.js | e22c820d6f1af6c34e628f499642a54a7ace1c60.json | fix horizontal scrollbar on certain pages | threejs/lessons/ru/threejs-textures.md | @@ -615,6 +615,5 @@ metalness
roughness
-->
-<canvas id="c"></canvas>
<script type="module" src="../resources/threejs-textures.js"></script>
<link rel="stylesheet" href="../resources/threejs-textures.css"> | true |
Other | mrdoob | three.js | e22c820d6f1af6c34e628f499642a54a7ace1c60.json | fix horizontal scrollbar on certain pages | threejs/lessons/threejs-primitives.md | @@ -398,7 +398,6 @@ 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).
-<canvas id="c"></canvas>
<link rel="stylesheet" href="resources/threejs-primitives.css">
<script type="module" src="resources/threejs-primitives.js"></script>
| true |
Other | mrdoob | three.js | e22c820d6f1af6c34e628f499642a54a7ace1c60.json | fix horizontal scrollbar on certain pages | threejs/lessons/threejs-textures.md | @@ -624,6 +624,5 @@ metalness
roughness
-->
-<canvas id="c"></canvas>
<link rel="stylesheet" href="resources/threejs-textures.css">
<script type="module" src="resources/threejs-textures.js"></script> | true |
Other | mrdoob | three.js | 2efb3385eff61e8cf18694d7689c764c61bca3a7.json | fix input textarea color | threejs/lessons/resources/threejs-primitives.css | @@ -39,6 +39,12 @@ div[data-primitive] .input>div {
div[data-primitive] .input input {
position: absolute;
}
+div[data-primitive] .input input[type=text] {
+ background: #444;
+ color: white;
+ border: none;
+ padding: 3px;
+}
@media (max-width: 600px) {
div[data-primitive] .input>div { | false |
Other | mrdoob | three.js | 3714df0b234c3b509a0e169b0621045eda4af5cf.json | add sliders to primitives | threejs/lessons/resources/lesson.css | @@ -39,6 +39,7 @@ pre>code {
pre.prettyprint {
margin-top: 2em !important;
margin-bottom: 2em !important;
+ position: relative;
}
pre.prettyprint li {
white-space: pre;
@@ -565,5 +566,10 @@ pre.prettyprint.lighttheme .fun { color: #900; } /* function name */
.lesson-comment-notes {
background: #222;
}
+ input[type=text] {
+ background: #444;
+ color: white;
+ border: none;
+ padding: 3px;
+ }
}
- | true |
Other | mrdoob | three.js | 3714df0b234c3b509a0e169b0621045eda4af5cf.json | add sliders to primitives | threejs/lessons/resources/threejs-lesson-utils.js | @@ -217,4 +217,4 @@ export const threejsLessonUtils = {
},
};
-
+window.threejsLessonUtils = threejsLessonUtils;
\ No newline at end of file | true |
Other | mrdoob | three.js | 3714df0b234c3b509a0e169b0621045eda4af5cf.json | add sliders to primitives | threejs/lessons/resources/threejs-primitives.css | @@ -21,12 +21,50 @@ div[data-primitive] .desc {
div[data-primitive] .desc code {
white-space: normal;
}
+
+div[data-primitive] .input {
+ display: inline-block;
+ user-select: none;
+}
+div[data-primitive] .input::before {
+ content:" ";
+}
+div[data-primitive] .input input[type=range] {
+ width: 200px;
+}
+div[data-primitive] .input>div {
+ position: absolute;
+ display: inline-block;
+}
+div[data-primitive] .input input {
+ position: absolute;
+}
+
+@media (max-width: 600px) {
+ div[data-primitive] .input>div {
+ right: 0;
+ }
+ div[data-primitive] .input input {
+ opacity: 0.2;
+ right: 1em;
+ }
+}
+
@media (max-width: 550px) {
div[data-primitive] .shape {
width: 120px;
height: 120px;
}
}
+@media (max-width: 450px) {
+ div[data-primitive] .pair {
+ flex-direction: column-reverse;
+ }
+ div[data-primitive] .shape {
+ margin: 0 auto;
+ width: 100%;
+ }
+}
div[data-primitive] .desc {
flex: 1 1 auto;
} | true |
Other | mrdoob | three.js | 3714df0b234c3b509a0e169b0621045eda4af5cf.json | add sliders to primitives | threejs/lessons/resources/threejs-primitives.js | @@ -189,15 +189,15 @@ const geometry = THREE.ExtrudeBufferGeometry(shape, extrudeSettings);
for (let i = 0; i < 10; ++i) {
points.push(new THREE.Vector2(Math.sin(i * 0.2) * 3 + 3, (i - 5) * .8));
}
- const geometry = new THREE.LatheBufferGeometry(points);
- return geometry;
+ return new THREE.LatheBufferGeometry(points);
},
create2(segments = 12, phiStart = Math.PI * 0.25, phiLength = Math.PI * 1.5) {
const points = [];
for (let i = 0; i < 10; ++i) {
points.push(new THREE.Vector2(Math.sin(i * 0.2) * 3 + 3, (i - 5) * .8));
}
- return new THREE.LatheBufferGeometry(points, segments, phiStart, phiLength);
+ return new THREE.LatheBufferGeometry(
+ points, segments, phiStart, phiLength);
},
},
OctahedronBufferGeometry: {
@@ -266,7 +266,8 @@ const geometry = THREE.ExtrudeBufferGeometry(shape, extrudeSettings);
target.set(x, y, z).multiplyScalar(0.75);
}
- return new THREE.ParametricBufferGeometry(klein, slices, stacks);
+ return new THREE.ParametricBufferGeometry(
+ klein, slices, stacks);
},
},
PlaneBufferGeometry: {
@@ -317,7 +318,8 @@ const geometry = THREE.ExtrudeBufferGeometry(shape, extrudeSettings);
thetaLength: { type: 'range', min: 0, max: 2, mult: Math.PI },
},
create(innerRadius = 2, outerRadius = 7, thetaSegments = 18) {
- return new THREE.RingBufferGeometry(innerRadius, outerRadius, thetaSegments);
+ return new THREE.RingBufferGeometry(
+ innerRadius, outerRadius, thetaSegments);
},
create2(innerRadius = 2, outerRadius = 7, thetaSegments = 18, phiSegments = 2, thetaStart = Math.PI * 0.25, thetaLength = Math.PI * 1.5) {
return new THREE.RingBufferGeometry(
@@ -341,8 +343,7 @@ const geometry = THREE.ExtrudeBufferGeometry(shape, extrudeSettings);
shape.bezierCurveTo(x + 6, y + 7.7, x + 8, y + 4.5, x + 8, y + 3.5);
shape.bezierCurveTo(x + 8, y + 3.5, x + 8, y, x + 5, y);
shape.bezierCurveTo(x + 3.5, y, x + 2.5, y + 2.5, x + 2.5, y + 2.5);
- const geometry = new THREE.ShapeBufferGeometry(shape);
- return geometry;
+ return new THREE.ShapeBufferGeometry(shape);
},
create2(curveSegments = 5) {
const shape = new THREE.Shape();
@@ -405,24 +406,20 @@ const geometry = THREE.ExtrudeBufferGeometry(shape, extrudeSettings);
bevelSegments: { type: 'range', min: 0, max: 8, },
},
addConstCode: false,
- async create(text = 'three.js', size = 3, height = 0.2, curveSegments = 12, bevelEnabled = true, bevelThickness = 0.15, bevelSize = 0.3, bevelSegments = 5) {
- const loader = new THREE.FontLoader();
- // promisify font loading
- function loadFont(url) {
- return new Promise((resolve, reject) => {
- loader.load(url, resolve, undefined, reject);
+ create(text = 'three.js', size = 3, height = 0.2, curveSegments = 12, bevelEnabled = true, bevelThickness = 0.15, bevelSize = 0.3, bevelSegments = 5) {
+ return new Promise((resolve) => {
+ fontPromise.then((font) => {
+ resolve(new THREE.TextBufferGeometry(text, {
+ font: font,
+ size,
+ height,
+ curveSegments,
+ bevelEnabled,
+ bevelThickness,
+ bevelSize,
+ bevelSegments,
+ }));
});
- }
- const font = await loadFont('/threejs/resources/threejs/fonts/helvetiker_regular.typeface.json');
- return new THREE.TextBufferGeometry(text, {
- font: font,
- size,
- height,
- curveSegments,
- bevelEnabled,
- bevelThickness,
- bevelSize,
- bevelSegments,
});
},
src: `
@@ -499,25 +496,40 @@ loader.load('../resources/threejs/fonts/helvetiker_regular.typeface.json', (font
},
EdgesGeometry: {
ui: {
- widthSegments: { type: 'range', min: 1, max: 10, },
- heightSegments: { type: 'range', min: 1, max: 10, },
- depthSegments: { type: 'range', min: 1, max: 10, },
+ thresholdAngle: { type: 'range', min: 1, max: 180, },
},
- create(widthSegments = 2, heightSegments = 2, depthSegments = 2) {
- const size = 8;
+ create() {
return {
- lineGeometry: new THREE.EdgesGeometry(new THREE.BoxBufferGeometry(
- size, size, size,
- widthSegments, heightSegments, depthSegments)),
+ lineGeometry: new THREE.EdgesGeometry(
+ new THREE.BoxBufferGeometry(8, 8, 8)),
+ };
+ },
+ create2(thresholdAngle = 1) {
+ return {
+ lineGeometry: new THREE.EdgesGeometry(
+ new THREE.SphereBufferGeometry(7, 6, 3), thresholdAngle),
};
},
nonBuffer: false,
+ addConstCode: false,
src: `
const size = 8;
-const geometry = new THREE.EdgesGeometry(
- new THREE.BoxBufferGeometry(
- size, size, size,
- widthSegments, heightSegments, depthSegments));
+const widthSegments = 2;
+const heightSegments = 2;
+const depthSegments = 2;
+const boxGeometry = new THREE.BoxBufferGeometry(
+ size, size, size,
+ widthSegments, heightSegments, depthSegments);
+const geometry = new THREE.EdgesGeometry(boxGeometry);
+`,
+ src2: `
+const radius = 7;
+const widthSegments = 6;
+const heightSegments = 3;
+const sphereGeometry = new THREE.SphereBufferGeometry(
+ radius, widthSegments, heightSegments);
+const thresholdAngle = 1; // ui: thresholdAngle
+const geometry = new THREE.EdgesGeometry(sphereGeometry, thresholdAngle);
`,
},
WireframeGeometry: {
@@ -535,8 +547,12 @@ const geometry = new THREE.EdgesGeometry(
};
},
nonBuffer: false,
+ addConstCode: false,
src: `
const size = 8;
+const widthSegments = 2; // ui: widthSegments
+const heightSegments = 2; // ui: heightSegments
+const depthSegments = 2; // ui: depthSegments
const geometry = new THREE.WireframeGeometry(
new THREE.BoxBufferGeometry(
size, size, size,
@@ -557,6 +573,7 @@ const geometry = new THREE.WireframeGeometry(
return {
showLines: false,
mesh: points,
+ geometry,
};
},
},
@@ -575,6 +592,7 @@ const geometry = new THREE.WireframeGeometry(
return {
showLines: false,
mesh: points,
+ geometry,
};
},
},
@@ -650,10 +668,6 @@ const geometry = new THREE.WireframeGeometry(
return addElem(parent, 'div', className);
}
- const primitives = {};
- document.querySelectorAll('[data-diagram]').forEach(createDiagram);
- document.querySelectorAll('[data-primitive]').forEach(createPrimitiveDOM);
-
function createPrimitiveDOM(base) {
const name = base.dataset.primitive;
const info = diagrams[name];
@@ -726,72 +740,65 @@ const geometry = new THREE.WireframeGeometry(
if (!info) {
throw new Error(`no primitive ${name}`);
}
- return createLiveImage(base, info, name);
+ createLiveImage(base, info, name);
}
- const whiteLineMaterial = new THREE.LineBasicMaterial({
- color: 0xffffff,
- transparent: true,
- opacity: 0.5,
- });
- const blackLineMaterial = new THREE.LineBasicMaterial({
- color: 0x000000,
- transparent: true,
- opacity: 0.5,
- });
-
- function addGeometry(root, info, args = []) {
+ async function addGeometry(root, info, args = []) {
const geometry = info.create(...args);
const promise = (geometry instanceof Promise) ? geometry : Promise.resolve(geometry);
- return promise.then((geometryInfo) => {
- if (geometryInfo instanceof THREE.BufferGeometry ||
- geometryInfo instanceof THREE.Geometry) {
- const geometry = geometryInfo;
- geometryInfo = {
- geometry,
- };
- }
+ let geometryInfo = await promise;
+ if (geometryInfo instanceof THREE.BufferGeometry ||
+ geometryInfo instanceof THREE.Geometry) {
+ const geometry = geometryInfo;
+ geometryInfo = {
+ geometry,
+ };
+ }
- const boxGeometry = geometryInfo.geometry || geometryInfo.lineGeometry;
- boxGeometry.computeBoundingBox();
- const centerOffset = new THREE.Vector3();
- boxGeometry.boundingBox.getCenter(centerOffset).multiplyScalar(-1);
+ const boxGeometry = geometryInfo.geometry || geometryInfo.lineGeometry;
+ boxGeometry.computeBoundingBox();
+ const centerOffset = new THREE.Vector3();
+ boxGeometry.boundingBox.getCenter(centerOffset).multiplyScalar(-1);
- if (geometryInfo.geometry) {
- if (!info.material) {
- const material = new THREE.MeshPhongMaterial({
- flatShading: info.flatShading === false ? false : true,
- side: THREE.DoubleSide,
- });
- material.color.setHSL(Math.random(), .5, .5);
- info.material = material;
- }
- const mesh = new THREE.Mesh(geometryInfo.geometry, info.material);
- mesh.position.copy(centerOffset);
- root.add(mesh);
- }
- if (info.showLines !== false) {
- const lineMesh = new THREE.LineSegments(
- geometryInfo.lineGeometry || geometryInfo.geometry,
- geometryInfo.geometry ? whiteLineMaterial : blackLineMaterial);
- lineMesh.position.copy(centerOffset);
- root.add(lineMesh);
+ if (geometryInfo.geometry) {
+ if (!info.material) {
+ const material = new THREE.MeshPhongMaterial({
+ flatShading: info.flatShading === false ? false : true,
+ side: THREE.DoubleSide,
+ });
+ material.color.setHSL(Math.random(), .5, .5);
+ info.material = material;
}
- });
+ const mesh = new THREE.Mesh(geometryInfo.geometry, info.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);
+ }
}
- function updateGeometry(root, info, params) {
+ async function updateGeometry(root, info, params) {
const oldChildren = root.children.slice();
- addGeometry(root, info, Object.values(params)).then(() => {
- oldChildren.forEach((child) => {
- root.remove(child);
- child.geometry.dispose();
- });
+ await addGeometry(root, info, Object.values(params));
+ oldChildren.forEach((child) => {
+ root.remove(child);
+ child.geometry.dispose();
});
}
- function createLiveImage(elem, info, name) {
+ const primitives = {};
+
+ async function createLiveImage(elem, info, name) {
const root = new THREE.Object3D();
primitives[name] = primitives[name] || [];
@@ -800,9 +807,8 @@ const geometry = new THREE.WireframeGeometry(
info,
});
- addGeometry(root, info).then(() => {
- threejsLessonUtils.addDiagram(elem, {create: () => root});
- });
+ await addGeometry(root, info);
+ threejsLessonUtils.addDiagram(elem, {create: () => root});
}
function getValueElem(commentElem) {
@@ -838,6 +844,11 @@ const geometry = new THREE.WireframeGeometry(
console.error(`no value element for ${primitiveName}:${ndx} param: ${name}`); // eslint-disable-line
return;
}
+ const inputHolderHolder = document.createElement('div');
+ inputHolderHolder.className = 'input';
+ const inputHolder = document.createElement('div');
+ span.appendChild(inputHolderHolder);
+ inputHolderHolder.appendChild(inputHolder);
switch (ui.type) {
case 'range': {
const valueRange = ui.max - ui.min;
@@ -849,7 +860,7 @@ const geometry = new THREE.WireframeGeometry(
const value = parseFloat(valueElem.textContent);
params[name] = value * (ui.mult || 1);
input.value = (value - ui.min) / valueRange * inputMax;
- span.appendChild(input);
+ inputHolder.appendChild(input);
const precision = ui.precision === undefined ? (valueRange > 4 ? 0 : 2) : ui.precision;
const padding = ui.max.toFixed(precision).length;
input.addEventListener('input', () => {
@@ -868,7 +879,7 @@ const geometry = new THREE.WireframeGeometry(
input.type = 'checkbox';
params[name] = valueElem.textContent === 'true';
input.checked = params[name];
- span.appendChild(input);
+ inputHolder.appendChild(input);
input.addEventListener('change', () => {
params[name] = input.checked;
valueElem.textContent = params[name] ? 'true' : 'false';
@@ -882,7 +893,7 @@ const geometry = new THREE.WireframeGeometry(
params[name] = valueElem.textContent.slice(1, -1);
input.value = params[name];
input.maxlength = ui.maxLength || 50;
- span.appendChild(input);
+ inputHolder.appendChild(input);
input.addEventListener('input', () => {
params[name] = input.value;
valueElem.textContent = `'${input.value.replace(/'/g, '\'')}'`;
@@ -891,10 +902,13 @@ const geometry = new THREE.WireframeGeometry(
break;
}
default:
- throw new Error(`unknonw type for ${primitiveName}:${ndx} param: ${name}`);
+ throw new Error(`unknown type for ${primitiveName}:${ndx} param: ${name}`);
}
});
});
});
});
+
+ document.querySelectorAll('[data-diagram]').forEach(createDiagram);
+ document.querySelectorAll('[data-primitive]').forEach(createPrimitiveDOM);
}
\ No newline at end of file | true |
Other | mrdoob | three.js | 3714df0b234c3b509a0e169b0621045eda4af5cf.json | add sliders to primitives | threejs/lessons/threejs-primitives.md | @@ -42,7 +42,7 @@ for <code>TextBufferGeometry</code> and <code>TextGeometry</code> respectively.<
<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 <code>EdgesGeometry</code> instead the middle lines are removed.</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. Adjust the thresholdAngle below and you'll see the edges below that threshold disappear.</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`
@@ -75,7 +75,7 @@ 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. Whereas for `Geometry` you can add vertices as you go.
-We'll go over creating custom geometry in another article. For now
+We'll go over creating custom geometry in [another article](threejs-custom-geometry.html). For now
let's make an example creating each type of primitive. We'll start
with the [examples from the previous article](threejs-responsive.html).
| true |
Other | mrdoob | three.js | 816ec01e260847437dca4c8c4fb9a6d36ab147fd.json | fix position calculation | threejs/lessons/threejs-indexed-textures.md | @@ -162,8 +162,8 @@ const pickHelper = new GPUPickHelper();
function getCanvasRelativePosition(event) {
const rect = canvas.getBoundingClientRect();
return {
- x: event.clientX - rect.left,
- y: event.clientY - rect.top,
+ x: (event.clientX - rect.left) * canvas.width / rect.width,
+ y: (event.clientY - rect.top ) * canvas.height / rect.height,
};
}
@@ -538,8 +538,8 @@ is selected
function getCanvasRelativePosition(event) {
const rect = canvas.getBoundingClientRect();
return {
- x: event.clientX - rect.left,
- y: event.clientY - rect.top,
+ x: (event.clientX - rect.left) * canvas.width / rect.width,
+ y: (event.clientY - rect.top ) * canvas.height / rect.height,
};
}
@@ -609,8 +609,8 @@ to drag the globe.
function getCanvasRelativePosition(event) {
const rect = canvas.getBoundingClientRect();
return {
- x: event.clientX - rect.left,
- y: event.clientY - rect.top,
+ x: (event.clientX - rect.left) * canvas.width / rect.width,
+ y: (event.clientY - rect.top ) * canvas.height / rect.height,
};
}
| true |
Other | mrdoob | three.js | 816ec01e260847437dca4c8c4fb9a6d36ab147fd.json | fix position calculation | threejs/lessons/threejs-offscreencanvas.md | @@ -463,15 +463,15 @@ We updated `pickPosition` from the mouse like this
function getCanvasRelativePosition(event) {
const rect = canvas.getBoundingClientRect();
return {
- x: event.clientX - rect.left,
- y: event.clientY - rect.top,
+ x: (event.clientX - rect.left) * canvas.width / rect.width,
+ y: (event.clientY - rect.top ) * canvas.height / rect.height,
};
}
function setPickPosition(event) {
const pos = getCanvasRelativePosition(event);
- pickPosition.x = (pos.x / canvas.clientWidth ) * 2 - 1;
- pickPosition.y = (pos.y / canvas.clientHeight) * -2 + 1; // note we flip Y
+ pickPosition.x = (pos.x / canvas.width ) * 2 - 1;
+ pickPosition.y = (pos.y / canvas.height) * -2 + 1; // note we flip Y
}
window.addEventListener('mousemove', setPickPosition);
``` | true |
Other | mrdoob | three.js | 816ec01e260847437dca4c8c4fb9a6d36ab147fd.json | fix position calculation | threejs/lessons/threejs-picking.md | @@ -134,15 +134,15 @@ clearPickPosition();
function getCanvasRelativePosition(event) {
const rect = canvas.getBoundingClientRect();
return {
- x: event.clientX - rect.left,
- y: event.clientY - rect.top,
+ x: (event.clientX - rect.left) * canvas.width / rect.width,
+ y: (event.clientY - rect.top ) * canvas.height / rect.height,
};
}
function setPickPosition(event) {
const pos = getCanvasRelativePosition(event);
- pickPosition.x = (pos.x / canvas.clientWidth ) * 2 - 1;
- pickPosition.y = (pos.y / canvas.clientHeight) * -2 + 1; // note we flip Y
+ pickPosition.x = (pos.x / canvas.width ) * 2 - 1;
+ pickPosition.y = (pos.y / canvas.height) * -2 + 1; // note we flip Y
}
function clearPickPosition() { | true |
Other | mrdoob | three.js | 816ec01e260847437dca4c8c4fb9a6d36ab147fd.json | fix position calculation | threejs/lessons/threejs-voxel-geometry.md | @@ -972,15 +972,15 @@ hit.
function getCanvasRelativePosition(event) {
const rect = canvas.getBoundingClientRect();
return {
- x: event.clientX - rect.left,
- y: event.clientY - rect.top,
+ x: (event.clientX - rect.left) * canvas.width / rect.width,
+ y: (event.clientY - rect.top ) * canvas.height / rect.height,
};
}
function placeVoxel(event) {
const pos = getCanvasRelativePosition(event);
- const x = (pos.x / canvas.clientWidth ) * 2 - 1;
- const y = (pos.y / canvas.clientHeight) * -2 + 1; // note we flip Y
+ const x = (pos.x / canvas.width ) * 2 - 1;
+ const y = (pos.y / canvas.height) * -2 + 1; // note we flip Y
const start = new THREE.Vector3();
const end = new THREE.Vector3(); | true |
Other | mrdoob | three.js | 816ec01e260847437dca4c8c4fb9a6d36ab147fd.json | fix position calculation | threejs/threejs-indexed-textures-picking-and-highlighting.html | @@ -345,8 +345,8 @@
function getCanvasRelativePosition(event) {
const rect = canvas.getBoundingClientRect();
return {
- x: event.clientX - rect.left,
- y: event.clientY - rect.top,
+ x: (event.clientX - rect.left) * canvas.width / rect.width,
+ y: (event.clientY - rect.top ) * canvas.height / rect.height,
};
}
| true |
Other | mrdoob | three.js | 816ec01e260847437dca4c8c4fb9a6d36ab147fd.json | fix position calculation | threejs/threejs-indexed-textures-picking-debounced.html | @@ -350,8 +350,8 @@
function getCanvasRelativePosition(event) {
const rect = canvas.getBoundingClientRect();
return {
- x: event.clientX - rect.left,
- y: event.clientY - rect.top,
+ x: (event.clientX - rect.left) * canvas.width / rect.width,
+ y: (event.clientY - rect.top ) * canvas.height / rect.height,
};
}
| true |
Other | mrdoob | three.js | 816ec01e260847437dca4c8c4fb9a6d36ab147fd.json | fix position calculation | threejs/threejs-indexed-textures-picking.html | @@ -276,8 +276,8 @@
function getCanvasRelativePosition(event) {
const rect = canvas.getBoundingClientRect();
return {
- x: event.clientX - rect.left,
- y: event.clientY - rect.top,
+ x: (event.clientX - rect.left) * canvas.width / rect.width,
+ y: (event.clientY - rect.top ) * canvas.height / rect.height,
};
}
| true |
Other | mrdoob | three.js | 816ec01e260847437dca4c8c4fb9a6d36ab147fd.json | fix position calculation | threejs/threejs-indexed-textures-random-colors.html | @@ -325,8 +325,8 @@
function getCanvasRelativePosition(event) {
const rect = canvas.getBoundingClientRect();
return {
- x: event.clientX - rect.left,
- y: event.clientY - rect.top,
+ x: (event.clientX - rect.left) * canvas.width / rect.width,
+ y: (event.clientY - rect.top ) * canvas.height / rect.height,
};
}
| true |
Other | mrdoob | three.js | 816ec01e260847437dca4c8c4fb9a6d36ab147fd.json | fix position calculation | threejs/threejs-offscreencanvas-w-picking.html | @@ -85,16 +85,16 @@
function getCanvasRelativePosition(event) {
const rect = canvas.getBoundingClientRect();
return {
- x: event.clientX - rect.left,
- y: event.clientY - rect.top,
- };
+ x: (event.clientX - rect.left) * canvas.width / rect.width,
+ y: (event.clientY - rect.top ) * canvas.height / rect.height,
+ };
}
function setPickPosition(event) {
const pos = getCanvasRelativePosition(event);
sendMouse(
- (pos.x / canvas.clientWidth ) * 2 - 1,
- (pos.y / canvas.clientHeight) * -2 + 1); // note we flip Y
+ (pos.x / canvas.width ) * 2 - 1,
+ (pos.y / canvas.height) * -2 + 1); // note we flip Y
}
function clearPickPosition() { | true |
Other | mrdoob | three.js | 816ec01e260847437dca4c8c4fb9a6d36ab147fd.json | fix position calculation | threejs/threejs-picking-gpu.html | @@ -205,8 +205,8 @@
function getCanvasRelativePosition(event) {
const rect = canvas.getBoundingClientRect();
return {
- x: event.clientX - rect.left,
- y: event.clientY - rect.top,
+ x: (event.clientX - rect.left) * canvas.width / rect.width,
+ y: (event.clientY - rect.top ) * canvas.height / rect.height,
};
}
| true |
Other | mrdoob | three.js | 816ec01e260847437dca4c8c4fb9a6d36ab147fd.json | fix position calculation | threejs/threejs-picking-raycaster-complex-geo.html | @@ -136,8 +136,8 @@
function getCanvasRelativePosition(event) {
const rect = canvas.getBoundingClientRect();
return {
- x: event.clientX - rect.left,
- y: event.clientY - rect.top,
+ x: (event.clientX - rect.left) * canvas.width / rect.width,
+ y: (event.clientY - rect.top ) * canvas.height / rect.height,
};
}
| true |
Other | mrdoob | three.js | 816ec01e260847437dca4c8c4fb9a6d36ab147fd.json | fix position calculation | threejs/threejs-picking-raycaster-transparency.html | @@ -153,15 +153,15 @@
function getCanvasRelativePosition(event) {
const rect = canvas.getBoundingClientRect();
return {
- x: event.clientX - rect.left,
- y: event.clientY - rect.top,
+ x: (event.clientX - rect.left) * canvas.width / rect.width,
+ y: (event.clientY - rect.top ) * canvas.height / rect.height,
};
}
function setPickPosition(event) {
const pos = getCanvasRelativePosition(event);
- pickPosition.x = (pos.x / canvas.clientWidth ) * 2 - 1;
- pickPosition.y = (pos.y / canvas.clientHeight) * -2 + 1; // note we flip Y
+ pickPosition.x = (pos.x / canvas.width ) * 2 - 1;
+ pickPosition.y = (pos.y / canvas.height) * -2 + 1; // note we flip Y
}
function clearPickPosition() { | true |
Other | mrdoob | three.js | 816ec01e260847437dca4c8c4fb9a6d36ab147fd.json | fix position calculation | threejs/threejs-picking-raycaster.html | @@ -146,15 +146,15 @@
function getCanvasRelativePosition(event) {
const rect = canvas.getBoundingClientRect();
return {
- x: event.clientX - rect.left,
- y: event.clientY - rect.top,
+ x: (event.clientX - rect.left) * canvas.width / rect.width,
+ y: (event.clientY - rect.top ) * canvas.height / rect.height,
};
}
function setPickPosition(event) {
const pos = getCanvasRelativePosition(event);
- pickPosition.x = (pos.x / canvas.clientWidth ) * 2 - 1;
- pickPosition.y = (pos.y / canvas.clientHeight) * -2 + 1; // note we flip Y
+ pickPosition.x = (pos.x / canvas.width ) * 2 - 1;
+ pickPosition.y = (pos.y / canvas.height) * -2 + 1; // note we flip Y
}
function clearPickPosition() { | true |
Other | mrdoob | three.js | 816ec01e260847437dca4c8c4fb9a6d36ab147fd.json | fix position calculation | threejs/threejs-tips-preservedrawingbuffer.html | @@ -106,16 +106,16 @@
function getCanvasRelativePosition(event) {
const rect = canvas.getBoundingClientRect();
return {
- x: event.clientX - rect.left,
- y: event.clientY - rect.top,
+ x: (event.clientX - rect.left) * canvas.width / rect.width,
+ y: (event.clientY - rect.top ) * canvas.height / rect.height,
};
}
const temp = new THREE.Vector3();
function setPosition(e) {
const pos = getCanvasRelativePosition(e);
- const x = pos.x / canvas.clientWidth * 2 - 1;
- const y = pos.y / canvas.clientHeight * -2 + 1;
+ const x = pos.x / canvas.width * 2 - 1;
+ const y = pos.y / canvas.height * -2 + 1;
temp.set(x, y, 0).unproject(camera);
state.x = temp.x;
state.y = temp.y; | true |
Other | mrdoob | three.js | 816ec01e260847437dca4c8c4fb9a6d36ab147fd.json | fix position calculation | threejs/threejs-voxel-geometry-culled-faces-ui.html | @@ -512,15 +512,15 @@
function getCanvasRelativePosition(event) {
const rect = canvas.getBoundingClientRect();
return {
- x: event.clientX - rect.left,
- y: event.clientY - rect.top,
+ x: (event.clientX - rect.left) * canvas.width / rect.width,
+ y: (event.clientY - rect.top ) * canvas.height / rect.height,
};
}
function placeVoxel(event) {
const pos = getCanvasRelativePosition(event);
- const x = (pos.x / canvas.clientWidth ) * 2 - 1;
- const y = (pos.y / canvas.clientHeight) * -2 + 1; // note we flip Y
+ const x = (pos.x / canvas.width ) * 2 - 1;
+ const y = (pos.y / canvas.height) * -2 + 1; // note we flip Y
const start = new THREE.Vector3();
const end = new THREE.Vector3(); | true |
Other | mrdoob | three.js | 571aabfdd35f6379b885722ece8e121388ffd932.json | fix slight grammatical error
"Examples would lamps, bowling pins..." I assume this is meant to read "Examples would be: ...") | threejs/lessons/threejs-primitives.md | @@ -29,7 +29,7 @@ primitives.
Here we are extruding a heart shape. Note this is the basis
for <code>TextBufferGeometry</code> and <code>TextGeometry</code> respectively.</div>
<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="LatheBufferGeometry">A shape generated by spinning a line. Examples would be: 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="PlaneBufferGeometry">A 2D plane</div> | false |
Other | mrdoob | three.js | 7b797bb4ead8c9d9d11038365f401835c793af49.json | load external files only on live site | build/templates/analytics.template | @@ -1,10 +1,29 @@
-<script src="//cdn.webglstats.com/stat.js" defer="defer" async="async"></script>
-<script async src="https://www.googletagmanager.com/gtag/js?id=UA-120733518-1"></script>
<script>
- window.dataLayer = window.dataLayer || [];
- function gtag(){dataLayer.push(arguments);}
- gtag('js', new Date());
+(function() {
+ if (window.location.hostname.indexOf("threejsfundamentals.org") < 0) {
+ return;
+ }
- gtag('config', 'UA-120733518-1');
+ function addScript(src, fn) {
+ const script = document.createElement('script');
+ const firstScript = document.getElementsByTag('script')[0];
+ script.async = true;
+ script.defer = true;
+ if (fn) {
+ script.addEventListener('load', fn);
+ }
+ script.src = src;
+ firstScript.parentNode.insertBefore(script, firstScript);
+ }
+
+ addScript('//cdn.webglstats.com/stat.js');
+ addScript('https://www.googletagmanager.com/gtag/js?id=UA-120733518-1', () => {
+ window.dataLayer = window.dataLayer || [];
+ function gtag(){dataLayer.push(arguments);}
+ gtag('js', new Date());
+
+ gtag('config', 'UA-120733518-1');
+ });
+}());
</script>
| false |
Other | mrdoob | three.js | a43ab685966c758c6bb4284e9d9dddcd373b1abf.json | fix fixes from testing with check-all-the-errors | threejs/lessons/ru/threejs-lights.md | @@ -395,7 +395,7 @@ scene.add(light.target);
scene.add(helper);
```
-Угол конуса прожектора задается с помощью свойства [`angle`](Spotlight.angle)
+Угол конуса прожектора задается с помощью свойства [`angle`](SpotLight.angle)
в радианах. Мы будем использовать наш `DegRadHelper` из
[статьи про текстуры](threejs-textures.html) для представления пользовательского интерфейса в градусах..
| true |
Other | mrdoob | three.js | a43ab685966c758c6bb4284e9d9dddcd373b1abf.json | fix fixes from testing with check-all-the-errors | threejs/lessons/ru/threejs-materials.md | @@ -52,7 +52,7 @@ const m5 = new THREE.MeshBasicMaterial({color: 'hsl(0,100%,50%)'); // red
прим. переводчика:
Блик - световое пятно на ярко освещённой выпуклой или плоской глянцевой поверхности.
-[Зеркальное отражение](http://compgraph.tpu.ru/mir_reflection.htm) я часто буду называть бликом,
+[Зеркальное отражение](http://compgraph.tpu.ru/mir_reflection.html) я часто буду называть бликом,
хотя это скорее частный случай.
Итак, давайте рассмотрим набор материалов Three.js. | true |
Other | mrdoob | three.js | a43ab685966c758c6bb4284e9d9dddcd373b1abf.json | fix fixes from testing with check-all-the-errors | threejs/lessons/ru/threejs-textures.md | @@ -448,7 +448,7 @@ Mips - это копии текстуры, каждая из которых в
которые используют 4 или 5 текстур одновременно. 4 текстуры * 8 пикселей на текстуру -
это поиск 32 пикселей для каждого пикселя. Это может быть особенно важно учитывать на мобильных устройствах.
-## <a href="uvmanipulation"></a> Повторение, смещение, вращение, наложение текстуры
+## <a name="uvmanipulation"></a> Повторение, смещение, вращение, наложение текстуры
Текстуры имеют настройки для повторения, смещения и поворота текстуры.
| true |
Other | mrdoob | three.js | a43ab685966c758c6bb4284e9d9dddcd373b1abf.json | fix fixes from testing with check-all-the-errors | threejs/lessons/threejs-align-html-elements-to-3d.md | @@ -409,7 +409,7 @@ where min, max, lat, lon, are all in latitude and longitude degrees.
Let's load it up. The code is based on the examples from [optimizing lots of
objects](threejs-optimize-lots-of-objects.html) though we are not drawing lots
of objects we'll be using the same solutions for [rendering on
-demand](threejs-rendering-on-demand.htm).
+demand](threejs-rendering-on-demand.html).
The first thing is to make a sphere and use the outline texture.
| true |
Other | mrdoob | three.js | a43ab685966c758c6bb4284e9d9dddcd373b1abf.json | fix fixes from testing with check-all-the-errors | threejs/lessons/threejs-debugging-javascript.md | @@ -18,7 +18,7 @@ enormously in your learning.
All browsers have developer tools.
[Chrome](https://developers.google.com/web/tools/chrome-devtools/),
-[Firefox](https://developer.mozilla.org/son/docs/Tools),
+[Firefox](https://developer.mozilla.org/en-US/docs/Tools),
[Safari](https://developer.apple.com/safari/tools/),
[Edge](https://docs.microsoft.com/en-us/microsoft-edge/devtools-guide).
| true |
Other | mrdoob | three.js | a43ab685966c758c6bb4284e9d9dddcd373b1abf.json | fix fixes from testing with check-all-the-errors | threejs/lessons/threejs-game.md | @@ -1563,7 +1563,7 @@ things. To do that I made a `StatusDisplayHelper` component.
I uses a `PolarGridHelper` to draw a circle around each character
and it uses html elements to let each character show some status using
-the techniques covered in [the article on aligning html elements to 3D](threejs-align-html-elements-to-3d).
+the techniques covered in [the article on aligning html elements to 3D](threejs-align-html-elements-to-3d.html).
First we need to add some HTML to host these elements
| true |
Other | mrdoob | three.js | a43ab685966c758c6bb4284e9d9dddcd373b1abf.json | fix fixes from testing with check-all-the-errors | threejs/lessons/threejs-indexed-textures.md | @@ -262,7 +262,7 @@ but what about highlighting the selected countries?
For that we can take inspiration from *paletted graphics*.
-[Paletted graphics](https://en.wikipedia.org/wiki/Palette_(computing))
+[Paletted graphics](https://en.wikipedia.org/wiki/Palette_%28computing%29)
or [Indexed Color](https://en.wikipedia.org/wiki/Indexed_color) is
what older systems like the Atari 800, Amiga, NES,
Super Nintendo, and even older IBM PCs used. Instead of storing bitmaps | true |
Other | mrdoob | three.js | a43ab685966c758c6bb4284e9d9dddcd373b1abf.json | fix fixes from testing with check-all-the-errors | threejs/lessons/threejs-lights.md | @@ -400,7 +400,7 @@ scene.add(light.target);
scene.add(helper);
```
-The spotlight's cone's angle is set with the [`angle`](Spotlight.angle)
+The spotlight's cone's angle is set with the [`angle`](SpotLight.angle)
property in radians. We'll use our `DegRadHelper` from the
[texture article](threejs-textures.html) to present a UI in
degrees. | true |
Other | mrdoob | three.js | a43ab685966c758c6bb4284e9d9dddcd373b1abf.json | fix fixes from testing with check-all-the-errors | threejs/lessons/threejs-offscreencanvas.md | @@ -614,7 +614,7 @@ 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/gfxfundamentals/threejsfundamentals/blob/master/threejs/resources/threejs/r112/js/controls/OrbitControls.js)
+Digging through the [OrbitControls source code](https://github.com/gfxfundamentals/threejsfundamentals/blob/master/threejs/resources/threejs/r112/examples/js/controls/OrbitControls.js)
it looks like we need to handle the following events.
* contextmenu | true |
Other | mrdoob | three.js | a43ab685966c758c6bb4284e9d9dddcd373b1abf.json | fix fixes from testing with check-all-the-errors | threejs/lessons/threejs-optimize-lots-of-objects.md | @@ -18,7 +18,7 @@ re-create the [WebGL Globe](https://globe.chromeexperiments.com/).
The first thing we need to do is get some data. The WebGL Globe said the data
they use comes from [SEDAC](http://sedac.ciesin.columbia.edu/gpw/). Checking out
the site I saw there was [demographic data in a grid
-format](http://sedac.ciesin.columbia.edu/data/set/gpw-v4-basic-demographic-characteristics-rev10).
+format](https://beta.sedac.ciesin.columbia.edu/data/set/gpw-v4-basic-demographic-characteristics-rev10).
I downloaded the data at 60 minute resolution. Then I took a look at the data
It looks like this
@@ -256,7 +256,7 @@ didn't do this it would scale from the center but we want them to grow away from
</div>
Of course we could also solve that by parenting the box to more `THREE.Object3D`
-objects like we covered in [scene graphs](threejs-scenegraphs.html) but the more
+objects like we covered in [scene graphs](threejs-scenegraph.html) but the more
nodes we add to a scene graph the slower it gets.
We also setup this small hierarchy of nodes of `lonHelper`, `latHelper`, and | true |
Other | mrdoob | three.js | a43ab685966c758c6bb4284e9d9dddcd373b1abf.json | fix fixes from testing with check-all-the-errors | threejs/lessons/threejs-prerequisites.md | @@ -138,7 +138,7 @@ for (const [key, value] of Object.entries(someObject)) {
### Use `forEach`, `map`, and `filter` where useful
-Arrays added the functions [`forEach`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach,
+Arrays added the functions [`forEach`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach),
[`map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map), and
[`filter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) and
are used fairly extensively in modern JavaScript. | true |
Other | mrdoob | three.js | a43ab685966c758c6bb4284e9d9dddcd373b1abf.json | fix fixes from testing with check-all-the-errors | threejs/lessons/threejs-textures.md | @@ -456,7 +456,7 @@ we'll eventually have materials that use 4 or 5 textures all at once. 4 textures
pixels per texture is looking up 32 pixels for ever pixel rendered.
This can be especially important to consider on mobile devices.
-## <a href="uvmanipulation"></a> Repeating, offseting, rotating, wrapping a texture
+## <a name="uvmanipulation"></a> Repeating, offseting, rotating, wrapping a texture
Textures have settings for repeating, offseting, and rotating a texture.
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.