language stringclasses 1
value | owner stringlengths 2 15 | repo stringlengths 2 21 | sha stringlengths 45 45 | message stringlengths 7 36.3k | path stringlengths 1 199 | patch stringlengths 15 102k | is_multipart bool 2
classes |
|---|---|---|---|---|---|---|---|
Other | mrdoob | three.js | fd0c00def8dbb57efdceb91b87f95988d0d5af85.json | remove un-needed categories | threejs/lessons/ru/threejs-lights.md | @@ -1,6 +1,5 @@
Title: Three.js - Освещение
Description: Настройка освещения
-Category: fundamentals
TOC: Освещение
Эта статья является частью серии статей о three.js. | true |
Other | mrdoob | three.js | fd0c00def8dbb57efdceb91b87f95988d0d5af85.json | remove un-needed categories | threejs/lessons/ru/threejs-material-table.md | @@ -1,6 +1,5 @@
Title: Таблица характеристик материалов
Description: Таблица, показывающая, какие функции поддерживают каждый из материалов
-Category: reference
TOC: Таблица материалов
Наиболее распространенными материалами в three.js являются материалы | true |
Other | mrdoob | three.js | fd0c00def8dbb57efdceb91b87f95988d0d5af85.json | remove un-needed categories | threejs/lessons/ru/threejs-materials.md | @@ -1,6 +1,5 @@
Title: Материалы Three.js
Description: Материалы в Three.js
-Category: fundamentals
TOC: Материалы
Эта статья является частью серии статей о three.js. | true |
Other | mrdoob | three.js | fd0c00def8dbb57efdceb91b87f95988d0d5af85.json | remove un-needed categories | threejs/lessons/ru/threejs-multiple-scenes.md | @@ -1,6 +1,5 @@
Title: Three.js - Несколько холстов и Несколько сцен
Description: Kак рисовать на всей web-странице с THREE.js
-Category: solutions
TOC: Несколько холстов, несколько сцен
Допустим, вы хотите создать сайт электронной коммерции или сделать | true |
Other | mrdoob | three.js | fd0c00def8dbb57efdceb91b87f95988d0d5af85.json | remove un-needed categories | threejs/lessons/ru/threejs-primitives.md | @@ -1,6 +1,5 @@
Title: Примитивы Three.js
Description: Обзор примитивов three.js.
-Category: fundamentals
TOC: Примитивы
Эта статья является частью серии статей о three.js. | true |
Other | mrdoob | three.js | fd0c00def8dbb57efdceb91b87f95988d0d5af85.json | remove un-needed categories | threejs/lessons/ru/threejs-responsive.md | @@ -1,6 +1,5 @@
Title: Three.js Oтзывчивый Дизайн
Description: Как приспособить three.js под дисплеи разного размера.
-Category: basics
TOC: Адаптивный дизайн
Это вторая статья в серии статей о three.js. | true |
Other | mrdoob | three.js | fd0c00def8dbb57efdceb91b87f95988d0d5af85.json | remove un-needed categories | threejs/lessons/ru/threejs-scenegraph.md | @@ -1,6 +1,5 @@
Title: Граф сцены Three.js
Description: Что такое граф сцены?
-Category: fundamentals
TOC: Граф сцены
Эта статья является частью серии статей о three.js. | true |
Other | mrdoob | three.js | fd0c00def8dbb57efdceb91b87f95988d0d5af85.json | remove un-needed categories | threejs/lessons/ru/threejs-setup.md | @@ -1,6 +1,5 @@
Title: Настройка окружения Three.js
Description: Как настроить разрабочее окружение для Three.js
-Category: basics
TOC: Настройка
Эта статья является частью серии статей о three.js. | true |
Other | mrdoob | three.js | fd0c00def8dbb57efdceb91b87f95988d0d5af85.json | remove un-needed categories | threejs/lessons/ru/threejs-textures.md | @@ -1,6 +1,5 @@
Title: Three.js Текстуры
Description: Использование текстур в three.js
-Category: fundamentals
TOC: Текстуры
Эта статья является частью серии статей о three.js. | true |
Other | mrdoob | three.js | fd0c00def8dbb57efdceb91b87f95988d0d5af85.json | remove un-needed categories | threejs/lessons/threejs-align-html-elements-to-3d.md | @@ -1,6 +1,5 @@
Title: Three.js Aligning HTML Elements to 3D
Description: How to line up an HTML Element to match a point in 3D space
-Category: solutions
TOC: Aligning HTML Elements to 3D
This article is part of a series of articles about three.js. The first article | true |
Other | mrdoob | three.js | fd0c00def8dbb57efdceb91b87f95988d0d5af85.json | remove un-needed categories | threejs/lessons/threejs-backgrounds.md | @@ -1,6 +1,5 @@
Title: Three.js Backgrounds and Skyboxes
Description: How to add a background in THREE.js
-Category: solutions
TOC: Add a Background or Skybox
Most of the articles here use a solid color for a background. | true |
Other | mrdoob | three.js | fd0c00def8dbb57efdceb91b87f95988d0d5af85.json | remove un-needed categories | threejs/lessons/threejs-billboards.md | @@ -1,6 +1,5 @@
Title: Three.js Billboards
Description: How to make things always face the camera.
-Category: solutions
TOC: Billboards and Facades
In [a previous article](threejs-canvas-textures.html) we used a `CanvasTexture` | true |
Other | mrdoob | three.js | fd0c00def8dbb57efdceb91b87f95988d0d5af85.json | remove un-needed categories | threejs/lessons/threejs-cameras.md | @@ -1,6 +1,5 @@
Title: Three.js Cameras
Description: How to use Cameras in Three.js
-Category: fundamentals
TOC: Cameras
This article is one in a series of articles about three.js. | true |
Other | mrdoob | three.js | fd0c00def8dbb57efdceb91b87f95988d0d5af85.json | remove un-needed categories | threejs/lessons/threejs-canvas-textures.md | @@ -1,6 +1,5 @@
Title: Three.js Canvas Textures
Description: How to use a canvas as a texture in Three.js
-Category: solutions
TOC: Using A Canvas for Dynamic Textures
This article continues from [the article on textures](threejs-textures.html). | true |
Other | mrdoob | three.js | fd0c00def8dbb57efdceb91b87f95988d0d5af85.json | remove un-needed categories | threejs/lessons/threejs-cleanup.md | @@ -1,6 +1,5 @@
Title: Three.js Cleanup
Description: How to use free memory used by Three.js
-Category: solutions
TOC: Freeing Resources
Three.js apps often use lots of memory. A 3D model | true |
Other | mrdoob | three.js | fd0c00def8dbb57efdceb91b87f95988d0d5af85.json | remove un-needed categories | threejs/lessons/threejs-custom-buffergeometry.md | @@ -1,6 +1,5 @@
Title: Three.js Custom BufferGeometry
Description: How to make your own BufferGeometry.
-Category: fundamentals
TOC: Custom BufferGeometry
A [previous article](threejs-custom-geometry.html) covered | true |
Other | mrdoob | three.js | fd0c00def8dbb57efdceb91b87f95988d0d5af85.json | remove un-needed categories | threejs/lessons/threejs-custom-geometry.md | @@ -1,6 +1,5 @@
Title: Three.js Custom Geometry
Description: How to make your own geometry.
-Category: fundamentals
TOC: Custom Geometry
A [previous article](threejs-primitives.html) gave a tour of | true |
Other | mrdoob | three.js | fd0c00def8dbb57efdceb91b87f95988d0d5af85.json | remove un-needed categories | threejs/lessons/threejs-debugging-glsl.md | @@ -1,6 +1,5 @@
Title: Debugging Three.js - GLSL
Description: How to debug GLSL Shaders
-Category: tips
TOC: Debugging GLSL
This site so far does not teach GLSL just like it does not teach JavaScript. | true |
Other | mrdoob | three.js | fd0c00def8dbb57efdceb91b87f95988d0d5af85.json | remove un-needed categories | threejs/lessons/threejs-debugging-javascript.md | @@ -1,6 +1,5 @@
Title: Three.js Debugging JavaScript
Description: How to debug JavaScript with THREE.js
-Category: tips
TOC: Debugging JavaScript
Most of this article is not directly about THREE.js but is | true |
Other | mrdoob | three.js | fd0c00def8dbb57efdceb91b87f95988d0d5af85.json | remove un-needed categories | threejs/lessons/threejs-fog.md | @@ -1,6 +1,5 @@
Title: Three.js Fog
Description: Fog in Three.js
-Category: fundamentals
TOC: Fog
This article is part of a series of articles about three.js. The | true |
Other | mrdoob | three.js | fd0c00def8dbb57efdceb91b87f95988d0d5af85.json | remove un-needed categories | threejs/lessons/threejs-fundamentals.md | @@ -1,6 +1,5 @@
Title: Three.js Fundamentals
Description: Your first Three.js lesson starting with the fundamentals
-Category: basics
TOC: Fundamentals
This is the first article in a series of articles about three.js. | true |
Other | mrdoob | three.js | fd0c00def8dbb57efdceb91b87f95988d0d5af85.json | remove un-needed categories | threejs/lessons/threejs-indexed-textures.md | @@ -1,6 +1,5 @@
Title: Three.js Indexed Textures for Picking and Color
Description: Using Indexed Textures for Picking and Color
-Category: solutions
TOC: Using Indexed Textures for Picking and Color
This article is a continuation of [an article about aligning html elements to 3d](threejs-align-html-elements-to-3d.html). | true |
Other | mrdoob | three.js | fd0c00def8dbb57efdceb91b87f95988d0d5af85.json | remove un-needed categories | threejs/lessons/threejs-lights.md | @@ -1,6 +1,5 @@
Title: Three.js Lights
Description: Setting up Lights
-Category: fundamentals
TOC: Lights
This article is part of a series of articles about three.js. The | true |
Other | mrdoob | three.js | fd0c00def8dbb57efdceb91b87f95988d0d5af85.json | remove un-needed categories | threejs/lessons/threejs-load-gltf.md | @@ -1,6 +1,5 @@
Title: Three.js Loading a .GLTF File
Description: Loading a .GLTF File
-Category: solutions
TOC: Load a .GLTF file
In a previous lesson we [loaded an .OBJ file](threejs-load-obj.html). If | true |
Other | mrdoob | three.js | fd0c00def8dbb57efdceb91b87f95988d0d5af85.json | remove un-needed categories | threejs/lessons/threejs-load-obj.md | @@ -1,6 +1,5 @@
Title: Three.js Loading a .OBJ File
Description: Loading a .OBJ File
-Category: solutions
TOC: Load an .OBJ file
One of the most common things people want to do with three.js | true |
Other | mrdoob | three.js | fd0c00def8dbb57efdceb91b87f95988d0d5af85.json | remove un-needed categories | threejs/lessons/threejs-material-table.md | @@ -1,6 +1,5 @@
Title: Material Feature Table
Description: A Table showing which matierals have which features
-Category: reference
TOC: Material Table
The most common materials in three.js are the Mesh materials. Here | true |
Other | mrdoob | three.js | fd0c00def8dbb57efdceb91b87f95988d0d5af85.json | remove un-needed categories | threejs/lessons/threejs-materials.md | @@ -1,6 +1,5 @@
Title: Three.js Materials
Description: Materials in Three.js
-Category: fundamentals
TOC: Materials
This article is part of a series of articles about three.js. The | true |
Other | mrdoob | three.js | fd0c00def8dbb57efdceb91b87f95988d0d5af85.json | remove un-needed categories | threejs/lessons/threejs-multiple-scenes.md | @@ -1,6 +1,5 @@
Title: Three.js Multiple Canvases Multiple Scenes
Description: How to draw stuff all over the page with THREE.js
-Category: solutions
TOC: Multiple Canvases, Multiple Scenes
A common question is how to use THREE.js with multiple canvases. | true |
Other | mrdoob | three.js | fd0c00def8dbb57efdceb91b87f95988d0d5af85.json | remove un-needed categories | threejs/lessons/threejs-offscreencanvas.md | @@ -1,6 +1,5 @@
Title: Three.js OffscreenCanvas
Description: How to use three.js in a web worker
-Category: optimization
TOC: Using OffscreenCanvas in a Web Worker
[`OffscreenCanvas`](https://developer.mozilla.org/en-US/docs/Web/API/OffscreenCanvas) | true |
Other | mrdoob | three.js | fd0c00def8dbb57efdceb91b87f95988d0d5af85.json | remove un-needed categories | threejs/lessons/threejs-optimize-lots-of-objects-animated.md | @@ -1,6 +1,5 @@
Title: Three.js Optimize Lots of Objects Animated
Description: Animated merged objects with Morphtargets
-Category: optimization
TOC: Optimizing Lots of Objects Animated
This article is a continuation of [an article about optimizing lots of objects | true |
Other | mrdoob | three.js | fd0c00def8dbb57efdceb91b87f95988d0d5af85.json | remove un-needed categories | threejs/lessons/threejs-optimize-lots-of-objects.md | @@ -1,6 +1,5 @@
Title: Three.js Optimize Lots of Objects
Description: Optimize by merging Objects
-Category: optimization
TOC: Optimizing Lots of Objects
This article is part of a series of articles about three.js. The first article | true |
Other | mrdoob | three.js | fd0c00def8dbb57efdceb91b87f95988d0d5af85.json | remove un-needed categories | threejs/lessons/threejs-picking.md | @@ -1,6 +1,5 @@
Title: Three.js Picking
Description: Selecting Objects with the Mouse in Three.js
-Category: solutions
TOC: Picking Objects with the mouse
*Picking* refers to the process of figuring out which object a user clicked on or touched. There are tons of ways to implement picking each with their tradeoffs. Let's go over the 2 most common. | true |
Other | mrdoob | three.js | fd0c00def8dbb57efdceb91b87f95988d0d5af85.json | remove un-needed categories | threejs/lessons/threejs-post-processing-3dlut.md | @@ -1,6 +1,5 @@
Title: Three.js Post Processing 3DLUT
Description: How to implement a 3DLUT Post Process in THREE.js
-Category: solutions
TOC: Applying a LUT File for effects
In the last article we went over [post processing](threejs-post-processing.html). | true |
Other | mrdoob | three.js | fd0c00def8dbb57efdceb91b87f95988d0d5af85.json | remove un-needed categories | threejs/lessons/threejs-post-processing.md | @@ -1,6 +1,5 @@
Title: Three.js Post Processing
Description: How to Post Process in THREE.js
-Category: solutions
TOC: Post Processing
*Post processing* generally refers to applying some kind of effect or filter to | true |
Other | mrdoob | three.js | fd0c00def8dbb57efdceb91b87f95988d0d5af85.json | remove un-needed categories | threejs/lessons/threejs-prerequisites.md | @@ -1,6 +1,5 @@
Title: Three.js Prerequisites
Description: What you need to know to use this site.
-Category: basics
TOC: Prerequisites
These articles are meant to help you learn how to use three.js. | true |
Other | mrdoob | three.js | fd0c00def8dbb57efdceb91b87f95988d0d5af85.json | remove un-needed categories | threejs/lessons/threejs-primitives.md | @@ -1,6 +1,5 @@
Title: Three.js Primitives
Description: A tour of three.js primitives.
-Category: fundamentals
TOC: Primitives
This article is one in a series of articles about three.js. | true |
Other | mrdoob | three.js | fd0c00def8dbb57efdceb91b87f95988d0d5af85.json | remove un-needed categories | threejs/lessons/threejs-rendering-on-demand.md | @@ -1,6 +1,5 @@
Title: Three.js Rendering on Demand
Description: How to use less energy.
-Category: tips
TOC: Rendering On Demand
The topic might be obvious to many people but just in case ... most Three.js | true |
Other | mrdoob | three.js | fd0c00def8dbb57efdceb91b87f95988d0d5af85.json | remove un-needed categories | threejs/lessons/threejs-rendertargets.md | @@ -1,6 +1,5 @@
Title: Three.js Render Targets
Description: How to render to a texture.
-Category: fundamentals
TOC: Render Targets
A render target in three.js is basicaly a texture you can render to. | true |
Other | mrdoob | three.js | fd0c00def8dbb57efdceb91b87f95988d0d5af85.json | remove un-needed categories | threejs/lessons/threejs-responsive.md | @@ -1,6 +1,5 @@
Title: Three.js Responsive Design
Description: How to make your three.js fit different sized displays.
-Category: basics
TOC: Responsive Design
This is the second article in a series of articles about three.js. | true |
Other | mrdoob | three.js | fd0c00def8dbb57efdceb91b87f95988d0d5af85.json | remove un-needed categories | threejs/lessons/threejs-scenegraph.md | @@ -1,6 +1,5 @@
Title: Three.js Scene Graph
Description: What's a scene graph?
-Category: fundamentals
TOC: Scenegraph
This article is part of a series of articles about three.js. The | true |
Other | mrdoob | three.js | fd0c00def8dbb57efdceb91b87f95988d0d5af85.json | remove un-needed categories | threejs/lessons/threejs-setup.md | @@ -1,6 +1,5 @@
Title: Three.js Setup
Description: How to setup your development environment for three.js
-Category: basics
TOC: Setup
This article is one in a series of articles about three.js. | true |
Other | mrdoob | three.js | fd0c00def8dbb57efdceb91b87f95988d0d5af85.json | remove un-needed categories | threejs/lessons/threejs-shadertoy.md | @@ -1,6 +1,5 @@
Title: Three.js and Shadertoy
Description: How to use Shadertoy shaders in THREE.js
-Category: solutions
TOC: Using Shadertoy shaders
[Shadertoy](https://shadertoy.com) is a famous website hosting amazing shader experiments. People often ask how they can use those shaders with Three.js. | true |
Other | mrdoob | three.js | fd0c00def8dbb57efdceb91b87f95988d0d5af85.json | remove un-needed categories | threejs/lessons/threejs-shadows.md | @@ -1,6 +1,5 @@
Title: Three.js Shadows
Description: Shadows in Three.js
-Category: fundamentals
TOC: Shadows
This article is part of a series of articles about three.js. The | true |
Other | mrdoob | three.js | fd0c00def8dbb57efdceb91b87f95988d0d5af85.json | remove un-needed categories | threejs/lessons/threejs-textures.md | @@ -1,6 +1,5 @@
Title: Three.js Textures
Description: Using textures in three.js
-Category: fundamentals
TOC: Textures
This article is one in a series of articles about three.js. | true |
Other | mrdoob | three.js | fd0c00def8dbb57efdceb91b87f95988d0d5af85.json | remove un-needed categories | threejs/lessons/threejs-tips.md | @@ -1,6 +1,5 @@
Title: Three.js Tips
Description: Small issues that might trip you up using three.js
-Category: tips
TOC: #
This article is a collection of small issues you might run into | true |
Other | mrdoob | three.js | fd0c00def8dbb57efdceb91b87f95988d0d5af85.json | remove un-needed categories | threejs/lessons/threejs-transparency.md | @@ -1,6 +1,5 @@
Title: Three.js Transparency
Description: How to deal with transparency issues in THREE.js
-Category: solutions
TOC: How to Draw Transparent Objects
Transparency in three.js is both easy and hard. | true |
Other | mrdoob | three.js | fd0c00def8dbb57efdceb91b87f95988d0d5af85.json | remove un-needed categories | threejs/lessons/threejs-voxel-geometry.md | @@ -1,6 +1,5 @@
Title: Three.js Voxel(Minecraft Like) Geometry
Description: How to make voxel geometry like Minecraft
-Category: solutions
TOC: Making Voxel Geometry (Minecraft)
I've seen this topic come up more than once in various places. | true |
Other | mrdoob | three.js | fd0c00def8dbb57efdceb91b87f95988d0d5af85.json | remove un-needed categories | threejs/lessons/threejs-webvr-look-to-select.md | @@ -1,6 +1,5 @@
Title: Three.js WebVR - Look to Select
Description: How to implement Look to Select.
-Category: webvr
TOC: WebVR - Look To Select
**NOTE: The examples on this page require a VR capable | true |
Other | mrdoob | three.js | fd0c00def8dbb57efdceb91b87f95988d0d5af85.json | remove un-needed categories | threejs/lessons/threejs-webvr-point-to-select.md | @@ -1,6 +1,5 @@
Title: Three.js WebVR - 3DOF Point to Select
Description: How to implement 3DOF Point to Select.
-Category: webvr
TOC: WebVR - Point To Select
**NOTE: The examples on this page require a VR capable | true |
Other | mrdoob | three.js | fd0c00def8dbb57efdceb91b87f95988d0d5af85.json | remove un-needed categories | threejs/lessons/threejs-webvr.md | @@ -1,6 +1,5 @@
Title: Three.js WebVR
Description: How to use Virtual Reality in Three.js.
-Category: webvr
TOC: WebVR - Basics
Making WebVR apps in three.js is pretty simple. You basically just have to tell | true |
Other | mrdoob | three.js | fd0c00def8dbb57efdceb91b87f95988d0d5af85.json | remove un-needed categories | threejs/lessons/zh_cn/threejs-fundamentals.md | @@ -1,6 +1,5 @@
Title: Three.js基础
Description: 学习Three.js的第一篇文章
-Category: basics
TOC: 基础
这是Three.js系列文章的第一篇。 | true |
Other | mrdoob | three.js | fd0c00def8dbb57efdceb91b87f95988d0d5af85.json | remove un-needed categories | threejs/lessons/zh_cn/threejs-prerequisites.md | @@ -1,6 +1,5 @@
Title: Three.js先决条件
Description: 使用此网站你需要了解的。
-Category: basics
TOC: 先决条件
这些文章意在帮助你学习如何使用three.js。 | true |
Other | mrdoob | three.js | fd0c00def8dbb57efdceb91b87f95988d0d5af85.json | remove un-needed categories | threejs/lessons/zh_cn/threejs-responsive.md | @@ -1,6 +1,5 @@
Title: Three.js响应式设计
Description: 如何让你的three.js适应不同尺寸的显示器。
-Category: basics
TOC: 响应式设计
这是three.js系列文章的第二篇。 | true |
Other | mrdoob | three.js | fd0c00def8dbb57efdceb91b87f95988d0d5af85.json | remove un-needed categories | threejs/lessons/zh_cn/threejs-setup.md | @@ -1,6 +1,5 @@
Title: Three.js设置
Description: 如何为你的three.js设置开发环境
-Category: basics
TOC: 设置
这是three.js系列文章的其中之一。 | true |
Other | mrdoob | three.js | 3e4551bb559a9a2e337f14603cf7c6d3bb675a1e.json | use shared builder | Gruntfile.js | @@ -129,22 +129,18 @@ module.exports = function(grunt) {
filenames.add(filename);
});
});
- const buildStuff = require('./build/js/build');
+ const buildStuff = require('@gfxfundamentals/lesson-builder');
const settings = Object.assign({}, buildSettings, {
filenames,
});
const finish = this.async();
- buildStuff(settings).then(function() {
- finish();
- }).done();
+ buildStuff(settings).finally(finish);
});
grunt.registerTask('buildlessons', function() {
- const buildStuff = require('./build/js/build');
+ const buildStuff = require('@gfxfundamentals/lesson-builder');
const finish = this.async();
- buildStuff(buildSettings).then(function() {
- finish();
- }).done();
+ buildStuff(buildSettings).finally(finish);
});
grunt.task.registerMultiTask('fixthreepaths', 'fix three paths', function() { | true |
Other | mrdoob | three.js | 3e4551bb559a9a2e337f14603cf7c6d3bb675a1e.json | use shared builder | build/js/build.js | @@ -1,921 +0,0 @@
-/* global module require process */
-/* eslint no-undef: "error" */
-/* eslint no-console: "off" */
-
-/*
-
-This entire file is one giant hack and really needs to be cleaned up!
-
-*/
-
-'use strict';
-
-const requiredNodeVersion = 12;
-if (parseInt((/^v(\d+)\./).exec(process.version)[1]) < requiredNodeVersion) {
- throw Error(`requires at least node: ${requiredNodeVersion}`);
-}
-
-module.exports = function(settings) { // wrapper in case we're in module_context mode
-
-const hackyProcessSelectFiles = settings.filenames !== undefined;
-
-const cache = new (require('inmemfilecache'))();
-const Feed = require('feed').Feed;
-const fs = require('fs');
-const glob = require('glob');
-const Handlebars = require('handlebars');
-const hanson = require('hanson');
-const marked = require('marked');
-const path = require('path');
-const Promise = require('promise');
-const sitemap = require('sitemap');
-const utils = require('./utils');
-const moment = require('moment');
-const url = require('url');
-
-//process.title = 'build';
-
-let numErrors = 0;
-function error(...args) {
- ++numErrors;
- console.error(...args);
-}
-
-const executeP = Promise.denodeify(utils.execute);
-
-marked.setOptions({
- rawHtml: true,
- //pedantic: true,
-});
-
-function applyObject(src, dst) {
- Object.keys(src).forEach(function(key) {
- dst[key] = src[key];
- });
- return dst;
-}
-
-function mergeObjects() {
- const merged = {};
- Array.prototype.slice.call(arguments).forEach(function(src) {
- applyObject(src, merged);
- });
- return merged;
-}
-
-function readFile(fileName) {
- try {
- return cache.readFileSync(fileName, 'utf-8');
- } catch (e) {
- console.error('could not read:', fileName);
- throw e;
- }
-}
-
-function readHANSON(fileName) {
- const text = readFile(fileName);
- try {
- return hanson.parse(text);
- } catch (e) {
- throw new Error(`can not parse: ${fileName}: ${e}`);
- }
-}
-
-function writeFileIfChanged(fileName, content) {
- if (fs.existsSync(fileName)) {
- const old = readFile(fileName);
- if (content === old) {
- return;
- }
- }
- fs.writeFileSync(fileName, content);
- console.log('Wrote: ' + fileName); // eslint-disable-line
-}
-
-function copyFile(src, dst) {
- writeFileIfChanged(dst, readFile(src));
-}
-
-function replaceParams(str, params) {
- const template = Handlebars.compile(str);
- if (Array.isArray(params)) {
- params = mergeObjects.apply(null, params.slice().reverse());
- }
-
- return template(params);
-}
-
-function encodeParams(params) {
- const values = Object.values(params).filter(v => v);
- if (!values.length) {
- return '';
- }
- return '&' + Object.entries(params).map((kv) => {
- return `${encodeURIComponent(kv[0])}=${encodeURIComponent(kv[1])}`;
- }).join('&');
-}
-
-function encodeQuery(query) {
- if (!query) {
- return '';
- }
- return '?' + query.split('&').map(function(pair) {
- return pair.split('=').map(function(kv) {
- return encodeURIComponent(decodeURIComponent(kv));
- }).join('=');
- }).join('&');
-}
-
-function encodeUrl(src) {
- const u = url.parse(src);
- u.search = encodeQuery(u.query);
- return url.format(u);
-}
-
-function TemplateManager() {
- const templates = {};
-
- this.apply = function(filename, params) {
- let template = templates[filename];
- if (!template) {
- template = Handlebars.compile(readFile(filename));
- templates[filename] = template;
- }
-
- if (Array.isArray(params)) {
- params = mergeObjects.apply(null, params.slice().reverse());
- }
-
- return template(params);
- };
-}
-
-const templateManager = new TemplateManager();
-
-Handlebars.registerHelper('include', function(filename, options) {
- let context;
- if (options && options.hash && options.hash.filename) {
- const varName = options.hash.filename;
- filename = options.data.root[varName];
- context = Object.assign({}, options.data.root, options.hash);
- } else {
- context = options.data.root;
- }
- return templateManager.apply(filename, context);
-});
-
-Handlebars.registerHelper('example', function(options) {
- options.hash.width = options.hash.width ? 'width: ' + options.hash.width + 'px;' : '';
- options.hash.height = options.hash.height ? 'height: ' + options.hash.height + 'px;' : '';
- options.hash.caption = options.hash.caption || options.data.root.defaultExampleCaption;
- options.hash.examplePath = options.data.root.examplePath;
- options.hash.encodedUrl = encodeURIComponent(encodeUrl(options.hash.url));
- options.hash.url = encodeUrl(options.hash.url);
- options.hash.params = encodeParams({
- startPane: options.hash.startPane,
- });
- return templateManager.apply('build/templates/example.template', options.hash);
-});
-
-Handlebars.registerHelper('diagram', function(options) {
-
- options.hash.width = options.hash.width || '400';
- options.hash.height = options.hash.height || '300';
- options.hash.examplePath = options.data.root.examplePath;
- options.hash.className = options.hash.className || '';
- options.hash.url = encodeUrl(options.hash.url);
-
- return templateManager.apply('build/templates/diagram.template', options.hash);
-});
-
-Handlebars.registerHelper('image', function(options) {
-
- options.hash.examplePath = options.data.root.examplePath;
- options.hash.className = options.hash.className || '';
- options.hash.caption = options.hash.caption || undefined;
-
- if (options.hash.url.substring(0, 4) === 'http') {
- options.hash.examplePath = '';
- }
-
- return templateManager.apply('build/templates/image.template', options.hash);
-});
-
-Handlebars.registerHelper('selected', function(options) {
- const key = options.hash.key;
- const value = options.hash.value;
- const re = options.hash.re;
- const sub = options.hash.sub;
-
- const a = this[key];
- let b = options.data.root[value];
-
- if (re) {
- const r = new RegExp(re);
- b = b.replace(r, sub);
- }
-
- return a === b ? 'selected' : '';
-});
-
-function slashify(s) {
- return s.replace(/\\/g, '/');
-}
-
-function articleFilter(f) {
- if (hackyProcessSelectFiles) {
- if (!settings.filenames.has(f)) {
- return false;
- }
- }
- return !process.env['ARTICLE_FILTER'] || f.indexOf(process.env['ARTICLE_FILTER']) >= 0;
-}
-
-const Builder = function(outBaseDir, options) {
-
- const g_articlesByLang = {};
- let g_articles = [];
- let g_langInfo;
- let g_originalLangInfo;
- const g_langDB = {};
- const g_outBaseDir = outBaseDir;
- const g_origPath = options.origPath;
- const g_originalByFileName = {};
-
- const toc = readHANSON('toc.hanson');
-
- // These are the english articles.
- const g_origArticles = glob.sync(path.join(g_origPath, '*.md'))
- .map(a => path.basename(a))
- .filter(a => a !== 'index.md')
- .filter(articleFilter);
-
- const extractHeader = (function() {
- const headerRE = /([A-Z0-9_-]+): (.*?)$/i;
-
- return function(content) {
- const metaData = { };
- const lines = content.split('\n');
- for (;;) {
- const line = lines[0].trim();
- const m = headerRE.exec(line);
- if (!m) {
- break;
- }
- metaData[m[1].toLowerCase()] = m[2];
- lines.shift();
- }
- return {
- content: lines.join('\n'),
- headers: metaData,
- };
- };
- }());
-
- const parseMD = function(content) {
- return extractHeader(content);
- };
-
- const loadMD = function(contentFileName) {
- const content = cache.readFileSync(contentFileName, 'utf-8');
- const data = parseMD(content);
- data.link = contentFileName.replace(/\\/g, '/').replace(/\.md$/, '.html');
- return data;
- };
-
- function extractHandlebars(content) {
- const tripleRE = /\{\{\{.*?\}\}\}/g;
- const doubleRE = /\{\{\{.*?\}\}\}/g;
-
- let numExtractions = 0;
- const extractions = {
- };
-
- function saveHandlebar(match) {
- const id = '==HANDLEBARS_ID_' + (++numExtractions) + '==';
- extractions[id] = match;
- return id;
- }
-
- content = content.replace(tripleRE, saveHandlebar);
- content = content.replace(doubleRE, saveHandlebar);
-
- return {
- content: content,
- extractions: extractions,
- };
- }
-
- function insertHandlebars(info, content) {
- const handlebarRE = /==HANDLEBARS_ID_\d+==/g;
-
- function restoreHandlebar(match) {
- const value = info.extractions[match];
- if (value === undefined) {
- throw new Error('no match restoring handlebar for: ' + match);
- }
- return value;
- }
-
- content = content.replace(handlebarRE, restoreHandlebar);
-
- return content;
- }
-
- function isSameDomain(url, pageUrl) {
- const fdq1 = new URL(pageUrl);
- const fdq2 = new URL(url, pageUrl);
- return fdq1.origin === fdq2.origin;
- }
-
- function getUrlPath(url) {
- // yes, this is a hack
- const q = url.indexOf('?');
- return q >= 0 ? url.substring(0, q) : url;
- }
-
- // Try top fix relative links. This *should* only
- // happen in translations
- const iframeLinkRE = /(<iframe[\s\S]*?\s+src=")(.*?)(")/g;
- const imgLinkRE = /(<img[\s\S]*?\s+src=")(.*?)(")/g;
- const aLinkRE = /(<a[\s\S]*?\s+href=")(.*?)(")/g;
- const mdLinkRE = /(\[[\s\S]*?\]\()(.*?)(\))/g;
- const handlebarLinkRE = /({{{.*?\s+url=")(.*?)(")/g;
- const linkREs = [
- iframeLinkRE,
- imgLinkRE,
- aLinkRE,
- mdLinkRE,
- handlebarLinkRE,
- ];
- function hackRelLinks(content, pageUrl) {
- // console.log('---> pageUrl:', pageUrl);
- function fixRelLink(m, prefix, url, suffix) {
- if (isSameDomain(url, pageUrl)) {
- // a link that starts with "../" should be "../../" if it's in a translation
- // a link that starts with "resources" should be "../resources" if it's in a translation
- if (url.startsWith('../') ||
- url.startsWith('resources')) {
- // console.log(' url:', url);
- return `${prefix}../${url}${suffix}`;
- }
- }
- return m;
- }
-
- return content
- .replace(imgLinkRE, fixRelLink)
- .replace(aLinkRE, fixRelLink)
- .replace(iframeLinkRE, fixRelLink);
- }
-
- /**
- * Get all the local urls based on a regex that has <prefix><url><suffix>
- */
- function getUrls(regex, str) {
- const links = new Set();
- let m;
- do {
- m = regex.exec(str);
- if (m && m[2][0] !== '#' && isSameDomain(m[2], 'http://example.com/a/b/c/d')) {
- links.add(getUrlPath(m[2]));
- }
- } while (m);
- return links;
- }
-
- /**
- * Get all the local links in content
- */
- function getLinks(content) {
- return new Set(linkREs.map(re => [...getUrls(re, content)]).flat());
- }
-
- function fixUrls(regex, content, origLinks) {
- return content.replace(regex, (m, prefix, url, suffix) => {
- const q = url.indexOf('?');
- const urlPath = q >= 0 ? url.substring(0, q) : url;
- const urlQuery = q >= 0 ? url.substring(q) : '';
- if (!origLinks.has(urlPath) &&
- isSameDomain(urlPath, 'https://foo.com/a/b/c/d.html') &&
- !(/\/..\/^/.test(urlPath)) && // hacky test for link to main page. Example /webgl/lessons/ja/
- urlPath[0] !== '#') { // test for same page anchor -- bad test :(
- for (const origLink of origLinks) {
- if (urlPath.endsWith(origLink)) {
- const newUrl = `${origLink}${urlQuery}`;
- console.log(' fixing:', url, 'to', newUrl);
- return `${prefix}${newUrl}${suffix}`;
- }
- }
- error('could not fix:', url);
- }
- return m;
- });
- }
-
- const applyTemplateToContent = function(templatePath, contentFileName, outFileName, opt_extra, data) {
- // Call prep's Content which parses the HTML. This helps us find missing tags
- // should probably call something else.
- //Convert(md_content)
- const relativeOutName = slashify(outFileName).substring(g_outBaseDir.length);
- const pageUrl = `${settings.baseUrl}${relativeOutName}`;
- const metaData = data.headers;
- const content = data.content;
- //console.log(JSON.stringify(metaData, undefined, ' '));
- 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);
- }
- html = insertHandlebars(info, html);
- html = replaceParams(html, [opt_extra, g_langInfo]);
- const pathRE = new RegExp(`^\\/${settings.rootFolder}\\/lessons\\/$`);
- const langs = Object.keys(g_langDB).map((name) => {
- const lang = g_langDB[name];
- const url = slashify(path.join(lang.basePath, path.basename(outFileName)))
- .replace('index.html', '')
- .replace(pathRE, '/');
- return {
- lang: lang.lang,
- language: lang.language,
- url: url,
- };
- });
- metaData['content'] = html;
- metaData['langs'] = langs;
- metaData['src_file_name'] = slashify(contentFileName);
- metaData['dst_file_name'] = relativeOutName;
- metaData['basedir'] = '';
- metaData['toc'] = opt_extra.toc;
- metaData['tocHtml'] = g_langInfo.tocHtml;
- metaData['templateOptions'] = opt_extra.templateOptions;
- metaData['langInfo'] = g_langInfo;
- metaData['url'] = pageUrl;
- metaData['relUrl'] = relativeOutName;
- metaData['screenshot'] = `${settings.baseUrl}/${settings.rootFolder}/lessons/resources/${settings.siteThumbnail}`;
- const basename = path.basename(contentFileName, '.md');
- ['.jpg', '.png'].forEach(function(ext) {
- const filename = path.join(settings.rootFolder, 'lessons', 'screenshots', basename + ext);
- if (fs.existsSync(filename)) {
- metaData['screenshot'] = `${settings.baseUrl}/${settings.rootFolder}/lessons/screenshots/${basename}${ext}`;
- }
- });
- const output = templateManager.apply(templatePath, metaData);
- writeFileIfChanged(outFileName, output);
-
- return metaData;
- };
-
- const applyTemplateToFile = function(templatePath, contentFileName, outFileName, opt_extra) {
- console.log('processing: ', contentFileName); // eslint-disable-line
- opt_extra = opt_extra || {};
- const data = loadMD(contentFileName);
- const metaData = applyTemplateToContent(templatePath, contentFileName, outFileName, opt_extra, data);
- g_articles.push(metaData);
- };
-
- const applyTemplateToFiles = function(templatePath, filesSpec, extra) {
- const files = glob
- .sync(filesSpec)
- .sort()
- .filter(articleFilter);
-
- const byFilename = {};
- files.forEach((fileName) => {
- const data = loadMD(fileName);
- if (!data.headers.category) {
- throw new Error(`no catgeory for article: ${fileName}`);
- }
- byFilename[path.basename(fileName)] = data;
- });
-
- // HACK
- if (extra.lang === 'en') {
- Object.assign(g_originalByFileName, byFilename);
- g_originalLangInfo = g_langInfo;
- }
-
- function getLocalizedCategory(category) {
- const localizedCategory = g_langInfo.categoryMapping[category];
- if (localizedCategory) {
- return localizedCategory;
- }
- console.error(`no localization for category: ${category}`);
- const categoryName = g_originalLangInfo.categoryMapping[category];
- if (!categoryName) {
- throw new Error(`no English mapping for category: ${category}`);
- }
- return categoryName;
- }
-
- function addLangToLink(link) {
- return extra.lang === 'en'
- ? link
- : `${path.dirname(link)}/${extra.lang}/${path.basename(link)}`;
- }
-
- function tocLink(fileName) {
- let data = byFilename[fileName];
- let link;
- if (data) {
- link = data.link;
- } else {
- data = g_originalByFileName[fileName];
- link = addLangToLink(data.link);
- }
- const toc = data.headers.toc;
- if (toc === '#') {
- return [...data.content.matchAll(/<a\s*id="(.*?)"\s*data-toc="(.*?)"\s*><\/a>/g)].map(([, id, title]) => {
- const hashlink = `${link}#${id}`;
- return `<li><a href="/${hashlink}">${title}</a></li>`;
- }).join('\n');
- }
- return `<li><a href="/${link}">${toc}</a></li>`;
- }
-
- function makeToc(toc) {
- return `<ul>${
- Object.entries(toc).map(([category, files]) => ` <li>${getLocalizedCategory(category)}</li>
- <ul>
- ${Array.isArray(files)
- ? files.map(tocLink).join('\n')
- : makeToc(files)
- }
- </ul>`
- ).join('\n')
- }</ul>`;
- }
-
- if (!hackyProcessSelectFiles) {
- g_langInfo.tocHtml = makeToc(toc);
- }
-
- files.forEach(function(fileName) {
- const ext = path.extname(fileName);
- const baseName = fileName.substr(0, fileName.length - ext.length);
- const outFileName = path.join(outBaseDir, baseName + '.html');
- applyTemplateToFile(templatePath, fileName, outFileName, extra);
- });
-
- };
-
- const addArticleByLang = function(article, lang) {
- const filename = path.basename(article.dst_file_name);
- let articleInfo = g_articlesByLang[filename];
- const url = `${settings.baseUrl}${article.dst_file_name}`;
- if (!articleInfo) {
- articleInfo = {
- url: url,
- changefreq: 'monthly',
- links: [],
- };
- g_articlesByLang[filename] = articleInfo;
- }
- articleInfo.links.push({
- url: url,
- lang: lang,
- });
- };
-
- const getLanguageSelection = function(lang) {
- const lessons = lang.lessons;
- const langInfo = readHANSON(path.join(lessons, 'langinfo.hanson'));
- langInfo.langCode = langInfo.langCode || lang.lang;
- langInfo.home = lang.home;
- g_langDB[lang.lang] = {
- lang: lang.lang,
- language: langInfo.language,
- basePath: '/' + lessons,
- langInfo: langInfo,
- };
- };
-
- this.preProcess = function(langs) {
- langs.forEach(getLanguageSelection);
- };
-
- this.process = function(options) {
- console.log('Processing Lang: ' + options.lang); // eslint-disable-line
- g_articles = [];
- g_langInfo = g_langDB[options.lang].langInfo;
-
- applyTemplateToFiles(options.template, path.join(options.lessons, settings.lessonGrep), options);
-
- const articlesFilenames = g_articles.map(a => path.basename(a.src_file_name));
-
- // should do this first was easier to add here
- if (options.lang !== 'en') {
- const existing = g_origArticles.filter(name => articlesFilenames.indexOf(name) >= 0);
- existing.forEach((name) => {
- const origMdFilename = path.join(g_origPath, name);
- const transMdFilename = path.join(g_origPath, options.lang, name);
- const origLinks = getLinks(loadMD(origMdFilename).content);
- const transLinks = getLinks(loadMD(transMdFilename).content);
-
- if (process.env['ARTICLE_VERBOSE']) {
- console.log('---[', transMdFilename, ']---');
- console.log('origLinks: ---\n ', [...origLinks].join('\n '));
- console.log('transLinks: ---\n ', [...transLinks].join('\n '));
- }
-
- let show = true;
- transLinks.forEach((link) => {
- if (!origLinks.has(link)) {
- if (show) {
- show = false;
- error('---[', transMdFilename, ']---');
- }
- error(' link:[', link, '] not found in English file');
- }
- });
-
- if (!show && process.env['ARTICLE_FIX']) {
- // there was an error, try to auto-fix
- let fixedMd = fs.readFileSync(transMdFilename, {encoding: 'utf8'});
- linkREs.forEach((re) => {
- fixedMd = fixUrls(re, fixedMd, origLinks);
- });
- fs.writeFileSync(transMdFilename, fixedMd);
- }
- });
- }
-
- if (hackyProcessSelectFiles) {
- return Promise.resolve();
- }
-
- // generate place holders for non-translated files
- const missing = g_origArticles.filter(name => articlesFilenames.indexOf(name) < 0);
- missing.forEach(name => {
- const ext = path.extname(name);
- const baseName = name.substr(0, name.length - ext.length);
- const outFileName = path.join(outBaseDir, options.lessons, baseName + '.html');
- const data = Object.assign({}, loadMD(path.join(g_origPath, name)));
- data.content = g_langInfo.missing;
- const extra = {
- origLink: '/' + slashify(path.join(g_origPath, baseName + '.html')),
- toc: options.toc,
- };
- console.log(' generating missing:', outFileName); // eslint-disable-line
- applyTemplateToContent(
- 'build/templates/missing.template',
- path.join(options.lessons, 'langinfo.hanson'),
- outFileName,
- extra,
- data);
- });
-
- function utcMomentFromGitLog(result, filename, timeType) {
- const dateStr = result.stdout.split('\n')[0].trim();
- const utcDateStr = dateStr
- .replace(/"/g, '') // WTF to these quotes come from!??!
- .replace(' ', 'T')
- .replace(' ', '')
- .replace(/(\d\d)$/, ':$1');
- const m = moment.utc(utcDateStr);
- if (m.isValid()) {
- return m;
- }
- const stat = fs.statSync(filename);
- return moment(stat[timeType]);
- }
-
- const tasks = g_articles.map((article) => {
- return function() {
- return executeP('git', [
- 'log',
- '--format="%ci"',
- '--name-only',
- '--diff-filter=A',
- article.src_file_name,
- ]).then((result) => {
- article.dateAdded = utcMomentFromGitLog(result, article.src_file_name, 'ctime');
- });
- };
- }).concat(g_articles.map((article) => {
- return function() {
- return executeP('git', [
- 'log',
- '--format="%ci"',
- '--name-only',
- '--max-count=1',
- article.src_file_name,
- ]).then((result) => {
- article.dateModified = utcMomentFromGitLog(result, article.src_file_name, 'mtime');
- });
- };
- }));
-
- return tasks.reduce(function(cur, next){
- return cur.then(next);
- }, Promise.resolve()).then(function() {
- let articles = g_articles.filter(function(article) {
- return article.dateAdded !== undefined;
- });
- articles = articles.sort(function(a, b) {
- return b.dateAdded - a.dateAdded;
- });
-
- if (articles.length) {
- const feed = new Feed({
- title: g_langInfo.title,
- description: g_langInfo.description,
- link: g_langInfo.link,
- image: `${settings.baseUrl}/${settings.rootFolder}/lessons/resources/${settings.siteThumbnail}`,
- date: articles[0].dateModified.toDate(),
- published: articles[0].dateModified.toDate(),
- updated: articles[0].dateModified.toDate(),
- author: {
- name: `${settings.siteName} Contributors`,
- link: `${settings.baseUrl}/contributors.html`,
- },
- });
-
- articles.forEach(function(article) {
- feed.addItem({
- title: article.title,
- link: `${settings.baseUrl}${article.dst_file_name}`,
- description: '',
- author: [
- {
- name: `${settings.siteName} Contributors`,
- link: `${settings.baseUrl}/contributors.html`,
- },
- ],
- // contributor: [
- // ],
- date: article.dateModified.toDate(),
- published: article.dateAdded.toDate(),
- // image: posts[key].image
- });
-
- addArticleByLang(article, options.lang);
- });
-
- try {
- const outPath = path.join(g_outBaseDir, options.lessons, 'atom.xml');
- console.log('write:', outPath); // eslint-disable-line
- writeFileIfChanged(outPath, feed.atom1());
- } catch (err) {
- return Promise.reject(err);
- }
- } else {
- console.log('no articles!'); // eslint-disable-line
- }
-
- return Promise.resolve();
- }).then(function() {
- // this used to insert a table of contents
- // but it was useless being auto-generated
- applyTemplateToFile('build/templates/index.template', path.join(options.lessons, 'index.md'), path.join(g_outBaseDir, options.lessons, 'index.html'), {
- table_of_contents: '',
- templateOptions: g_langInfo,
- tocHtml: g_langInfo.tocHtml,
- });
- return Promise.resolve();
- }, function(err) {
- error('ERROR!:');
- error(err);
- if (err.stack) {
- error(err.stack); // eslint-disable-line
- }
- throw new Error(err.toString());
- });
- };
-
- this.writeGlobalFiles = function() {
- const sm = sitemap.createSitemap({
- hostname: settings.baseUrl,
- cacheTime: 600000,
- });
- const articleLangs = { };
- Object.keys(g_articlesByLang).forEach(function(filename) {
- const article = g_articlesByLang[filename];
- const langs = {};
- article.links.forEach(function(link) {
- langs[link.lang] = true;
- });
- articleLangs[filename] = langs;
- sm.add(article);
- });
- // var langInfo = {
- // articles: articleLangs,
- // langs: g_langDB,
- // };
- // var langJS = 'window.langDB = ' + JSON.stringify(langInfo, null, 2);
- // writeFileIfChanged(path.join(g_outBaseDir, 'langdb.js'), langJS);
- writeFileIfChanged(path.join(g_outBaseDir, 'sitemap.xml'), sm.toString());
- copyFile(path.join(g_outBaseDir, `${settings.rootFolder}/lessons/atom.xml`), path.join(g_outBaseDir, 'atom.xml'));
- copyFile(path.join(g_outBaseDir, `${settings.rootFolder}/lessons/index.html`), path.join(g_outBaseDir, 'index.html'));
-
- applyTemplateToFile('build/templates/index.template', 'contributors.md', path.join(g_outBaseDir, 'contributors.html'), {
- table_of_contents: '',
- templateOptions: '',
- });
-
- {
- const filename = path.join(settings.outDir, 'link-check.html');
- const html = `
- <html>
- <body>
- ${langs.map(lang => `<a href="${lang.home}">${lang.lang}</a>`).join('\n')}
- </body>
- </html>
- `;
- writeFileIfChanged(filename, html);
- }
- };
-
-
-};
-
-const b = new Builder(settings.outDir, {
- origPath: `${settings.rootFolder}/lessons`, // english articles
-});
-
-const readdirs = function(dirpath) {
- const dirsOnly = function(filename) {
- const stat = fs.statSync(filename);
- return stat.isDirectory();
- };
-
- const addPath = function(filename) {
- return path.join(dirpath, filename);
- };
-
- return fs.readdirSync(`${settings.rootFolder}/lessons`)
- .map(addPath)
- .filter(dirsOnly);
-};
-
-const isLangFolder = function(dirname) {
- const filename = path.join(dirname, 'langinfo.hanson');
- return fs.existsSync(filename);
-};
-
-
-const pathToLang = function(filename) {
- const lang = path.basename(filename);
- const lessonBase = `${settings.rootFolder}/lessons`;
- const lessons = `${lessonBase}/${lang}`;
- return {
- lang,
- toc: `${settings.rootFolder}/lessons/${lang}/toc.html`,
- lessons: `${lessonBase}/${lang}`,
- template: 'build/templates/lesson.template',
- examplePath: `/${lessonBase}/`,
- home: `/${lessons}/`,
- };
-};
-
-let langs = [
- // English is special (sorry it's where I started)
- {
- template: 'build/templates/lesson.template',
- lessons: `${settings.rootFolder}/lessons`,
- lang: 'en',
- toc: `${settings.rootFolder}/lessons/toc.html`,
- examplePath: `/${settings.rootFolder}/lessons/`,
- home: '/',
- },
-];
-
-langs = langs.concat(readdirs(`${settings.rootFolder}/lessons`)
- .filter(isLangFolder)
- .map(pathToLang));
-
-b.preProcess(langs);
-
-if (hackyProcessSelectFiles) {
- const langsInFilenames = new Set();
- [...settings.filenames].forEach((filename) => {
- const m = /lessons\/(\w{2}|\w{5})\//.exec(filename);
- const lang = m ? m[1] : 'en';
- langsInFilenames.add(lang);
- });
- langs = langs.filter(lang => langsInFilenames.has(lang.lang));
-}
-
-const tasks = langs.map(function(lang) {
- return function() {
- return b.process(lang);
- };
-});
-
-return tasks.reduce(function(cur, next) {
- return cur.then(next);
-}, Promise.resolve()).then(function() {
- if (!hackyProcessSelectFiles) {
- b.writeGlobalFiles(langs);
- }
- return numErrors ? Promise.reject(new Error(`${numErrors} errors`)) : Promise.resolve();
-}).finally(() => {
- cache.clear();
-});
-
-};
- | true |
Other | mrdoob | three.js | 3e4551bb559a9a2e337f14603cf7c6d3bb675a1e.json | use shared builder | build/js/utils.js | @@ -1,69 +0,0 @@
-/*
- * Copyright 2014, Gregg Tavares.
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Gregg Tavares. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-/*eslint-env node*/
-/*eslint no-console: 0*/
-
-'use strict';
-
-const execute = function(cmd, args, callback) {
- const spawn = require('child_process').spawn;
-
- const proc = spawn(cmd, args);
- let stdout = [];
- let stderr = [];
-
- proc.stdout.setEncoding('utf8');
- proc.stdout.on('data', function(data) {
- const str = data.toString();
- const lines = str.split(/(\r?\n)/g);
- stdout = stdout.concat(lines);
- });
-
- proc.stderr.setEncoding('utf8');
- proc.stderr.on('data', function(data) {
- const str = data.toString();
- const lines = str.split(/(\r?\n)/g);
- stderr = stderr.concat(lines);
- });
-
- proc.on('close', function(code) {
- const result = {stdout: stdout.join('\n'), stderr: stderr.join('\n')};
- if (parseInt(code) !== 0) {
- callback('exit code ' + code, result);
- } else {
- callback(null, result);
- }
- });
-};
-
-exports.execute = execute;
- | true |
Other | mrdoob | three.js | 0a3cff6f74732213e90664b435dccd4dc8816072.json | handle helper paths | threejs/resources/editor.js | @@ -370,7 +370,11 @@ function getSourceBlob(htmlParts) {
g.rootScriptInfo.source = htmlParts.js;
makeBlobURLsForSources(g.rootScriptInfo);
- const prefix = dirname(g.url);
+ const dname = dirname(g.url);
+ // HACK! for webgl-2d-vs... those examples are not in /webgl they're in /webgl/resources
+ // We basically assume url is https://foo/base/example.html so there will be 4 slashes
+ // If the path is longer than then we need '../' to back up so prefix works below
+ const prefix = `${dname}${dname.split('/').slice(4).map(() => '/..').join('')}`;
let source = g.html;
source = source.replace('${hackedParams}', JSON.stringify(g.query));
source = source.replace('${html}', htmlParts.html); | false |
Other | mrdoob | three.js | 4952cf90600ae810c1ed11599e02c59da9aa72e8.json | fix TOC title | threejs/lessons/threejs-backgrounds.md | @@ -1,7 +1,7 @@
Title: Three.js Backgrounds and Skyboxes
Description: How to add a background in THREE.js
Category: solutions
-TOC: Load a .GLTF file
+TOC: Add a Background or Skybox
Most of the articles here use a solid color for a background.
| false |
Other | mrdoob | three.js | 60e5adb4ad1e3a328a4bd1192a6dc1083c957814.json | fix github links | build/templates/index.template | @@ -151,7 +151,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
}
</style>
-<div id="forkongithub"><a href="https://github.com/greggman/threejsfundamentals">Fix or Fork me on GitHub</a></div>
+<div id="forkongithub"><a href="https://github.com/gfxfundamentals/threejsfundamentals">Fix or Fork me on GitHub</a></div>
</body>
<script src="/3rdparty/jquery-3.3.1.slim.min.js"></script>
<script src="/threejs/lessons/resources/lesson.js"></script> | true |
Other | mrdoob | three.js | 60e5adb4ad1e3a328a4bd1192a6dc1083c957814.json | fix github links | threejs/lessons/zh_cn/toc.html | @@ -1,6 +1,6 @@
{{{tocHtml}}}
<ul>
- <li><a href="https://github.com/greggman/threejsfundamentals">github</a></li>
+ <li><a href="https://github.com/gfxfundamentals/threejsfundamentals">github</a></li>
<li><a href="https://threejs.org">three.js</a></li>
<li><a href="https://threejs.org/docs/">three.js docs</a></li>
</ul> | true |
Other | mrdoob | three.js | 3c26038dff2666199428003c3f45935c080f85f8.json | fix github links | threejs/lessons/langinfo.hanson | @@ -5,8 +5,8 @@
title: 'three.js fundamentals',
description: 'Learn Three.js',
link: 'http://threejsfundamentals.org/',
- commentSectionHeader: '<div>Questions? <a href="http://stackoverflow.com/questions/tagged/three.js">Ask on stackoverflow</a>.</div>\n <div><a href="https://github.com/greggman/threejsfundamentals/issues/new?assignees=&labels=suggested+topic&template=suggest-topic.md&title=%5BSUGGESTION%5D">Suggestion</a>? <a href="https://github.com/greggman/threejsfundamentals/issues/new?assignees=&labels=&template=request.md&title=">Request</a>? <a href="https://github.com/greggman/threejsfundamentals/issues/new?assignees=&labels=bug+%2F+issue&template=bug-issue-report.md&title=">Issue</a>? <a href="https://github.com/greggman/threejsfundamentals/issues/new?assignees=&labels=bug+%2F+issue&template=bug-issue-report.md&title=">Bug</a>?</div>',
- missing: "Sorry this article has not been translated yet. [Translations Welcome](https://github.com/greggman/threejsfundamentals)! 😄\n\n[Here's the original English article for now]({{{origLink}}}).",
+ commentSectionHeader: '<div>Questions? <a href="http://stackoverflow.com/questions/tagged/three.js">Ask on stackoverflow</a>.</div>\n <div><a href="https://github.com/gfxfundamentals/threejsfundamentals/issues/new?assignees=&labels=suggested+topic&template=suggest-topic.md&title=%5BSUGGESTION%5D">Suggestion</a>? <a href="https://github.com/gfxfundamentals/threejsfundamentals/issues/new?assignees=&labels=&template=request.md&title=">Request</a>? <a href="https://github.com/gfxfundamentals/threejsfundamentals/issues/new?assignees=&labels=bug+%2F+issue&template=bug-issue-report.md&title=">Issue</a>? <a href="https://github.com/gfxfundamentals/threejsfundamentals/issues/new?assignees=&labels=bug+%2F+issue&template=bug-issue-report.md&title=">Bug</a>?</div>',
+ missing: "Sorry this article has not been translated yet. [Translations Welcome](https://github.com/gfxfundamentals/threejsfundamentals)! 😄\n\n[Here's the original English article for now]({{{origLink}}}).",
toc: 'Table of Contents',
categoryMapping: {
'basics': 'Basics', | true |
Other | mrdoob | three.js | 3c26038dff2666199428003c3f45935c080f85f8.json | fix github links | threejs/lessons/ru/langinfo.hanson | @@ -5,8 +5,8 @@
title: 'Основы three.js',
description: 'Изучение Three.js с нуля.',
link: 'http://threejsfundamentals.org/',
- commentSectionHeader: '<div>Вопросы? <a href="http://stackoverflow.com/questions/tagged/three.js">Спросите на stackoverflow</a>.</div>\n <div>Нашли ошибку? <a href="http://github.com/greggman/threejsfundamentals/issues">Создайте issue на github</a>.</div>',
- missing: "К сожалению, страница ещё не переведена. [Я всегда рад переводчикам](https://github.com/greggman/threejsfundamentals)! 😄\n\n[А пока можете почитать статью на английском языке]({{{origLink}}}).",
+ commentSectionHeader: '<div>Вопросы? <a href="http://stackoverflow.com/questions/tagged/three.js">Спросите на stackoverflow</a>.</div>\n <div>Нашли ошибку? <a href="http://github.com/gfxfundamentals/threejsfundamentals/issues">Создайте issue на github</a>.</div>',
+ missing: "К сожалению, страница ещё не переведена. [Я всегда рад переводчикам](https://github.com/gfxfundamentals/threejsfundamentals)! 😄\n\n[А пока можете почитать статью на английском языке]({{{origLink}}}).",
toc: 'Оглавление',
categoryMapping: {
'basics': 'Введение', | true |
Other | mrdoob | three.js | 3c26038dff2666199428003c3f45935c080f85f8.json | fix github links | threejs/lessons/ru/threejs-setup.md | @@ -12,7 +12,7 @@ TOC: Настройка
вашего жесткого диска. Это означает, что для разработки вам необходимо использовать веб-сервер.
К счастью, веб-серверы разработки очень просты в настройке и использовании.
-Прежде всего, если вы хотите, вы можете скачать весь этот сайт по [этой ссылке](https://github.com/greggman/threejsfundamentals/archive/gh-pages.zip).
+Прежде всего, если вы хотите, вы можете скачать весь этот сайт по [этой ссылке](https://github.com/gfxfundamentals/threejsfundamentals/archive/gh-pages.zip).
После загрузки дважды щелкните по zip-файлу, чтобы распаковать файлы.
Затем загрузите один из этих простых веб-серверов или воспользуйтесь средствами вашего ide | true |
Other | mrdoob | three.js | 3c26038dff2666199428003c3f45935c080f85f8.json | fix github links | threejs/lessons/ru/toc.html | @@ -1,6 +1,6 @@
{{{tocHtml}}}
<ul>
- <li><a href="https://github.com/greggman/threejsfundamentals">github</a></li>
+ <li><a href="https://github.com/gfxfundamentals/threejsfundamentals">github</a></li>
<li><a href="https://threejs.org">three.js</a></li>
<li><a href="https://threejs.org/docs/">three.js docs</a></li>
</ul> | true |
Other | mrdoob | three.js | 3c26038dff2666199428003c3f45935c080f85f8.json | fix github links | threejs/lessons/threejs-align-html-elements-to-3d.md | @@ -375,7 +375,7 @@ I found [this data](http://thematicmapping.org/downloads/world_borders.php)
which contains the borders of countries. It's licensed as
[CC-BY-SA](http://creativecommons.org/licenses/by-sa/3.0/).
-I [wrote some code](https://github.com/greggman/threejsfundamentals/blob/master/threejs/lessons/tools/geo-picking/)
+I [wrote some code](https://github.com/gfxfundamentals/threejsfundamentals/blob/master/threejs/lessons/tools/geo-picking/)
to load the data, and generate country outlines and some JSON data with the names
of the countries and their locations.
| true |
Other | mrdoob | three.js | 3c26038dff2666199428003c3f45935c080f85f8.json | fix github links | threejs/lessons/threejs-indexed-textures.md | @@ -50,7 +50,7 @@ then use a similar GPU picking technique. We'd draw the globe off screen using
this index texture. Looking at the color of the pixel the user clicks would
tell us the country id.
-So, I [wrote some code](https://github.com/greggman/threejsfundamentals/blob/master/threejs/lessons/tools/geo-picking/)
+So, I [wrote some code](https://github.com/gfxfundamentals/threejsfundamentals/blob/master/threejs/lessons/tools/geo-picking/)
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> | true |
Other | mrdoob | three.js | 3c26038dff2666199428003c3f45935c080f85f8.json | fix github links | threejs/lessons/threejs-offscreencanvas.md | @@ -601,7 +601,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/greggman/threejsfundamentals/blob/master/threejs/resources/threejs/r105/js/controls/OrbitControls.js)
+Digging through the [OrbitControls source code](https://github.com/gfxfundamentals/threejsfundamentals/blob/master/threejs/resources/threejs/r105/js/controls/OrbitControls.js)
it looks like we need to handle the following events.
* contextmenu | true |
Other | mrdoob | three.js | 3c26038dff2666199428003c3f45935c080f85f8.json | fix github links | threejs/lessons/threejs-setup.md | @@ -13,7 +13,7 @@ WebGL cannot use images from your hard drive directly. That means
in order to do development you need to use a web server. Fortunately
development web servers are super easy to setup and use.
-First off if you'd like you can download this entire site from [this link](https://github.com/greggman/threejsfundamentals/archive/gh-pages.zip).
+First off if you'd like you can download this entire site from [this link](https://github.com/gfxfundamentals/threejsfundamentals/archive/gh-pages.zip).
Once downloaded double click the zip file to unpack the files.
Next download one of these simple web servers. | true |
Other | mrdoob | three.js | 3c26038dff2666199428003c3f45935c080f85f8.json | fix github links | threejs/lessons/toc.html | @@ -1,6 +1,6 @@
{{{tocHtml}}}
<ul>
- <li><a href="https://github.com/greggman/threejsfundamentals">github</a></li>
+ <li><a href="https://github.com/gfxfundamentals/threejsfundamentals">github</a></li>
<li><a href="https://threejs.org">three.js</a></li>
<li><a href="https://threejs.org/docs/">three.js docs</a></li>
</ul> | true |
Other | mrdoob | three.js | 3c26038dff2666199428003c3f45935c080f85f8.json | fix github links | threejs/lessons/zh_cn/langinfo.hanson | @@ -5,8 +5,8 @@
title: 'three.js基础',
description: 'Three.js基础学习',
link: 'http://threejsfundamentals.org/',
- commentSectionHeader: '<div>Questions? <a href="http://stackoverflow.com/questions/tagged/three.js">Ask on stackoverflow</a>.</div>\n <div><a href="https://github.com/greggman/threejsfundamentals/issues/new?assignees=&labels=suggested+topic&template=suggest-topic.md&title=%5BSUGGESTION%5D">Suggestion</a>? <a href="https://github.com/greggman/threejsfundamentals/issues/new?assignees=&labels=&template=request.md&title=">Request</a>? <a href="https://github.com/greggman/threejsfundamentals/issues/new?assignees=&labels=bug+%2F+issue&template=bug-issue-report.md&title=">Issue</a>? <a href="https://github.com/greggman/threejsfundamentals/issues/new?assignees=&labels=bug+%2F+issue&template=bug-issue-report.md&title=">Bug</a>?</div>',
- missing: "Sorry this article has not been translated yet. [Translations Welcome](https://github.com/greggman/threejsfundamentals)! 😄\n\n[Here's the original English article for now]({{{origLink}}}).",
+ commentSectionHeader: '<div>Questions? <a href="http://stackoverflow.com/questions/tagged/three.js">Ask on stackoverflow</a>.</div>\n <div><a href="https://github.com/gfxfundamentals/threejsfundamentals/issues/new?assignees=&labels=suggested+topic&template=suggest-topic.md&title=%5BSUGGESTION%5D">Suggestion</a>? <a href="https://github.com/gfxfundamentals/threejsfundamentals/issues/new?assignees=&labels=&template=request.md&title=">Request</a>? <a href="https://github.com/gfxfundamentals/threejsfundamentals/issues/new?assignees=&labels=bug+%2F+issue&template=bug-issue-report.md&title=">Issue</a>? <a href="https://github.com/gfxfundamentals/threejsfundamentals/issues/new?assignees=&labels=bug+%2F+issue&template=bug-issue-report.md&title=">Bug</a>?</div>',
+ missing: "Sorry this article has not been translated yet. [Translations Welcome](https://github.com/gfxfundamentals/threejsfundamentals)! 😄\n\n[Here's the original English article for now]({{{origLink}}}).",
toc: '内容列表',
categoryMapping: {
'basics': '基础', | true |
Other | mrdoob | three.js | 3c26038dff2666199428003c3f45935c080f85f8.json | fix github links | threejs/lessons/zh_cn/threejs-setup.md | @@ -13,7 +13,7 @@ WebGL不能直接从你的硬件使用图片。意思是说
为了能开发你需要使用web服务。幸运的是
web服务很容易设置和使用。
-首先如果你喜欢你可以从[这个链接](https://github.com/greggman/threejsfundamentals/archive/gh-pages.zip)
+首先如果你喜欢你可以从[这个链接](https://github.com/gfxfundamentals/threejsfundamentals/archive/gh-pages.zip)
下载整个网站。
一旦下载完成双击文件来解压。
| true |
Other | mrdoob | three.js | 9c6a79f7281b8a2923b51f8745a866f3cd0cd2bf.json | use node 12 | .travis.yml | @@ -1,6 +1,6 @@
language: node_js
node_js:
- - "11"
+ - "12"
script:
- npm run build
env: | false |
Other | mrdoob | three.js | c3c06f93798d2f92707d4f4c2ecc701a19070930.json | Fix typos in buffer geometry article | threejs/lessons/threejs-custom-buffergeometry.md | @@ -17,16 +17,16 @@ of the face.
<div class="threejs_center"><img src="resources/threejs-geometry.svg" style="width: 700px"></div>
-`BufferGeometry` on the other hand uses *named* `BufferAttribute`s
-Each `BufferAttribute` represents an array of one type of data, positions,
-normals, colors, uv, and togther the all the added `BufferAttribute`s represent
-*parallel arrays* of all the data for each vertex.
+`BufferGeometry` on the other hand uses *named* `BufferAttribute`s.
+Each `BufferAttribute` represents an array of one type of data: positions,
+normals, colors, and uv. Togther, the added `BufferAttribute`s represent
+*parallel arrays* of all the data for each vertex.
<div class="threejs_center"><img src="resources/threejs-attributes.svg" style="width: 700px"></div>
-Above you can see we have 4 attributes, `position`, `normal`, `color`, `uv`.
+Above you can see we have 4 attributes: `position`, `normal`, `color`, `uv`.
They represent *parallel arrays* which means that the Nth set of data in each
-attribute belongs to the same vertex. Above the vertex at index = 4 is highlighted
+attribute belongs to the same vertex. The vertex at index = 4 is highlighted
to show that the parallel data across all attributes defines one vertex.
This brings up a point, here's a diagram of a cube with one corner highlighted.
@@ -44,19 +44,19 @@ That is where the extra memory and time comes from when using `Geometry`. Extra
memory for all the `Vector3`s, `Vector2`s, `Face3`s and array objects and then
extra time to translate all of that data into parallel arrays in the form of
`BufferAttribute`s like above. Somtimes that makes using `Geometry` easier.
-With `BufferGeometry` is up to us to supply the data already turned into this format.
+With `BufferGeometry` it is up to us to supply the data already turned into this format.
As a simple example let's make a cube using `BufferGeometry`. A cube is interesting
because it appears to share vertices at the corners but really
does not. For our example we'll list out all the vertices with all their data
and then convert that data into parallel arrays and finally use those to make
`BufferAttribute`s and add them to a `BufferGeometry`.
-Starting with the texture coordinate example from [the previous article](threejs-custom-geometry.html) we've delete all the code related to setting up
+Starting with the texture coordinate example from [the previous article](threejs-custom-geometry.html) we've deleted all the code related to setting up
a `Geometry`. Then we list all the data needed for the cube. Remember again
that if a vertex has any unique parts it has to be a separate vertex. As such
-to make a cube requires 36 vertex. 2 triangles per face, 3 vertices per triangle,
-6 faces = 36 vertices
+to make a cube requires 36 vertices. 2 triangles per face, 3 vertices per triangle,
+6 faces = 36 vertices.
```js
const vertices = [
@@ -124,7 +124,7 @@ for (const vertex of vertices) {
}
```
-Finally we can create a `BufferGeometry` and then a `BufferAttribute` for each array
+Finally we can create a `BufferGeometry` and then a `BufferAttribute` for each array
and add it to the `BufferGeometry`.
```js
@@ -151,17 +151,17 @@ name your attribute `color`.
Above we created 3 JavaScript native arrays, `positions`, `normals` and `uvs`.
We then convert those into
[TypedArrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray)
-of type `Float32Array`. A `BufferAttribute` requires a typedarray not a native
-array. A `BufferAttribute` also requires you tell it how many components there
+of type `Float32Array`. A `BufferAttribute` requires a TypedArray not a native
+array. A `BufferAttribute` also requires you to tell it how many components there
are per vertex. For the positions and normals we have 3 components per vertex,
x, y, and z. For the UVs we have 2, u and v.
{{{example url="../threejs-custom-buffergeometry-cube.html"}}}
That's a lot of data. A small thing we can do is use indices to reference
the vertices. Looking back at our cube data, each face is made from 2 triangles
-with 3 vertices each, 6 vertices total, but 2 of those vertices are exactly the same;
-The same position, the same normal, and the same uv.
+with 3 vertices each, 6 vertices total, but 2 of those vertices are exactly the same;
+The same position, the same normal, and the same uv.
So, we can remove the matching vertices and then
reference them by index. First we remove the matching vertices.
@@ -266,12 +266,12 @@ is no way to share the vertices at the start and end of the cylinder since they
require different UVs. Just a small thing to be aware of. The solution is
to supply your own normals.
-We can also use [typedarrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) from the start instead of native JavaScript arrays.
-The disadvantage to typedarrays is you must specify their size up front. Of
+We can also use [TypedArrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) from the start instead of native JavaScript arrays.
+The disadvantage to TypedArrays is you must specify their size up front. Of
course that's not that large of a burden but with native arrays we can just
`push` values onto them and look at what size they end up by checking their
-`length` at the end. With typedarrays there is no push function so we need
-to do our own bookkeeping when adding values do them.
+`length` at the end. With TypedArrays there is no push function so we need
+to do our own bookkeeping when adding values to them.
In this example knowing the length up front is pretty easy since we're using
a big block of static data to start.
@@ -328,7 +328,7 @@ geometry.setIndex([
{{{example url="../threejs-custom-buffergeometry-cube-typedarrays.html"}}}
A good reason to use typedarrays is if you want to dynamically update any
-part of the vertices.
+part of the vertices.
I couldn't think of a really good example of dynamically updating the vertices
so I decided to make a sphere and move each quad in and out from the center. Hopefully
@@ -454,9 +454,9 @@ And we set `positionAttribute.needsUpdate` to tell THREE.js to use our changes.
{{{example url="../threejs-custom-buffergeometry-dynamic.html"}}}
-I hope these were useful example of how to use `BufferGeometry` directly to
+I hope these were useful examples of how to use `BufferGeometry` directly to
make your own geometry and how to dynamically update the contents of a
-`BufferAttribute`. Which you use, `Geometry` or `BufferGeometry` really
+`BufferAttribute`. Which you use, `Geometry` or `BufferGeometry`, really
depends on your needs.
<canvas id="c"></canvas> | false |
Other | mrdoob | three.js | 9d5e65875fcd9a82f8351dd067a0db923dcfc87e.json | Remove outdated examples of ArrowHelper | docs/api/en/helpers/ArrowHelper.html | @@ -33,8 +33,6 @@ <h2>Code Example</h2>
<h2>Examples</h2>
<p>
- [example:webgl_geometries WebGL / geometries]<br/>
- [example:webgl_geometry_normals WebGL / geometry / normals]<br/>
[example:webgl_shadowmesh WebGL / shadowmesh]
</p>
| false |
Other | mrdoob | three.js | f549b793fe070b951fa1018af8cbaddf8650c11f.json | fix static value of Euler | src/math/Euler.js | @@ -17,9 +17,17 @@ class Euler {
}
- static RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
+ static get RotationOrders() {
- static DefaultOrder = 'XYZ';
+ return [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
+
+ }
+
+ static get DefaultOrder() {
+
+ return 'XYZ';
+
+ }
get x() {
| false |
Other | mrdoob | three.js | 7386f92ca436be2be5b25044dc4b265af632fe2a.json | Add entry on examples files | examples/files.js | @@ -333,6 +333,7 @@ var files = {
"webxr_vr_handinput",
"webxr_vr_handinput_cubes",
"webxr_vr_handinput_profiles",
+ "webxr_vr_haptics",
"webxr_vr_lorenzattractor",
"webxr_vr_panorama",
"webxr_vr_panorama_depth", | false |
Other | mrdoob | three.js | 979f99d21b688253cab8b6e69f4816febe64fd91.json | solve hoisting in Vector3 | src/math/Vector3.js | @@ -1,7 +1,7 @@
import { MathUtils } from './MathUtils.js';
import { Quaternion } from './Quaternion.js';
-const _vector = new Vector3();
+let _vector;
const _quaternion = new Quaternion();
class Vector3 {
@@ -725,6 +725,8 @@ class Vector3 {
}
-};
+}
+
+_vector = new Vector3();
export { Vector3 }; | true |
Other | mrdoob | three.js | 979f99d21b688253cab8b6e69f4816febe64fd91.json | solve hoisting in Vector3 | src/math/Vector4.js | @@ -648,6 +648,6 @@ class Vector4 {
}
-};
+}
export { Vector4 }; | true |
Other | mrdoob | three.js | 4ed488645f9c787d7ed8cd4f6bea098a551faae0.json | Add webaudio osc | examples/webxr_vr_haptics.html | @@ -26,11 +26,42 @@
var box = new THREE.Box3();
var controllers = [];
+ var oscillators = [];
var controls, group;
+ var audioCtx = null;
init();
animate();
+ function initAudio() {
+
+ if ( audioCtx !== null ) {
+
+ return;
+
+ }
+
+ audioCtx = new ( window.AudioContext || window.webkitAudioContext )();
+ function createOscillator() {
+
+ let oscillator = audioCtx.createOscillator();
+ const real = Array.from( { length: 8192 }, ( _, n ) => (
+ n === 0 ?
+ 0 :
+ 4 / ( n * Math.PI ) * Math.sin( Math.PI * n * 0.18 )
+ ) );
+ const imag = real.map( () => 0 );
+ oscillator.setPeriodicWave( audioCtx.createPeriodicWave( Float32Array.from( real ), Float32Array.from( imag ) ) );
+ oscillator.start();
+ return oscillator;
+
+ }
+
+ oscillators.push( createOscillator() );
+ oscillators.push( createOscillator() );
+ window.oscillators = oscillators;
+ }
+
function init() {
container = document.createElement( 'div' );
@@ -75,12 +106,13 @@
for ( var i = 0; i < 10; i ++ ) {
+ const intensity = ( i + 1 ) / 10;
const w = 0.1;
const h = 0.1;
const minH = 1;
var geometry = new THREE.BoxBufferGeometry( w, h * i + minH, w );
var material = new THREE.MeshStandardMaterial( {
- color: Math.random() * 0xffffff,
+ color: new THREE.Color( intensity, 0.1, 0.1 ),
roughness: 0.7,
metalness: 0.0
} );
@@ -90,7 +122,8 @@
object.castShadow = true;
object.receiveShadow = true;
object.userData = {
- index: i + 1
+ index: i + 1,
+ intensity: intensity
};
group.add( object );
@@ -109,6 +142,12 @@
document.body.appendChild( VRButton.createButton( renderer ) );
+ document.getElementById( "VRButton" ).addEventListener( "click", () => {
+
+ initAudio();
+
+ } );
+
// controllers
controller1 = renderer.xr.getController( 0 );
@@ -141,7 +180,9 @@
controllers.push( {
gamepad: evt.data.gamepad,
- grip: evt.target
+ grip: evt.target,
+ colliding: false,
+ playing: false
} );
}
@@ -178,6 +219,8 @@
for ( var g = 0; g < controllers.length; g ++ ) {
+ controllers[ g ].colliding = false;
+
const { grip, gamepad } = controllers[ g ];
var sphere = {
radius: 0.03,
@@ -196,6 +239,8 @@
const intensity = child.userData.index / group.children.length;
child.scale.setScalar( 1 + Math.random() * 0.1 * intensity );
gamepad.hapticActuators[ 0 ].pulse( intensity, 100 );
+ oscillators[ g ].frequency.value = 100 + intensity * 60;
+ controllers[ g ].colliding = true;
} else {
@@ -208,6 +253,26 @@
}
+ if ( controllers[ g ].colliding ) {
+
+ if ( ! controllers[ g ].playing ) {
+
+ controllers[ g ].playing = true;
+ oscillators[ g ].connect( audioCtx.destination );
+
+ }
+
+ } else {
+
+ if ( controllers[ g ].playing ) {
+
+ controllers[ g ].playing = false;
+ oscillators[ g ].disconnect( audioCtx.destination );
+
+ }
+
+ }
+
}
renderer.render( scene, camera ); | false |
Other | mrdoob | three.js | 039a75df49c2f1ca7ed92c39b5b6938188fce44b.json | Add random scale | examples/webxr_vr_haptics.html | @@ -193,11 +193,14 @@
if ( box.intersectsSphere( sphere ) ) {
child.material.emissive.b = 1;
- gamepad.hapticActuators[ 0 ].pulse( child.userData.index / group.children.length, 100 );
+ const intensity = child.userData.index / group.children.length;
+ child.scale.setScalar( 1 + Math.random() * 0.1 * intensity );
+ gamepad.hapticActuators[ 0 ].pulse( intensity, 100 );
} else {
child.material.emissive.b = 0;
+ child.scale.setScalar( 1 );
}
| false |
Other | mrdoob | three.js | 1eedf1b3712f9d4f9cffa50073a30ec29678974e.json | Preserve sourcemaps in Rollup transforms.
Context: #9745, #10954. | utils/build/rollup.config.js | @@ -160,7 +160,7 @@ function glconstants() {
return {
code: code,
- map: { mappings: '' }
+ map: null
};
}
@@ -192,7 +192,7 @@ function glsl() {
return {
code: code,
- map: { mappings: '' }
+ map: null
};
}
@@ -228,7 +228,7 @@ function bubleCleanup() {
return {
code: code,
- map: { mappings: '' }
+ map: null
};
} | false |
Other | mrdoob | three.js | 93c3d48e2587eca9a3987a334c65719808a05daf.json | add translation kr/threejs-shadertoy.md | threejs/lessons/kr/threejs-shadertoy.md | @@ -0,0 +1,338 @@
+Title: 쉐이더토이(Shadertoy) 활용하기
+Description: Three.js에서 쉐이더토이의 쉐이더를 사용하는 법을 알아봅니다
+TOC: 쉐이더토이 쉐이더 활용하기
+
+[쉐이더토이(Shadertoy)](https://shadertoy.com)는 다양한 쉐이더를 제공하는 유명한 사이트입니다. 시리즈를 진행하다보니 쉐이더토이에서 받은 쉐이더를 Three.js에 적용하는 법을 물어보시는 분들이 꽤 있더군요.
+
+하지만 쉐이더**토이**라고 불리는 데는 이유가 있습니다. 쉐이더토이에 올라온 쉐이더는 정석대로 만들어진 쉐이더가 아닙니다. [드위터(dwitter)](https://dwitter.net)(140자 내로 코드를 작성하는 사이트)나 [js13kGames](https://js13kgames.com)(13kb 이하의 게임을 만드는 사이트)처럼 여러 사람이 쉐이더-챌린지를 진행하는 곳이죠.
+
+쉐이더토이의 미션은 *주어진 픽셀 위치값으로 무언가 재밌는 것을 렌더링하는 함수를 만드는 것*입니다. 재밌는 미션이고 많은 결과물을 보면 대단하다는 소리가 절로 나옵니다. 하지만 초보자가 보고 배우기에 좋은 예제들은 아니죠.
+
+아래의 [쉐이더로 도시 전체를 렌더링한 쉐이더토이 예제](https://www.shadertoy.com/view/XtsSWs)를 한 번 봅시다.
+
+<div class="threejs_center"><img src="resources/images/shadertoy-skyline.png"></div>
+
+제 컴퓨터에서 FHD 해상도를 기준으로 약 5 프레임 내외가 나옵니다. 이를 [시티즈: 스카이라인(Cities: Skylines)](https://store.steampowered.com/app/255710/Cities_Skylines/) 같은 게임과 비교해보면
+
+<div class="threejs_center"><img src="resources/images/cities-skylines.jpg" style="width: 600px;"></div>
+
+같은 컴퓨터에서 30-60 프레임이 나옵니다. 이 게임이 텍스처를 입힌 삼각형을 렌더링하는 등 좀 더 일반적인 기법을 사용했기 때문이죠.
+
+뭐 그렇다고 해도 쉐이더토이의 쉐이더를 Three.js에 한 번 불러와보는 건 나쁘지 않을 겁니다.
+
+아래는 쉐이더토이에서 ["New"를 클릭했을 때](https://www.shadertoy.com/new) 나오는 기본 쉐이더입니다(2019년 1월 기준).
+
+```glsl
+// By iq: https://www.shadertoy.com/user/iq
+// license: Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.
+void mainImage( out vec4 fragColor, in vec2 fragCoord )
+{
+ // Normalized pixel coordinates (from 0 to 1)
+ vec2 uv = fragCoord/iResolution.xy;
+
+ // Time varying pixel color
+ vec3 col = 0.5 + 0.5*cos(iTime+uv.xyx+vec3(0,2,4));
+
+ // Output to screen
+ fragColor = vec4(col,1.0);
+}
+```
+
+여기서 중요한 건 쉐이더는 GLSL(Graphic Library Shading Language)로 작성한다는 겁니다. GLSL은 3D 수학을 위해 C 언어 기반으로 고안된 상위 언어로, GLSL만의 고유한 타입이 있습니다. 위 코드의 `vec4`, `vec2`, `vec3`이 그런 고유 타입들이죠. `vec2`는 값이 2개, `vec3`는 3개, `vec4`는 4개인데, 이들은 각각 다양한 값으로 사용되지만 `x`, `y`, `z` 그리고 `w`로 사용하는 게 보통입니다.
+
+```glsl
+vec4 v1 = vec4(1.0, 2.0, 3.0, 4.0);
+float v2 = v1.x + v1.y; // adds 1.0 + 2.0
+```
+
+GLSL은 자바스크립트와 달리 C나 C++처럼 변수를 선언할 때 해당 타입을 사용해야 합니다. 예를 들어 실수(float)를 변수에 담을 때 자바스크립트는 `var v = 1.2;`와 같이 쓰지만, GLSL에서는 `float v = 1.2;`와 같이 씁니다.
+
+이 글에서 GLSL을 자세히 설명하는 건 주제에 벗어나니 [이 글](https://webglfundamentals.org/webgl/lessons/ko/webgl-shaders-and-glsl.html)을 읽어보거나 [이 시리즈](https://thebookofshaders.com/?lan=kr)를 정주행해보기 바랍니다.
+
+또한 2019년 1월 기준으로 [쉐이더토이](https://shadertoy.com)는 *fragment shaders*만 지원합니다. fragment shader는 아까 말한 미션처럼 픽셀의 좌표를 받아 해당 픽셀에 특정 색을 지정하는 역할을 하죠.
+
+위 코드를 보면 `mainImage` 함수에 `fragColor`라는 이름의 `out` 매개변수가 보일 겁니다. `out`은 `output`의 줄임말로, 바로 이 매개변수가 색상값을 지정할 변수 합니다.
+
+`fragCoord`, `in`(`input`의 줄임말) 매개변수는 `out`의 색상값을 사용할 픽셀의 좌표입니다. 이 픽셀 좌표로 새로운 색상값을 만들 수 있죠. 만약 400x300짜리 캔버스에 이 쉐이더를 적용한다면 이 함수는 400x300번, 그러니까 총 120,000번 호출되는 셈입니다.
+
+코드에 선언부가 없긴 하지만 사용할 수 있는 변수가 2개 더 있습니다. 하나는 캔버스의 해상도를 설정하는 `iResolution`으로, 캔버스를 400x300으로 만들려면 `iResolution`을 `400, 300`으로 설정해야 합니다. 그리고 `iResolution`에 의해 픽셀 좌표가 바뀌면 `uv` 변수는 텍스처 크기의 0.0에서 1.0만큼 위, 옆으로 갑니다. 이렇듯 어떤 값을 *정규화(normalize)*하는 것이 작업을 간단히 하는 데 도움이 되기에 쉐이더토이의 주 함수는 대개 저런 식으로 시작합니다.
+
+다른 하나는 `iTime`으로, 이는 페이지가 로드된 이후의 초 단위 시간값입니다.
+
+쉐이더의 세계에서 이 전역 변수들은 *균등(uniform)* 변수라고 불립니다. *균등*이라고 불리는 이유는 쉐이더 한 루프 안에서는 전혀 변하지 않는 변수이기 때문이죠. 다만 위에서 언급한 변수들은 GLSL의 *표준* 변수가 아니라 쉐이더토이에서 자체적으로 제공하는 변수입니다.
+
+[쉐이더토이 공식 문서에는 몇 가지 변수를 더 언급](https://www.shadertoy.com/howto)해 놓았지만, 일단은 위 두 변수를 활용해 예제를 하나 만들어보겠습니다.
+
+먼저 캔버스 전체를 채울 평면을 하나 만듭니다. [배경과 하늘상자 추가하기](threejs-backgrounds.html)에서 정육면체를 뺀 예제를 가져오겠습니다. 코드가 길지 않으니 아래에 전부 적도록 하죠.
+
+```js
+function main() {
+ const canvas = document.querySelector('#c');
+ const renderer = new THREE.WebGLRenderer({ canvas });
+ renderer.autoClearColor = false;
+
+ const camera = new THREE.OrthographicCamera(
+ -1, // left
+ 1, // right
+ 1, // top
+ -1, // bottom
+ -1, // near,
+ 1, // far
+ );
+ const scene = new THREE.Scene();
+ const plane = new THREE.PlaneBufferGeometry(2, 2);
+ const material = new THREE.MeshBasicMaterial({
+ color: 'red',
+ });
+ scene.add(new THREE.Mesh(plane, material));
+
+ 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() {
+ resizeRendererToDisplaySize(renderer);
+
+ renderer.render(scene, camera);
+
+ requestAnimationFrame(render);
+ }
+
+ requestAnimationFrame(render);
+}
+
+main();
+```
+
+[배경과 하늘상자 추가하기](threejs-backgrounds.html)에서도 설명했지만 위와 같이 `OrthographicCamera`를 설정하면 2칸짜리 평면이 캔버스 전체를 채우게 됩니다. 당장은 평면이 빨간 `MeshBasicMaterial`을 사용했기에 캔버스 전체가 빨갛게 보입니다.
+
+{{{example url="../threejs-shadertoy-prep.html" }}}
+
+이제 쉐이더토이에서 쉐이더를 가져와 적용해봅시다.
+
+```js
+const fragmentShader = `
+#include <common>
+
+uniform vec3 iResolution;
+uniform float iTime;
+
+// By iq: https://www.shadertoy.com/user/iq
+// license: Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.
+void mainImage( out vec4 fragColor, in vec2 fragCoord )
+{
+ // Normalized pixel coordinates (from 0 to 1)
+ vec2 uv = fragCoord/iResolution.xy;
+
+ // Time varying pixel color
+ vec3 col = 0.5 + 0.5*cos(iTime+uv.xyx+vec3(0,2,4));
+
+ // Output to screen
+ fragColor = vec4(col,1.0);
+}
+
+void main() {
+ mainImage(gl_FragColor, gl_FragCoord.xy);
+}
+`;
+```
+
+위 코드에서는 아까 설명했던 균등 변수 2개를 선언했습니다. 그런 다음 쉐이더토이에서 만든 GLSL 코드를 복사해 넣었죠. 그리고 하단에서 `mainImage`에 `gl_FragColor`와 `gl_FragCoord.xy`를 넘겨 호출했습니다. 여기서 사용한 `gl_FragColor`는 WebGL의 공식 전역 변수로, 쉐이더는 여기에 해당 픽셀의 색상값을 지정해야 합니다. `gl_FragCoord` 또한 WebGL 공식 전역 변수로, 현재 색상을 적용해야 하는 픽셀의 좌표값을 나타내죠.
+
+다음으로 쉐이더에 데이터를 전달할 전달해야 하니 Three.js 균등 변수를 생성합니다.
+
+```js
+const uniforms = {
+ iTime: { value: 0 },
+ iResolution: { value: new THREE.Vector3() },
+};
+```
+
+Three.js의 균등 변수에는 `value` 속성을 넣어야 합니다. 물론 값으로 들어가는 데이터도 균등 변수의 타입과 맞아야 하죠.
+
+fragment 쉐이더와 균등 변수를 `ShaderMaterial`에 넘겨줍니다.
+
+```js
+-const material = new THREE.MeshBasicMaterial({
+- color: 'red',
+-});
++const material = new THREE.ShaderMaterial({
++ fragmentShader,
++ uniforms,
++});
+```
+
+또한 매 프레임마다 균등 변수의 값을 변경하도록 합니다.
+
+```js
+-function render() {
++function render(time) {
++ time *= 0.001; // 초 단위로 변환
+
+ resizeRendererToDisplaySize(renderer);
+
++ const canvas = renderer.domElement;
++ uniforms.iResolution.value.set(canvas.width, canvas.height, 1);
++ uniforms.iTime.value = time;
+
+ renderer.render(scene, camera);
+
+ requestAnimationFrame(render);
+}
+```
+
+> 참고: [쉐이더토이 공식 문서](https://www.shadertoy.com/howto)를 뒤져봤지만 `iResolution`가 왜 `vec3`여야 하는지, 3번째 값은 어디에 쓰이는 건지 알아내지 못했습니다. 일단 예제에서는 쓰지 않는 값이니 1로 설정하고 넘어가야겠네요. ¯\\_(ツ)\_/¯
+
+{{{example url="../threejs-shadertoy-basic.html" }}}
+
+[쉐이더토이에서 "New"를 클릭했을 때 나왔던 결과](https://www.shadertoy.com/new)와 똑같네요. 물론 2019년 1월 기준으로 말이죠😉. 이 쉐이더는 어떻게 이런 결과를 만들어낸 걸까요?
+
+* `uv`가 시간에 따라 서서히 0에서 1로 바뀝니다.
+* `cos(uv.xyx)`는 입력한 값에 코사인 함수를 적용해 `vec3` 형식으로 반환합니다. 하나는 `uv.x`에, 다른 하나는 `uv.y`에, 마지막은 다시 `uv.x`에 코사인 함수를 실행한 결과값이죠.
+* 이전에 `cos(iTime+uv.xyx)` 이렇게 시간값을 더해 애니메이션을 구현합니다.
+* 이전에 `vec3(0,2,4)`를 더해 `cos(iTime+uv.xyx+vec3(0,2,4))`와 같이 하면 코사인 파도가 생깁니다.
+* `cos`의 결과값은 -1부터 1까지이므로, `0.5 * 0.5 + cos(...)`을 적용하면 -1 <-> 1, 0.0 <-> 1.0 이런 식으로 바뀝니다.
+* 이 결과값을 현재 픽셀에 대한 RGB 값으로 씁니다.
+
+코드를 조금 수정하면 코사인 파도가 더 잘 보일 겁니다. 지금은 `uv`의 값이 0부터 1까지죠. 코사인의 주기는 2π이니 `uv`에 40.0을 곱해 `uv`값이 0부터 40까지 되도록 해보겠습니다. 이러면 화면에 파도가 약 6.3번 반복될 거예요.
+
+```glsl
+-vec3 col = 0.5 + 0.5 * cos(iTime + uv.xyx + vec3(0,2,4));
++vec3 col = 0.5 + 0.5 * cos(iTime + uv.xyx * 40.0 + vec3(0,2,4));
+```
+
+아래 예제를 보니 파도가 약 6개 하고 1/3 정도 보입니다. 파란선 사이에 빨간선이 보이는 건 파란색의 위치를 `+ vec3(0,2,4)`로 4만큼 옮겼기 때문이죠. 이렇게 하지 않았다면 빨강과 파랑이 완전히 겹쳐 자주색으로 보였을 겁니다.
+
+{{{example url="../threejs-shadertoy-basic-x40.html" }}}
+
+주어지는 값이 이렇게 단순한데 이걸로 [도심 운하](https://www.shadertoy.com/view/MdXGW2), [숲](https://www.shadertoy.com/view/4ttSWf), [달팽이](https://www.shadertoy.com/view/ld3Gz2), [버섯](https://www.shadertoy.com/view/4tBXR1) 등을 구현하다니 정말 놀랍네요. 다만 삼각형으로 장면을 구성하는 일반적인 방법에 비해 왜 이 방법이 안 좋은지 분명히 하지 않은 게 아쉽습니다. 한 픽셀 한 픽셀 정성들여 픽셀의 색상을 연산하니 그만큼 한 프레임을 만드는 데 시간이 많이 걸릴 수밖에 없죠.
+
+쉐이더토이 쉐이더 중에는 [텍스처를 받아서 사용하는 경우](https://www.shadertoy.com/view/MsXSzM)도 있습니다.
+
+```glsl
+// By Daedelus: https://www.shadertoy.com/user/Daedelus
+// license: Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.
+#define TIMESCALE 0.25
+#define TILES 8
+#define COLOR 0.7, 1.6, 2.8
+
+void mainImage( out vec4 fragColor, in vec2 fragCoord )
+{
+ vec2 uv = fragCoord.xy / iResolution.xy;
+ uv.x *= iResolution.x / iResolution.y;
+
+ vec4 noise = texture2D(iChannel0, floor(uv * float(TILES)) / float(TILES));
+ float p = 1.0 - mod(noise.r + noise.g + noise.b + iTime * float(TIMESCALE), 1.0);
+ p = min(max(p * 3.0 - 1.8, 0.1), 2.0);
+
+ vec2 r = mod(uv * float(TILES), 1.0);
+ r = vec2(pow(r.x - 0.5, 2.0), pow(r.y - 0.5, 2.0));
+ p *= 1.0 - pow(min(1.0, 12.0 * dot(r, r)), 2.0);
+
+ fragColor = vec4(COLOR, 1.0) * p;
+}
+```
+
+쉐이더에 텍스처를 넘겨주는 건 [재질(material)에 텍스처를 넘겨주는 것](threejs-textures.html)과 비슷하나, 대신 텍스처를 균등 변수에 지정해야 합니다.
+
+먼저 쉐이더에 균등 변수를 추가합니다. 텍스처는 GLSL에서 `sampler2D`라고 불립니다.
+
+```js
+const fragmentShader = `
+#include <common>
+
+uniform vec3 iResolution;
+uniform float iTime;
++uniform sampler2D iChannel0;
+
+...
+```
+
+다음으로 [이 글](threejs-textures.html)에서 했던 것처럼 텍스처를 불러와 균등 변수에 지정합니다.
+
+```js
++const loader = new THREE.TextureLoader();
++const texture = loader.load('resources/images/bayer.png');
++texture.minFilter = THREE.NearestFilter;
++texture.magFilter = THREE.NearestFilter;
++texture.wrapS = THREE.RepeatWrapping;
++texture.wrapT = THREE.RepeatWrapping;
+const uniforms = {
+ iTime: { value: 0 },
+ iResolution: { value: new THREE.Vector3() },
++ iChannel0: { value: texture },
+};
+```
+
+{{{example url="../threejs-shadertoy-bleepy-blocks.html" }}}
+
+여태까지는 [쉐이더토이 사이트](https://shadertoy.com)에 나와있는 대로 캔버스 전체에 쉐이더를 구현했습니다. 하지만 쉐이더를 사용할 때 꼭 예제 형식에 얽매일 필요는 없겠죠. 쉐이더토이의 작가들은 대부분 `fragCoord`와 `iResolution`을 사용한다는 것만 기억하면 됩니다. `fragCoord`가 꼭 픽셀의 좌표여야할 이유는 없다는 말입니다. 이를 텍스처 좌표로 바꿔 쉐이더를 텍스처처럼 사용할 수도 있죠. 이렇게 쉐이더 함수로 텍스처를 만드는 기법을 [*절차적 텍스처(procedural texture)*](https://www.google.com/search?q=procedural+texture)라고 합니다.
+
+예제에 이 기법을 적용해봅시다. Three.js에서 텍스처 좌표를 받아 여기에 `iResolution`을 곱해 `fragCoord`에 넘기는 게 제일 간단할 듯하네요.
+
+먼저 fragment 쉐이더에서 쓸 *varying*을 추가합니다. varying은 vertex(정점) 쉐이더에서 fragment 쉐이더에 넘겨주는 값으로, 각 정점 사이를 보간한(점진적으로 채운(varied)) 값입니다. Three.js가 텍스처 좌표를 `uv` 앞에 *varying*을 이니셜인 `v`를 붙여 표시하니 그 이름을 그대로 사용하겠습니다.
+
+```glsl
+...
+
++varying vec2 vUv;
+
+void main() {
+- mainImage(gl_FragColor, gl_FragCoord.xy);
++ mainImage(gl_FragColor, vUv * iResolution.xy);
+}
+```
+
+추가로 vertex 쉐이더를 만들어야 합니다. 아래는 가장 간단한 형태의 Three.js vertex 쉐이더로, `uv`, `projectionMatrix`, `modelViewMatrix`, `position` 등의 변수는 Three.js가 선언해줄 겁니다.
+
+```js
+const vertexShader = `
+ varying vec2 vUv;
+ void main() {
+ vUv = uv;
+ gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
+ }
+`;
+```
+
+vertex 쉐이더도 같이 `ShaderMaterial`에 넘겨줍니다.
+
+```js
+const material = new THREE.ShaderMaterial({
+ vertexShader,
+ fragmentShader,
+ uniforms,
+});
+```
+
+텍스처의 크기는 바뀔 일이 없으니 `iResolution` 균등 변수의 초기값을 미리 설정합니다.
+
+```js
+const uniforms = {
+ iTime: { value: 0 },
+- iResolution: { value: new THREE.Vector3() },
++ iResolution: { value: new THREE.Vector3(1, 1, 1) },
+ iChannel0: { value: texture },
+};
+```
+
+`render` 함수 안에 있던 코드도 삭제합니다.
+
+```js
+-const canvas = renderer.domElement;
+-uniforms.iResolution.value.set(canvas.width, canvas.height, 1);
+uniforms.iTime.value = time;
+```
+
+여기에 [반응형 디자인에 관한 글](threejs-responsive.html)에서 카메라와 회전하는 정육면체 3개를 가져왔습니다. 이제 한 번 실행해보죠.
+
+{{{example url="../threejs-shadertoy-as-texture.html" }}}
+
+이 글이 Three.js에서 쉐이더토이의 쉐이더를 활용하는 데 도움이 되었으면 합니다. 누차 말하지만 쉐이더토이의 쉐이더는 실제 사용하기 위해 제작되었다기보다-함수 하나로 모든 요소를 만드는-연습용 챌린지에 가깝습니다. 하지만 그래도 쉐이더토이에 올라온 쉐이더들은 여전히 인상 깊고, 놀랍습니다. 배울 점도 굉장히 많죠. | false |
Other | mrdoob | three.js | ab940f9e2a4976e8ed787ddb8871018d849f030d.json | fix offscreen to use es6 modules | threejs/lessons/threejs-offscreencanvas.md | @@ -10,15 +10,11 @@ to a web worker so as not to slow down the responsiveness of the browser. It
also means data is loaded and parsed in the worker so possibly less jank while
the page loads.
-One big issue with offscreen canvas is, at least in Chrome, es6 modules are not yet
-supported on web workers, so, unlike all the other examples on this site that use
-es6 modules these examples will use class scripts.
-
Getting *started* using it is pretty straight forward. Let's port the 3 spinning cube
example from [the article on responsiveness](threejs-responsive.html).
Workers generally have their code separated
-into another script file. Most of the examples on this site have had
+into another script file whereas most of the examples on this site have had
their scripts embedded into the HTML file of the page they are on.
In our case we'll make a file called `offscreencanvas-cubes.js` and
@@ -37,14 +33,14 @@ function main() {
...
```
-We can then start our worker with `new Worker(pathToScript)`.
+We can then start our worker with `new Worker(pathToScript, {type: 'module'})`.
and pass the `offscreen` object to it.
```js
function main() {
const canvas = document.querySelector('#c');
const offscreen = canvas.transferControlToOffscreen();
- const worker = new Worker('offscreencanvas-cubes.js');
+ const worker = new Worker('offscreencanvas-cubes.js', {type: 'module'});
worker.postMessage({type: 'main', canvas: offscreen}, [offscreen]);
}
main();
@@ -53,7 +49,7 @@ main();
It's important to note that workers can't access the `DOM`. They
can't look at HTML elements nor can they receive mouse events or
keyboard events. The only thing they can generally do is respond
-to messages sent to them.
+to messages sent to them and send messages back to the page.
To send a message to a worker we call [`worker.postMessage`](https://developer.mozilla.org/en-US/docs/Web/API/Worker/postMessage) and
pass it 1 or 2 arguments. The first argument is a JavaScript object
@@ -69,7 +65,8 @@ so once transferred the `offscreen` object back in the main page is useless.
Workers receive messages from their `onmessage` handler. The object
we passed to `postMessage` arrives on `event.data` passed to the `onmessage`
handler on the worker. The code above declares a `type: 'main'` in the object it passes
-to the worker. We'll make a handler that based on `type` calls
+to the worker. This object has no meaning to the browser. It's entirely for
+our own usage. We'll make a handler that based on `type` calls
a different function in the worker. Then we can add functions as
needed and easily call them from the main page.
@@ -93,13 +90,7 @@ that was sent from the main page.
So now we just need to start changing the `main` we pasted into
`offscreencanvas-cubes.js` from [the responsive article](threejs-responsive.html).
-The first thing we need to do is include THREE.js into our worker.
-
-```js
-importScripts('resources/threejs/r119/build/three.min.js');
-```
-
-Then instead of looking up the canvas from the DOM we'll receive it from the
+Instead of looking up the canvas from the DOM we'll receive it from the
event data.
```js
@@ -189,7 +180,7 @@ function render(time) {
Back in the main page we'll send a `size` event anytime the page changes size.
```js
-const worker = new Worker('offscreencanvas-picking.js');
+const worker = new Worker('offscreencanvas-picking.js', {type: 'module'});
worker.postMessage({type: 'main', canvas: offscreen}, [offscreen]);
+function sendSize() {
@@ -245,7 +236,7 @@ function main() {
+ return;
+ }
const offscreen = canvas.transferControlToOffscreen();
- const worker = new Worker('offscreencanvas-picking.js');
+ const worker = new Worker('offscreencanvas-picking.js', {type: 'module});
worker.postMessage({type: 'main', canvas: offscreen}, [offscreen]);
...
@@ -266,7 +257,7 @@ the canvas in the main page like normal.
> running in the main page. What you do is really up to you.
The first thing we should probably do is separate out the three.js
-code from the code that is specific to the worker. That we we can
+code from the code that is specific to the worker. That way we can
use the same code on both the main page and the worker. In other words
we will now have 3 files
@@ -283,19 +274,53 @@ we will now have 3 files
`offscreencanvas-worker-cubes.js`
`shared-cubes.js` and `offscreencanvas-worker-cubes.js` are basically
-the split of our previous `offscreencanvas-cubes.js` file.
-We renamed `main` to `init` since we already have a `main` in our
-HTML file.
+the split of our previous `offscreencanvas-cubes.js` file. First we
+copy all of `offscreencanvas-cubes.js` to `shared-cube.js`. Then
+we rename `main` to `init` since we already have a `main` in our
+HTML file and we need to export `init` and `state`
-`offscreencanvas-worker-cubes.js` is just
+```js
+import * as THREE from './resources/threejs/r119/build/three.module.js';
+
+-const state = {
++export const state = {
+ width: 300, // canvas default
+ height: 150, // canvas default
+};
+
+-function main(data) {
++export function init(data) {
+ const {canvas} = data;
+ const renderer = new THREE.WebGLRenderer({canvas});
+```
+
+and cut out the just the non three.js relates parts
```js
-'use strict';
+-function size(data) {
+- state.width = data.width;
+- state.height = data.height;
+-}
+-
+-const handlers = {
+- main,
+- size,
+-};
+-
+-self.onmessage = function(e) {
+- const fn = handlers[e.data.type];
+- if (!fn) {
+- throw new Error('no handler for type: ' + e.data.type);
+- }
+- fn(e.data);
+-};
+```
-/* global importScripts, init, state */
+Then we copy those parts we just deleted to `offscreencanvas-worker-cubes.js`
+and import `shared-cubes.js` as well as call `init` instead of `main`.
-importScripts('resources/threejs/r119/build/three.min.js');
-+importScripts('shared-cubes.js');
+```js
+import {init, state} from './shared-cubes.js';
function size(data) {
state.width = data.width;
@@ -317,13 +342,11 @@ self.onmessage = function(e) {
};
```
-note we include `shared-cubes.js` which is all our three.js code
-
-Similarly we need to include three.js and `shared-cubes.js` in the main page
+Similarly we need to include `shared-cubes.js` in the main page
```html
-<script src="resources/threejs/r119/build/three.min.js"></script>
-<script src="shared-cubes.js"><script>
+<script type="module">
++import {init, state} from './shared-cubes.js';
```
We can remove the HTML and CSS we added previously
@@ -362,7 +385,7 @@ function main() {
- return;
- }
- const offscreen = canvas.transferControlToOffscreen();
-- const worker = new Worker('offscreencanvas-picking.js');
+- const worker = new Worker('offscreencanvas-picking.js', {type: 'module'});
- worker.postMessage({type: 'main', canvas: offscreen}, [offscreen]);
+ if (canvas.transferControlToOffscreen) {
+ startWorker(canvas);
@@ -377,8 +400,8 @@ We'll move all the code we had to setup the worker inside `startWorker`
```js
function startWorker(canvas) {
const offscreen = canvas.transferControlToOffscreen();
- const worker = new Worker('offscreencanvas-worker-cubes.js');
- worker.postMessage({type: 'init', canvas: offscreen}, [offscreen]);
+ const worker = new Worker('offscreencanvas-worker-cubes.js', {type: 'module'});
+ worker.postMessage({type: 'main', canvas: offscreen}, [offscreen]);
function sendSize() {
worker.postMessage({
@@ -395,6 +418,13 @@ function startWorker(canvas) {
}
```
+and send `init` instead of `main`
+
+```js
+- worker.postMessage({type: 'main', canvas: offscreen}, [offscreen]);
++ worker.postMessage({type: 'init', canvas: offscreen}, [offscreen]);
+```
+
for starting in the main page we can do this
```js
@@ -514,7 +544,7 @@ to the worker or the main page.
function startWorker(canvas) {
const offscreen = canvas.transferControlToOffscreen();
- const worker = new Worker('offscreencanvas-worker-picking.js');
+ const worker = new Worker('offscreencanvas-worker-picking.js', {type: 'module'});
worker.postMessage({type: 'init', canvas: offscreen}, [offscreen]);
+ sendMouse = (x, y) => {
@@ -609,7 +639,7 @@ and the keyboard.
Unlike our code so far we can't really use a global `state` object
without re-writing all the OrbitControls code to work with it.
-The OrbitControls take an element to which they attach most
+The OrbitControls take an `HTMLElement` to which they attach most
of the DOM events they use. Maybe we could pass in our own
object that has the same API surface as a DOM element.
We only need to support the features the OrbitControls need.
@@ -648,7 +678,9 @@ tell the difference.
Here's the code for the worker part.
```js
-class ElementProxyReceiver extends THREE.EventDispatcher {
+import {EventDispatcher} from './resources/threejs/r119/build/three.module.js';
+
+class ElementProxyReceiver extends EventDispatcher {
constructor() {
super();
}
@@ -728,19 +760,13 @@ self.onmessage = function(e) {
};
```
-We also need to actually add the `OrbitControls` to the top of
-the script
+In our shared three.js code we need to import the `OrbitControls` and set them up.
```js
-importScripts('resources/threejs/r119/build/three.min/js');
-+importScripts('resources/threejs/r119/examples/js/controls/OrbitControls.js');
-*importScripts('shared-orbitcontrols.js');
-```
-
-and in our shared three.js code we need to set them up
+import * as THREE from './resources/threejs/r119/build/three.module.js';
++import {OrbitControls} from './resources/threejs/r119/examples/jsm/controls/OrbitControls.js';
-```js
-function init(data) {
+export function init(data) {
- const {canvas} = data;
+ const {canvas, inputElement} = data;
const renderer = new THREE.WebGLRenderer({canvas});
@@ -849,7 +875,7 @@ When we start the worker we first make a proxy and pass in our event handlers.
```js
function startWorker(canvas) {
const offscreen = canvas.transferControlToOffscreen();
- const worker = new Worker('offscreencanvas-worker-orbitcontrols.js');
+ const worker = new Worker('offscreencanvas-worker-orbitcontrols.js', {type: 'module'});
+ const eventHandlers = {
+ contextmenu: preventDefaultHandler,
@@ -1085,7 +1111,7 @@ class ElementProxy {
and in our shared three.js code we no longer need `state`
```js
--const state = {
+-export const state = {
- width: 300, // canvas default
- height: 150, // canvas default
-};
@@ -1117,28 +1143,21 @@ function render(time) {
...
```
-A few more hacks. The OrbitControls attach event handlers to `window` to
-get keyboard events. Not sure that's the right place to attach them but that's beyond our control
-unless we fork the OrbitControls. In any case `window` doesn't exist in a worker.
+A few more hacks. The OrbitControls add `mousemove` and `mouseup` events to the
+`ownerDocument` of the element to handle mouse capture (when the mouse goes
+outside the window).
-They also also add `mousemove` and `mouseup` events to the `document`
-to handle mouse capture (when the mouse goes outside the window) but
-like `window` there is no `document` in a worker.
+Further the code references the global `document` but there is no global document
+in a worker.
-Further the code compares `document` to the element we pass into `OrbitControls`
-and expects them to not be equal.
-
-We can solve all of these with a few quick hacks. In our worker
-code we'll re-use our proxy for all 3 problems.
+We can solve all of these with a 2 quick hacks. In our worker
+code we'll re-use our proxy for both problems.
```js
function start(data) {
const proxy = proxyManager.getProxy(data.canvasId);
-+ self.window = proxy; // HACK!
-+ self.document = { // HACK!
-+ addEventListener: proxy.addEventListener.bind(proxy),
-+ removeEventListener: proxy.removeEventListener.bind(proxy),
-+ };
++ proxy.ownerDocument = proxy; // HACK!
++ self.document = {} // HACK!
init({
canvas: data.canvas,
inputElement: proxy, | true |
Other | mrdoob | three.js | ab940f9e2a4976e8ed787ddb8871018d849f030d.json | fix offscreen to use es6 modules | threejs/offscreencanvas-cubes.js | @@ -1,8 +1,4 @@
-'use strict'; // eslint-disable-line
-
-/* global importScripts, THREE */
-
-importScripts('resources/threejs/r119/build/three.min.js');
+import * as THREE from './resources/threejs/r119/build/three.module.js';
const state = {
width: 300, // canvas default | true |
Other | mrdoob | three.js | ab940f9e2a4976e8ed787ddb8871018d849f030d.json | fix offscreen to use es6 modules | threejs/offscreencanvas-worker-cubes.js | @@ -1,9 +1,4 @@
-'use strict';
-
-/* global importScripts, init, state */
-
-importScripts('resources/threejs/r119/build/three.min.js');
-importScripts('shared-cubes.js');
+import {init, state} from './shared-cubes.js';
function size(data) {
state.width = data.width; | true |
Other | mrdoob | three.js | ab940f9e2a4976e8ed787ddb8871018d849f030d.json | fix offscreen to use es6 modules | threejs/offscreencanvas-worker-orbitcontrols.js | @@ -1,15 +1,10 @@
-'use strict';
-
-/* global importScripts, init, THREE */
-
-importScripts('resources/threejs/r119/build/three.min.js');
-importScripts('resources/threejs/r119/examples/js/controls/OrbitControls.js');
-importScripts('shared-orbitcontrols.js');
+import {init} from './shared-orbitcontrols.js';
+import {EventDispatcher} from './resources/threejs/r119/build/three.module.js';
function noop() {
}
-class ElementProxyReceiver extends THREE.EventDispatcher {
+class ElementProxyReceiver extends EventDispatcher {
constructor() {
super();
}
@@ -68,12 +63,8 @@ const proxyManager = new ProxyManager();
function start(data) {
const proxy = proxyManager.getProxy(data.canvasId);
- proxy.body = proxy; // HACK!
- self.window = proxy;
- self.document = {
- addEventListener: proxy.addEventListener.bind(proxy),
- removeEventListener: proxy.removeEventListener.bind(proxy),
- };
+ proxy.ownerDocument = proxy; // HACK!
+ self.document = {}; // HACK!
init({
canvas: data.canvas,
inputElement: proxy, | true |
Other | mrdoob | three.js | ab940f9e2a4976e8ed787ddb8871018d849f030d.json | fix offscreen to use es6 modules | threejs/offscreencanvas-worker-picking.js | @@ -1,9 +1,4 @@
-'use strict';
-
-/* global importScripts, init, state, pickPosition */
-
-importScripts('resources/threejs/r119/build/three.min.js');
-importScripts('shared-picking.js');
+import {state, init, pickPosition} from './shared-picking.js';
function size(data) {
state.width = data.width; | true |
Other | mrdoob | three.js | ab940f9e2a4976e8ed787ddb8871018d849f030d.json | fix offscreen to use es6 modules | threejs/shared-cubes.js | @@ -1,9 +1,11 @@
-const state = {
+import * as THREE from './resources/threejs/r119/build/three.module.js';
+
+export const state = {
width: 300, // canvas default
height: 150, // canvas default
};
-function init(data) { /* eslint-disable-line no-unused-vars */
+export function init(data) { /* eslint-disable-line no-unused-vars */
const {canvas} = data;
const renderer = new THREE.WebGLRenderer({canvas});
| true |
Other | mrdoob | three.js | ab940f9e2a4976e8ed787ddb8871018d849f030d.json | fix offscreen to use es6 modules | threejs/shared-orbitcontrols.js | @@ -1,4 +1,7 @@
-function init(data) { /* eslint-disable-line no-unused-vars */
+import * as THREE from './resources/threejs/r119/build/three.module.js';
+import {OrbitControls} from './resources/threejs/r119/examples/jsm/controls/OrbitControls.js';
+
+export function init(data) { /* eslint-disable-line no-unused-vars */
const {canvas, inputElement} = data;
const renderer = new THREE.WebGLRenderer({canvas});
@@ -9,7 +12,7 @@ function init(data) { /* eslint-disable-line no-unused-vars */
const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
camera.position.z = 4;
- const controls = new THREE.OrbitControls(camera, inputElement);
+ const controls = new OrbitControls(camera, inputElement);
controls.target.set(0, 0, 0);
controls.update();
| true |
Other | mrdoob | three.js | ab940f9e2a4976e8ed787ddb8871018d849f030d.json | fix offscreen to use es6 modules | threejs/shared-picking.js | @@ -1,11 +1,13 @@
-const state = {
+import * as THREE from './resources/threejs/r119/build/three.module.js';
+
+export const state = {
width: 300, // canvas default
height: 150, // canvas default
};
-const pickPosition = {x: 0, y: 0};
+export const pickPosition = {x: 0, y: 0};
-function init(data) { // eslint-disable-line no-unused-vars
+export function init(data) { // eslint-disable-line no-unused-vars
const {canvas} = data;
const renderer = new THREE.WebGLRenderer({canvas});
| true |
Other | mrdoob | three.js | ab940f9e2a4976e8ed787ddb8871018d849f030d.json | fix offscreen to use es6 modules | threejs/threejs-offscreencanvas-w-fallback.html | @@ -19,16 +19,12 @@
<body>
<canvas id="c"></canvas>
</body>
-<script src="resources/threejs/r119/build/three.min.js"></script>
-<script src="shared-cubes.js"></script>
-<script>
-'use strict'; // eslint-disable-line
-
-/* globals state, init */
+<script type="module">
+import {init, state} from './shared-cubes.js';
function startWorker(canvas) {
const offscreen = canvas.transferControlToOffscreen();
- const worker = new Worker('offscreencanvas-worker-cubes.js');
+ const worker = new Worker('offscreencanvas-worker-cubes.js', {type: 'module'});
worker.postMessage({type: 'init', canvas: offscreen}, [offscreen]);
function sendSize() { | true |
Other | mrdoob | three.js | ab940f9e2a4976e8ed787ddb8871018d849f030d.json | fix offscreen to use es6 modules | threejs/threejs-offscreencanvas-w-orbitcontrols.html | @@ -22,13 +22,8 @@
<body>
<canvas id="c" tabindex="1"></canvas>
</body>
-<script src="resources/threejs/r119/build/three.min.js"></script>
-<script src="resources/threejs/r119/examples/js/controls/OrbitControls.js"></script>
-<script src="shared-orbitcontrols.js"></script>
-<script>
-'use strict'; // eslint-disable-line
-
-/* global init */
+<script type="module">
+import {init} from './shared-orbitcontrols.js';
const mouseEventHandler = makeSendPropertiesHandler([
'ctrlKey',
@@ -146,7 +141,7 @@
function startWorker(canvas) {
canvas.focus();
const offscreen = canvas.transferControlToOffscreen();
- const worker = new Worker('offscreencanvas-worker-orbitcontrols.js');
+ const worker = new Worker('offscreencanvas-worker-orbitcontrols.js', {type: 'module'});
const eventHandlers = {
contextmenu: preventDefaultHandler, | true |
Other | mrdoob | three.js | ab940f9e2a4976e8ed787ddb8871018d849f030d.json | fix offscreen to use es6 modules | threejs/threejs-offscreencanvas-w-picking.html | @@ -19,19 +19,14 @@
<body>
<canvas id="c"></canvas>
</body>
-<script src="resources/threejs/r119/build/three.min.js"></script>
-<script src="resources/threejs/r119/examples/js/controls/OrbitControls.js"></script>
-<script src="shared-picking.js"></script>
-<script>
-'use strict'; // eslint-disable-line
-
-/* global state, init, pickPosition */
+<script type="module">
+import {state, init, pickPosition} from './shared-picking.js';
let sendMouse;
function startWorker(canvas) {
const offscreen = canvas.transferControlToOffscreen();
- const worker = new Worker('offscreencanvas-worker-picking.js');
+ const worker = new Worker('offscreencanvas-worker-picking.js', {type: 'module'});
worker.postMessage({type: 'init', canvas: offscreen}, [offscreen]);
sendMouse = (x, y) => { | true |
Other | mrdoob | three.js | ab940f9e2a4976e8ed787ddb8871018d849f030d.json | fix offscreen to use es6 modules | threejs/threejs-offscreencanvas.html | @@ -31,9 +31,7 @@
<div>no OffscreenCanvas support</div>
</div>
</body>
-<script>
-'use strict'; // eslint-disable-line
-
+<script type="module">
function main() { /* eslint consistent-return: 0 */
const canvas = document.querySelector('#c');
if (!canvas.transferControlToOffscreen) {
@@ -42,7 +40,7 @@
return;
}
const offscreen = canvas.transferControlToOffscreen();
- const worker = new Worker('offscreencanvas-cubes.js');
+ const worker = new Worker('offscreencanvas-cubes.js', {type: 'module'});
worker.postMessage({type: 'main', canvas: offscreen}, [offscreen]);
function sendSize() { | true |
Other | mrdoob | three.js | 63be4938a7251adb6792a4213696c1dde5457763.json | make this work as an es6 module.
We should probably make it an es6 module. | threejs/resources/webgl-debug-helper.js | @@ -29,7 +29,7 @@
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-/* global define */
+/* global define, globalThis */
(function(root, factory) { // eslint-disable-line
if (typeof define === 'function' && define.amd) {
@@ -41,7 +41,7 @@
// Browser globals
root.webglDebugHelper = factory.call(root);
}
-}(this, function() {
+}(this || globalThis, function() {
'use strict'; // eslint-disable-line
//------------ [ from https://github.com/KhronosGroup/WebGLDeveloperTools ] | false |
Other | mrdoob | three.js | e11e17b7587e7146fb08a8d08a23c9fe04a5397f.json | try more translation hints | build/templates/example.template | @@ -1,5 +1,5 @@
<div translate="no" class="threejs_example_container notranslate">
- <div><iframe class="threejs_example" style="{{width}} {{height}}" src="/threejs/resources/editor.html?url={{{examplePath}}}{{{encodedUrl}}}{{{params}}}"></iframe></div>
+ <div><iframe class="threejs_example notranslate" translate="no" style="{{width}} {{height}}" src="/threejs/resources/editor.html?url={{{examplePath}}}{{{encodedUrl}}}{{{params}}}"></iframe></div>
<a class="threejs_center" href="{{{examplePath}}}{{{url}}}" target="_blank">{{{caption}}}</a>
</div>
| true |
Other | mrdoob | three.js | e11e17b7587e7146fb08a8d08a23c9fe04a5397f.json | try more translation hints | threejs/lessons/resources/lesson.js | @@ -361,9 +361,8 @@ $(document).ready(function($){
window.prettyPrint();
}
$('span[class=com]')
- .replaceWith(function() {
- return $('<span class="com notranslate" translate="yes">' + this.innerHTML + '</span>');
- });
+ .addClass('translate yestranslate')
+ .attr('translate', 'yes');
const params = getQueryParams();
if (params.doubleSpace || params.doublespace) { | true |
Other | mrdoob | three.js | 5c52e7f38a29c2c59cad3275e97beb194123d1fb.json | add translate attributes | build/templates/example.template | @@ -1,4 +1,4 @@
-<div class="threejs_example_container">
+<div translate="no" class="threejs_example_container">
<div><iframe class="threejs_example" style="{{width}} {{height}}" src="/threejs/resources/editor.html?url={{{examplePath}}}{{{encodedUrl}}}{{{params}}}"></iframe></div>
<a class="threejs_center" href="{{{examplePath}}}{{{url}}}" target="_blank">{{{caption}}}</a>
</div> | true |
Other | mrdoob | three.js | 5c52e7f38a29c2c59cad3275e97beb194123d1fb.json | add translate attributes | threejs/lessons/resources/lesson.js | @@ -355,11 +355,15 @@ $(document).ready(function($){
$('pre>code')
.unwrap()
.replaceWith(function() {
- return $('<pre class="prettyprint showlinemods">' + this.innerHTML + '</pre>');
+ return $('<pre class="prettyprint showlinemods" translate="no">' + this.innerHTML + '</pre>');
});
if (window.prettyPrint) {
window.prettyPrint();
}
+ $('span[class=com]')
+ .replaceWith(function() {
+ return $('<span class="com" translate="yes">' + this.innerHTML + '</span>');
+ });
const params = getQueryParams();
if (params.doubleSpace || params.doublespace) { | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.