diff --git a/.claude/launch.json b/.claude/launch.json new file mode 100644 index 00000000000..2b224ba6a31 --- /dev/null +++ b/.claude/launch.json @@ -0,0 +1,17 @@ +{ + "version": "0.0.1", + "configurations": [ + { + "name": "tinkerbit-dev", + "runtimeExecutable": "npx", + "runtimeArgs": ["cross-env", "NODE_OPTIONS=--openssl-legacy-provider", "webpack-dev-server", "--host", "127.0.0.1"], + "port": 8601 + }, + { + "name": "iot-api-dev", + "runtimeExecutable": "npx", + "runtimeArgs": ["cross-env", "AUTH_DISABLED=1", "IOT_BROKER_MODE=none", "npm", "--prefix", "services/iot-api", "start"], + "port": 20114 + } + ] +} diff --git a/.env.example b/.env.example new file mode 100644 index 00000000000..fe59b1b9c96 --- /dev/null +++ b/.env.example @@ -0,0 +1,17 @@ +# Google OAuth (Web application client) +GOOGLE_CLIENT_ID= +GOOGLE_CLIENT_SECRET= + +# 32+ character random secret used to sign session cookies +AUTH_SECRET= + +# Public site origin (no trailing slash) +# Production: https://www.tinkerbit.io +# Local vercel dev: http://127.0.0.1:3000 +AUTH_BASE_URL=https://www.tinkerbit.io + +# Local only: set to 1 to skip Google login outside Vercel production +# AUTH_DISABLED=1 + +# Microsoft Clarity project ID (Settings → Overview in clarity.microsoft.com) +CLARITY_ID= diff --git a/.env.local.example b/.env.local.example new file mode 100644 index 00000000000..1cf0932daec --- /dev/null +++ b/.env.local.example @@ -0,0 +1,4 @@ +# Auth helpers for local checks (no Google secrets required) +AUTH_SECRET=local-dev-secret-at-least-32-chars-long +AUTH_BASE_URL=http://127.0.0.1:3000 +AUTH_DISABLED=1 diff --git a/.eslintignore b/.eslintignore index 93c033154fb..86be67b5e65 100644 --- a/.eslintignore +++ b/.eslintignore @@ -1,3 +1,6 @@ node_modules/* build/* dist/* +module-test/* +prototypes/micropython/* +src/beginner-studio/components/module-icons/module-icons.js diff --git a/.gitattributes b/.gitattributes index 811d7e4fa87..93624964c61 100644 --- a/.gitattributes +++ b/.gitattributes @@ -38,4 +38,12 @@ Makefile text eol=lf README text eol=lf TRADEMARK text eol=lf +# Server deploy files run on Linux +*.sh text eol=lf +*.mjs text eol=lf +*.conf text eol=lf +*.service text eol=lf +*.timer text eol=lf +*.example text eol=lf + # Use CRLF for Windows-specific file types diff --git a/.gitignore b/.gitignore index 14a056e0df1..9141607a8ae 100644 --- a/.gitignore +++ b/.gitignore @@ -12,8 +12,23 @@ npm-* # Build /build /dist +/.generated /.opt-in # Generated translation files /translations /locale + +.vercel + +# Secrets / local keys +MakerShop.pem +*.pem +.env +.env.local +.env.*.local + +# Local recovery helpers +scripts/recover-from-transcript.js +scripts/apply-strreplace.js +scripts/recover-report.json diff --git a/.nvmrc b/.nvmrc new file mode 100644 index 00000000000..3c032078a4a --- /dev/null +++ b/.nvmrc @@ -0,0 +1 @@ +18 diff --git a/.vercelignore b/.vercelignore new file mode 100644 index 00000000000..937e18b7277 --- /dev/null +++ b/.vercelignore @@ -0,0 +1,9 @@ +MakerShop.pem +*.pem +scripts/recover-from-transcript.js +scripts/apply-strreplace.js +scripts/recover-report.json +serial_monitor_integration.md +build-log.txt +.git +node_modules diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md new file mode 100644 index 00000000000..a816f0c2a23 --- /dev/null +++ b/ARCHITECTURE.md @@ -0,0 +1,596 @@ +# TinkerBit — project documentation + +**Product:** browser studio for the Maker ESP32 RJ11 kit +**Modes:** Beginner (`/beginner`) and Advanced (`/ide`). **Advanced is locked** while we focus on Beginner (see "Advanced mode lock" in section 4.1). +**Audience:** students, teachers, and anyone who needs to see how the app is put together + +This is the project document. It is written as five parts: + +1. What TinkerBit is and what it includes +2. How a person uses Beginner and Advanced +3. The physical kit: modules, jacks, and the rules the software enforces +4. How the software is built: pages, login, codegen, MicroPython upload, compile, and flash +5. What can go wrong, how the app handles it, and where the code lives + +--- + +## 1. Product overview and features + +TinkerBit is a web application for a physical electronics kit. The board is a Maker ESP32 with RJ11 jacks. Students plug sensors and actuators into those jacks, then program the board in a browser. They do not install anything, and they do not type code unless they want to read what the app generated (MicroPython in Beginner, C++ in Advanced). + +The same kit is used in two products: + +| Mode | URL | Who it is for | How you program | +|------|-----|---------------|-----------------| +| **Beginner Studio** | `/beginner` | First lessons, classrooms, kit tours | Pick a module, plug it into a jack, click action blocks. Live MicroPython appears on the side. | +| **Advanced IDE** (locked) | `/ide` | Students who already know blocks | OpenBlock Blockly. Generic pin blocks, kit device blocks, motors, I2C, and Blynk. Paused for now: `/ide` redirects to Beginner. | + +The two modes reach the board in different ways, both from the browser over USB (Web Serial): + +- **Beginner** sends a MicroPython program straight to the board, with no compile step and no server in between, so it keeps working offline once the page has loaded. The board runs the **TinkerBit firmware**: MicroPython with the kit library built in, installed once per board with **Update board** (section 4.8). Teachers can switch Beginner back to Arduino C++ with `?board=arduino`. +- **Advanced** compiles an Arduino sketch on a server and flashes it (section 4.5). Flashing replaces the TinkerBit firmware, so a board used in Advanced needs Update board before the next Beginner upload. + +Chrome or Edge on a computer is required. A phone or Firefox cannot open the USB port. + +There is no student project database in this repository. Work lives in the browser session. Beginner templates load a ready-made wiring and program. Advanced projects use the IDE’s own save path. + +### 1.1 What the product includes + +**Accounts** + +- Google sign-in before Choose, Beginner, or Advanced. +- A **Choose** page: Beginner or Advanced. While Advanced is locked it shows as "Paused for now", not as a link. +- Localhost can open Choose without a session so developers can work offline. + +**Beginner Studio** + +- A drawing of the Maker ESP32 with labeled jacks (ST, D13, 3D, D5, MD, I2C, A1–A4, ESP, UART). +- A shelf of kit modules. Click a module, then click a jack that accepts it. Illegal jacks stay blocked and show a short hint. +- SVG cables from jack to module card. Cards can be dragged; the cable midpoint can bend. Moving a card does not change the GPIO in the sketch. +- A project library and a quick-start strip. Opening a project lands on **Build**, not Code, so the student sees the wiring first. +- A Code view: wait, repeat, if/else, print text, print a variable, plus one action per wired module (LED on/off/blink/brightness, read soil, print climate, and so on). +- A live code panel ("Your program as MicroPython") that updates whenever wiring or blocks change. That text is what Upload sends, as `main.py`. +- **Connect board**, **Upload**, and a serial monitor at **115200** (9600 when the project has an HC-05, which shares the USB serial line). **Start** restarts the board so the program's first lines show. +- **Update board** in the account menu: shows what the board runs and installs the TinkerBit firmware. +- A status bar that prints the jack map so a teacher can check a cable without opening this document. + +**Advanced IDE** + +- The OpenBlock / Scratch-style workspace: toolbox, canvas, hardware header, serial console. +- Maker ESP32 categories that were already there: digital write/read, analog read, L293D motors, stepper, I2C begin, Blynk. +- Maker Kit categories that match Beginner: sensors, outputs, radio (onboard BLE and HC-05). Every kit part has a block, including IR, PIR, reed, LDR, flame, water level, MPU6050, buzzer tones, LED brightness, pump and door lock. +- Compiles on the server and flashes over USB. This replaces the TinkerBit firmware on the board. + +**Upload and hardware** + +- Beginner (MicroPython): no compile. Upload writes `main.py` (plus the library files or Cloud settings when needed) through the MicroPython raw REPL at 115200, then restarts the program. A 3 KB program takes about 1 s. +- Advanced, and Beginner with `?board=arduino`: compile on a server (`arduino-cli`). The browser only receives firmware and writes it over USB. +- ESP32 download mode (Arduino flashing and Update board): classic auto-reset, slower laptop timing, USB-JTAG reset, then “hold BOOT”. +- Arduino Uno support stays in the code for old Advanced projects; the board list shows only the Maker ESP32. +- Beginner MicroPython programs print at 115200 (9600 with an HC-05). Arduino kit sketches print at 9600, Blynk sketches at 115200. The serial console must match. + +### 1.2 What the product does not do + +- It does not replace the Arduino IDE for arbitrary sketches you type yourself (Advanced can, but the compile server only allows three board types). +- It does not store class rosters or cloud projects in this repo. +- It does not run on Safari, Firefox, or a phone for upload. +- It does not ship Arduino sensor libraries to the browser. For Arduino sketches, the Servo, OLED, RFID, and pulse libraries must already be on the compile server. MicroPython drivers are part of the TinkerBit firmware. +- It does not run Edge AI in MicroPython yet. Edge AI needs Arduino mode (`?board=arduino`). + +--- + +## 2. User point of view + +This section is the path a student or teacher actually takes. + +### 2.1 First visit + +1. Open the site. +2. Sign in with Google. +3. On **How do you want to code?**, pick **Beginner** or **Advanced**. + +Beginner is the kit lesson: wire, click blocks, read the MicroPython, upload. Advanced is the full block IDE: more control, Blynk, and generic pins. + +### 2.2 Beginner — a typical lesson + +**Build is the home screen.** After you pick a template, you still land on Build. + +**Wire** + +1. Click a module in the shelf, for example **LED**. +2. Legal jacks highlight. For an LED the first choice is **D13** (GPIO 33). A1, A2, A3 also work. D5 does not — that jack is reserved for the ultrasonic sensor. +3. Click the jack. A card and a cable appear. +4. Add the rest of the lesson the same way. Some modules have only one jack: + + - HC-SR04 → **D5** only (Trig GPIO 26, Echo GPIO 25). + - RFID → **3D** only. Do not use D13 at the same time; they share GPIO 33. + - L293D or 4-channel relay → **MD**. + - Stepper → **ST**. + - OLED and HW-605 → **I2C** (they share the bus). + - Onboard BLE → no cable; it attaches to **ESP**. + - HC-05 → **UART** (RX GPIO 3, TX GPIO 1 — the same UART as USB). + +5. If a jack is wrong, the app shows a short reason instead of connecting. + +**Program** + +6. Open **Code**. The palette lists control blocks and the actions of whatever you wired. +7. Click **On / Off**, **Brightness**, **Blink**, **Read distance**, **Print soil moisture**, and so on. +8. LED brightness is 0–255 PWM on the same pin as On/Off. +9. Use **If…then** to compare a sensor (soil below 40, distance under 20 cm, button pressed). +10. Watch the code panel (MicroPython). You do not edit it for a normal lesson. + +**Upload and see output** + +11. Use **Chrome or Edge** on a computer. Use a data USB cable. +12. Close Arduino IDE Serial Monitor, Thonny, PuTTY, or another TinkerBit tab. Only one program can own the COM port. +13. Click **Connect board** and pick the ESP32 in the browser list. +14. The first time a board is used here (new kits come with an Arduino demo, and Advanced flashes Arduino too), open the account menu, choose **Update board** and install the TinkerBit firmware. This is once per board. Upload says so when it finds no MicroPython. +15. Click **Upload**. The Studio checks the board, stops the last program, installs the library files if they changed, writes your program as `main.py` and starts it. It usually takes a few seconds and uses no server. (With `?board=arduino` the sketch compiles on the server first, which can take minutes the first time.) +16. Start the serial monitor. Start restarts the board, so you see `TinkerBit Beginner ready` and then a line for each action (`LED: ON`, `HC-SR04 cm=42`, `Soil moisture=61 %`). + +**If Upload says the board is not ready** + +- "This board does not have MicroPython": run **Update board** once. +- "Older TinkerBit firmware": run **Update board**. "Newer TinkerBit firmware than this page": reload the page. +- "Cloud needs the TinkerBit firmware": the board has plain MicroPython; run **Update board**. +- A program that never gives control back (including HC-05 programs, which turn off Ctrl-C) is handled by Upload itself: it restarts the board in safe mode, which skips `main.py`. + +**If Update board (or an Arduino upload) sticks at about 5%** + +The firmware is ready. The board has not entered download mode. On many laptops the USB chip does not pulse DTR/RTS correctly. + +- Hold **BOOT** on the board until progress moves past ~12%, then release. +- Prefer a USB 2.0 port or a different cable. +- Unplug, wait two seconds, plug in, Connect again, then Upload while holding BOOT. + +**If the serial window is empty or looks like noise** + +- Beginner MicroPython programs use **115200**, or **9600** when the project has an HC-05. The monitor follows the project. +- Arduino kit sketches (Advanced, or Beginner with `?board=arduino`) use **9600**; Blynk sketches use **115200**. Set the hardware console to match the sketch you actually flashed. +- After an upload, press Start again. Start restarts the board; if nothing appears within 4 s, press RST once (some laptops start the board in its flashing mode when it is plugged in). + +### 2.3 Advanced — a typical session + +> **Locked for now.** `/ide` and the IDE example pages redirect to `/beginner` until Advanced mode is switched back on (section 4.1). The steps below describe it when it is open. + +1. Open `/ide`. It starts on the Maker ESP32, the only board in the board list. Other OpenBlock boards stay in the code (hidden by `KIT_DEVICE_ID` in [devices/index.jsx](src/lib/libraries/devices/index.jsx)), so old projects saved for them still open. +2. Drag blocks from **Maker Kit Sensors**, **Maker Kit Outputs**, or **Maker Kit Radio**, or from Digital / Analog / Motors / Stepper / I2C / Blynk. +3. On kit blocks, pick the jack (D13, A1, …). Labels match Beginner. A4 is shown as **A4 (BOOT)**. D5 is not in any jack list: only the HC-SR04 block uses it. Old projects saved with D4 or D5 fall back to D13 and the sketch says so in a comment. +4. Connect and Upload. Advanced always compiles an Arduino sketch, which replaces the TinkerBit firmware: run Update board before using that board in Beginner again. +5. Open the hardware console at 9600 for kit sketches. + +### 2.4 Classroom checklist + +- Browser: Chrome or Edge, desktop, HTTPS or localhost. +- Driver: if Windows does not show a COM port, install CH340 or CP210x for your USB chip. TinkerBit does not ship that driver. +- One serial owner: close the Arduino IDE monitor (or Thonny) before Connect. +- Firmware: run **Update board** once per board before the first Beginner lesson. A board last used in Advanced needs it again. +- Cable: data cable, not charge-only. +- Jacks: follow the table in section 3. Wrong jack is the most common hardware fail (DHT on D13, RFID plus LED on D13, ultrasonic on a single digital pin). + +--- + +## 3. Kit catalog, jacks, and software rules + +Beginner only offers modules that exist in the physical kit. Advanced kit blocks use the same GPIO map. + +### 3.1 Jack map + +| Jack | GPIOs | What it is for | +|------|-------|----------------| +| ST | 12, 13, 14, 27 | 4-wire stepper | +| D13 | 33 | Button, LED, 1-ch relay, servo (not DHT if you can avoid it) | +| 3D | 32 SS, 33 RST, 34 MISO; SPI SCK 16, MOSI 23 | RFID RC522. Conflicts with D13. | +| D5 | Echo 25, Trig 26 | HC-SR04 only. Echo must stay INPUT. | +| MD | 17, 5, 18, 19 | L293D motor A/B or 4-ch relay (active-low) | +| I2C | SDA 21, SCL 22 | OLED and/or HW-605 | +| A1 | 4 | Analog sensors; preferred DHT pin | +| A2 | 15 | Analog (strapping pin) | +| A3 | 2 | Analog (strapping pin) | +| A4 | 0 | Analog / BOOT. Do not hold LOW at reset. | +| ESP | — | Onboard BLE | +| UART | RX 3, TX 1 | HC-05 at 9600; shares UART0 with USB serial and the MicroPython REPL | + +### 3.2 Modules and what the student can do + +| Module | Typical jack | Actions in Beginner | +|--------|--------------|---------------------| +| Push button | D13 | Is pressed? (INPUT_PULLUP) | +| Potentiometer | A1–A4 | Read knob 0–4095 (averaged) | +| LED | D13 | On/Off, Brightness 0–255 PWM, Blink | +| Relay (1 ch) | D13 | On/Off | +| Servo | D13 | Set angle (ESP32Servo) | +| L293D | MD | Motor A/B speed and direction, stop | +| 4-ch relay | MD | Channel on/off, all off (active-low) | +| Stepper | ST | Move steps at an RPM | +| OLED | I2C | Show text, show number | +| MQ-2 | A1–A4 | Read / print raw gas (heater needs ~1 min; not ppm) | +| Microphone | A1–A4 | Read loudness | +| HW-605 pulse | I2C | Read BPM (MAX30102 @ 100 kHz) | +| MPU6050 motion | I2C | Tilt in degrees and shake 0–100 (plain `Wire`, address 0x68 or 0x69); the sensor Edge AI learns moves from | +| Capacitive soil | A1–A4 | Moisture 0–100% | +| DHT11 | A1 | Temp, humidity, print climate (sample every 2 s) | +| HC-SR04 | D5 | Distance cm (invalid echo → −1) | +| RFID RC522 | 3D | Read UID | +| BLE (onboard) | ESP | Advertise name, send text | +| HC-05 | UART | Send line, read line | + +Control blocks (no jack): Wait, Repeat, If…then, Print text, Print variable. + +### 3.3 Rules the software enforces + +These are the reasons a jack stays grey, or a sketch comment appears. + +| Rule | Why it exists | What the app does | +|------|---------------|-------------------| +| D13 and 3D cannot be used together | Both use GPIO 33 (D13 signal and RFID RST) | The second jack is blocked. Hint: unplug the other first. | +| D5 is ultrasonic only | Dual pins; driving Echo as an output heats the module | Digital modules cannot take D5. Code keeps Echo as INPUT. | +| A4 is BOOT (GPIO 0) | LOW at reset enters download mode | Dropdown says **A4 (BOOT)**. Code comments warn before `pinMode`. | +| DHT prefers A1 | GPIO 33 is a poor DHT data pin on this ESP32 | Auto-assign tries A1, A2, A3, then D13. Fail text says plug into A1. | +| RFID SPI is not on D5 | Ultrasonic already owns 25/26 | SCK=16, MOSI=23; SS/RST/MISO on 3D. | +| UART is USB serial | HC-05 RX/TX are U0RXD/U0TXD | Arduino: send/receive use `Serial` at 9600. MicroPython: the program moves the line to 9600 and turns off Ctrl-C (`kbd_intr(-1)`), so the monitor opens at 9600 and Upload gets back in through safe mode. Do not open a second monitor. | +| I2C is shared | OLED, HW-605 and MPU6050 are all 3.3 V I2C | They may share the I2C jacks; `Wire.begin` runs once. Pulse init uses 100 kHz, not 400 kHz. A missing MPU6050 is retried every 5 s and reads shake −1. | +| Soil is capacitive | Dry ≈ high ADC, wet ≈ low | Map raw ~3200→0%, ~1200→100%. Raw ≈ 0 is a cable fail. | +| MQ-2 / mic / pot noise | Single ADC reads swing | Average 12–16 samples with a short delay. | +| Analog is ADC2 | WiFi/BLE steal ADC2 | Comments: turn the radio off for stable reads. | +| 4-ch relay is active-low | Floating LOW turns channels on at power-up | Setup writes HIGH to 17/5/18/19 (off). ON drives LOW. MicroPython: `boot.py` does it on every boot, before `main.py`. | +| A2, A3, ST are strapping pins | Wrong level at reset can change boot | Jacks are flagged; A4 is the strongest warning. | +| Copies only on shared jacks | Parts with their own jack, I2C address or radio cannot be doubled | One-wire and analog parts (D13, A1–A4) can be added again: the copy keeps a number for life (`conn.n`), is named "LED 2" and reads into `name2` variables. Others say "already on the board". See [partCopies.js](src/beginner-studio/domain/partCopies.js). | + +LED default pin is **D13 = GPIO 33**. Brightness uses `analogWrite` on that same pin. + +--- + +## 4. Technical capability + +The running system has four layers, plus the optional TinkerBit Cloud service (section 4.6). Cloud has its own SQLite database; nothing else stores application data. + +```mermaid +flowchart LR + pages[Static pages] --> auth[Google session] + auth --> beginner[Beginner Studio] + auth --> ide[Advanced IDE] + auth --> iot[IoT Dashboard] + beginner -- "MicroPython (default)" --> repl[Web Serial raw REPL] + repl --> board[TinkerBit firmware] + beginner -. "?board=arduino" .-> compile[Compile server] + ide --> compile + compile --> flash[Web Serial flash] + iot --> cloud[iot-api + Mosquitto] +``` + +### 4.1 Pages and hosting + +Webpack writes several HTML apps into `build/` ([webpack.config.js](webpack.config.js)). [vercel.json](vercel.json) maps clean URLs onto those files and sets security headers (no iframe, no sniff). + +| URL | Built as | Purpose | +|-----|----------|---------| +| `/` | landing | Marketing | +| `/login` | login | Google sign-in | +| `/choose` | choose | Beginner vs Advanced | +| `/beginner` | beginnerStudio | Kit studio | +| `/ide` | IDE bundle | OpenBlock GUI (locked: redirects to `/beginner`) | +| `/iot`, `/iot/*` | iot | IoT Dashboard, full page (phone friendly) | + +Local development is usually `http://127.0.0.1:8601`. + +**Advanced mode lock.** One switch, `ADVANCED_MODE`, keeps the IDE closed unless it is set to `on`: + +- [middleware.js](middleware.js) redirects `/ide`, `/ide.html` and the IDE example pages (`blocks-only.html`, `compatibility-testing.html`, `player.html`) to `/beginner` with a 302, before any sign-in check. +- webpack bakes the same value into the pages ([advanced-mode.js](src/lib/advanced-mode.js)). The IDE page sends itself to `/beginner` (this also covers local dev, which has no middleware), the Choose page shows Advanced as paused, and the Beginner menu hides "Switch mode". +- To unlock: set `ADVANCED_MODE=on` in the Vercel project and redeploy, or run `ADVANCED_MODE=on npm start` locally. The IDE code and its build stay in place; the IDE build also copies `static/`, which Beginner needs for the bundled firmware. + +[middleware.js](middleware.js) also runs on `/choose`, `/beginner`, `/ide`, and `/iot` for sign-in. If auth is on and the session cookie is missing, the request goes to `/login?next=...`. If auth is off, the pages open. If auth is on but `AUTH_SECRET` or `GOOGLE_CLIENT_ID` is missing, login fails closed. + +`/api/compile` and `/api/compile/health` are not implemented in the frontend host. They are rewritten to the compile server. `/devices/*` and `/extensions/*` for the Advanced IDE are rewritten the same way. + +### 4.2 Sign-in + +| Step | File | +|------|------| +| Redirect to Google | [api/auth/google.mjs](api/auth/google.mjs) | +| Exchange code, set cookie | [api/auth/callback.mjs](api/auth/callback.mjs) | +| Who is signed in | [api/auth/me.mjs](api/auth/me.mjs) | +| Clear cookie | [api/auth/logout.mjs](api/auth/logout.mjs) | + +[lib/auth/session.mjs](lib/auth/session.mjs) signs the session. After login, `next` may only be `/choose`, `/beginner`, `/ide`, or `/iot`. The choose page calls [src/lib/auth-client.js](src/lib/auth-client.js). On localhost it allows the page through without a session. + +### 4.3 Beginner Studio internals + +[src/beginner-studio/App.jsx](src/beginner-studio/App.jsx) is a shell: top bar (Build / Code), quick start, the active view, status bar, project library. + +State lives in [src/beginner-studio/context/StudioContext.jsx](src/beginner-studio/context/StudioContext.jsx): + +- `connections` — `{ id, moduleId, portId, pin, offsetX, offsetY, bendX, bendY }` +- `program` — nested block tree (`children`, `elseChildren`) +- `selectedModule` — module waiting for a jack click +- `view` — `'build'` on first load and after a template load +- theme, project name, palette filters + +[src/beginner-studio/hooks/useStudioActions.js](src/beginner-studio/hooks/useStudioActions.js) is the only place that mutates that state. Wiring is **select then click**, not drag-onto-a-port. BLE calls `connect` on `ONBOARD` immediately. + +```mermaid +flowchart LR + shelf[Shelf] --> select[selectModule] + select --> jack[Compatible jack] + jack --> conn[connections] + palette[Palette] --> tree[program tree] + conn --> gen["generatePython (default) or generateArduino"] + tree --> gen + gen --> code[Live code panel] + code --> up[Upload] +``` + +| File | Role | +|------|------| +| [modules.js](src/beginner-studio/domain/modules.js) | Catalog, actions, includes | +| [ports.js](src/beginner-studio/domain/ports.js) | Jacks, GPIO, conflicts, `pickPortForModule` | +| [tree.js](src/beginner-studio/domain/tree.js) | Append, nest, delete blocks | +| [boardLanguage.js](src/beginner-studio/domain/boardLanguage.js) | MicroPython (default) or Arduino; `?board=arduino` / `?board=micropython`, remembered per browser | +| [pycodegen.js](src/beginner-studio/domain/pycodegen.js) | MicroPython `main.py` for the `tinkerbit` library (section 4.8) | +| [codegen.js](src/beginner-studio/domain/codegen.js) | Arduino sketch: includes, setup, loop, helpers | +| [templates.js](src/beginner-studio/domain/templates.js) | Named projects → connections + program | +| [useGeneratedCode.js](src/beginner-studio/hooks/useGeneratedCode.js) | Memoized program text in the active language | +| [BoardCanvas.jsx](src/beginner-studio/components/build/BoardCanvas.jsx) | SVG board, ports, cables | +| [useBoardUpload.js](src/beginner-studio/hooks/useBoardUpload.js) | Connect; Upload (MicroPython over the REPL, or compile and flash for Arduino); Update board | +| [useSerialMonitor.js](src/beginner-studio/hooks/useSerialMonitor.js) | Monitor at 115200 for MicroPython (9600 with an HC-05) or 9600 for Arduino; Start restarts the board | + +**MicroPython (default).** `main.py` imports `tinkerbit`, creates one object per wired part by jack name (`led = tinkerbit.Led("D13")`), prints `TinkerBit Beginner ready`, runs the setup lines, then loops over the program tree in `while True:`. GPIO numbers live only in the library's `board.py`. Details in section 4.8. + +**Arduino (`?board=arduino`).** Every generated sketch starts with `Serial.begin(9600)`, a short delay, and `TinkerBit Beginner ready`. Setup then configures only the modules that are actually wired. Loop is the program tree. Helpers (DHT bit-bang, `readAnalogAvg`, `soilRawToPercent`, `getDistanceTrigEcho`, RFID, BLE) are included only when needed. + +### 4.4 Advanced IDE internals + +The IDE shell is [src/containers/gui.jsx](src/containers/gui.jsx) (OpenBlock VM + Blockly). Maker ESP32 is a static extension: + +| File | Role | +|------|------| +| [pin-map.js](static/extensions/makerEsp32/pin-map.js) | Same GPIO numbers as Beginner | +| [blocks.js](static/extensions/makerEsp32/blocks.js) | Block shapes | +| [toolbox.js](static/extensions/makerEsp32/toolbox.js) | Digital, Analog, Motors, Stepper, I2C, Kit Sensors, Kit Outputs, Kit Radio, Blynk | +| [generator.js](static/extensions/makerEsp32/generator.js) | C++ per block; kit helpers copied from Beginner | +| [translations.js](static/extensions/makerEsp32/translations.js) | Labels | + +Sensor blocks read the same active level as Beginner (IR, reed and flame are LOW when triggered; PIR and LDR are HIGH). Pump, lock and buzzer blocks write LOW in setup so a relay does not click on at boot. The MPU6050 blocks add the same raw-Wire driver Beginner uses. [maker-esp32-extension.test.js](test/unit/maker-esp32-extension.test.js) checks that every toolbox block has a shape, a label and a generator. + +Unlike Beginner, the IDE does not stop two blocks from using pins that share a GPIO (D13 and the RFID reset are both GPIO 33). + +Kit blocks force `Serial.begin(9600)`. Blynk blocks force `Serial.begin(115200)`. If both appear in one workspace, the last `Serial.begin` the generator writes wins. Match the console to that sketch. + +### 4.5 Compile and flash + +Used by the Advanced IDE, by Beginner with `?board=arduino`, and by the Edge AI recorder (Arduino only). Beginner's default MicroPython upload skips this path entirely (section 4.8). + +```mermaid +flowchart LR + ui["Advanced, or Beginner with ?board=arduino"] --> client[compile-client.js] + client --> rewrite["/api/compile"] + rewrite --> api[compile-api] + api --> cli[arduino-cli] + cli --> bin[HEX or ESP images] + bin --> port[Web Serial] +``` + +**Browser.** [src/lib/web-serial/compile-client.js](src/lib/web-serial/compile-client.js) POSTs `{ source, fqbn }` (3 minute timeout) and checks `/api/compile/health`. + +[src/lib/web-serial/device-profiles.js](src/lib/web-serial/device-profiles.js): + +| Board | FQBN | Flash | Monitor | Open for flash | +|-------|------|-------|---------|----------------| +| Uno | `arduino:avr:uno` | STK500 | 9600 | 115200 | +| Maker ESP32 | `esp32:esp32:esp32` | esptool | 9600 | 115200 | +| ESP32-S3 | `esp32:esp32:esp32s3` | esptool | 9600 | 115200 | + +[src/lib/web-serial/upload-pipeline.js](src/lib/web-serial/upload-pipeline.js): refuse a second upload, compile, stop the monitor, close the port, flash, close again, notify the monitor. + +ESP32 boot ([esptool-flash.js](src/lib/web-serial/esptool-flash.js)), in order: + +1. Classic DTR/RTS reset +2. Slower reset (laptop USB timing) +3. USB-JTAG reset +4. Manual BOOT (log: hold the button; 60 s timeout) + +Flash baud stays **115200**. Faster rates fail on common CP210x chips. Progress near 5% is bootloader connect, not compile. + +[web-serial-port.js](src/lib/web-serial/web-serial-port.js) retries `open()` after a delay (Windows often fails if reopen is instant). [errors.js](src/lib/web-serial/errors.js) maps “port busy”, “insecure origin”, and “failed to connect” into short sentences. + +**Server.** [services/compile-api/server.js](services/compile-api/server.js) listens on localhost. `GET /health` → `{ ok: true }`. `POST /api/compile` accepts only the three FQBNs and a sketch up to 128 KB. It writes a temp sketch, runs `arduino-cli`, deletes the folder. Uno → HEX. ESP32 → flash images plus a cleared OTA-data region so the new app boots. Blynk headers add the Blynk library path if that folder exists on the machine. Sensor libraries (ESP32Servo, SSD1306, MFRC522, MAX3010x) must already be installed there. + +> **Transport.** Vercel rewrites `/api/compile` to `https://api.tinkerbit.io/api/compile`, so sketches (Arduino Cloud sketches carry the WiFi password and device key) are encrypted all the way to the EC2 host. MicroPython Cloud projects never send these to any server: they go to the board's `/config.json` over USB. `/devices/*` and `/extensions/*` are public static files and still go to `http://13.127.144.30`. + +### 4.6 TinkerBit Cloud (IoT) + +Students add the onboard **TinkerBit Cloud** part in Beginner Studio. The board joins WiFi, talks MQTT to our broker, and shows up on `/iot`, where they see readings, flip dashboard switches and sliders, and get alerts. Pilot scale: about 100 boards on the existing EC2 host. + +```mermaid +flowchart LR + board["ESP32 (MicroPython or Arduino)"] -- "MQTT TLS 8883 (or WSS 443)" --> mosq[Mosquitto + dynamic security] + mosq -- "internal 1883" --> api[iot-api Node service] + api --> db[(SQLite)] + browser["/iot and Studio"] -- "/api/iot/* via Vercel" --> nginx[nginx api.tinkerbit.io] + nginx --> api + browser -- "wss live ticket" --> nginx +``` + +| Piece | Where | Notes | +|-------|-------|-------| +| Broker | [services/iot-api/deploy/mosquitto.conf](services/iot-api/deploy/mosquitto.conf) | One login and ACL `tb//#` per board; anonymous off; 4 KB packets | +| Service | [services/iot-api/](services/iot-api/) | HTTP API, live WebSocket, ingest, alert rules, rollups, backups. Runbook in its [readme](services/iot-api/readme.md) | +| Firmware (Arduino) | [cloudFirmware.js](src/beginner-studio/domain/cloudFirmware.js) | `esp-mqtt` on its own FreeRTOS task; ISRG roots; falls back to WSS on 443 behind strict firewalls; failsafe values when offline | +| Firmware (MicroPython) | [cloud.py](prototypes/micropython/lib/tinkerbit/cloud.py), [tbcloud.c](prototypes/micropython/firmware/cmodules/tbcloud/tbcloud.c), `micropythonCloudConfig` in [pycodegen.js](src/beginner-studio/domain/pycodegen.js) | WiFi from Python; MQTT over TLS in the `tbcloud` C module (esp-mqtt on its own task, ISRG roots, WSS fallback remembered on the board). Same topics, telemetry, controls, alerts and checklist lines as the Arduino firmware. Settings come from `/config.json`. Needs the TinkerBit firmware | +| Studio Cloud page | [CloudView.jsx](src/beginner-studio/components/cloud/CloudView.jsx), [useCloudSetup.js](src/beginner-studio/hooks/useCloudSetup.js), [cloudSecrets.js](src/beginner-studio/domain/cloudSecrets.js) | Opened by the top-bar "Cloud" button (asks to add the Cloud part first). One checklist: the project's Cloud board, WiFi, then upload and go live; each step shows a tick and a Change link once done. When set up, a live card beside it shows the board's readings and the controls the program uses, plus a QR code to the phone. Dashboards, alerts and board settings are only in TinkerBit Cloud (`/iot`), never inside Studio | +| Project's board | [BoardStep.jsx](src/beginner-studio/components/cloud/BoardStep.jsx) | Each project gets its own board, named after the project, made when the student presses Next. Using a board they already have is behind "Use a board I already have". A project keeps the board it used last | +| Control names | `nameControl` in [useCloudSetup.js](src/beginner-studio/hooks/useCloudSetup.js), [cloudPanel.js](src/beginner-studio/domain/cloudPanel.js) | "Names on your phone": the student names each dashboard switch and slider the program uses ("Pump" for Dashboard switch 1). Names are saved in the project's Cloud link (`cloud.labels`) and follow the project to another board. Studio sends them, with part names for readings, as the board's `labels` (`PATCH /devices/:id`); `/iot` shows them on tiles, settings and alert messages through `labelFor`. Tiles keep plain titles, so a rename shows at once | +| Add Cloud | [CloudAddDialog.jsx](src/beginner-studio/components/cloud/CloudAddDialog.jsx) | Adds the Cloud part (lists parts in the way), then opens the Cloud page | +| Going live | [useCloudLive.js](src/beginner-studio/hooks/useCloudLive.js), [cloudProgress.js](src/beginner-studio/domain/cloudProgress.js) | Reads the board's USB messages and polls the Cloud service after a Cloud upload | +| Dashboard | [src/iot/](src/iot/) | TinkerBit Cloud, in the brand look (light by default, dark in the account menu; tokens in [theme.js](src/iot/theme.js)). Boards list, one board page (controls first, then readings, chart, alerts with a "Tell me when…" rule builder, and board settings), widget grid (drag to move, drag the corner to resize, tap a tile for a settings panel with live preview; layout is a flowing grid so phones and desktops share it), alert rules, settings, data export/delete | +| Browser client | [src/lib/iot-api.js](src/lib/iot-api.js) | Same-origin `/api/iot/*` (Vercel rewrite → `https://api.tinkerbit.io/iot/v1/*`; dev proxy → `127.0.0.1:20114`) | + +Rules the software enforces: + +- **A1–A4 are off while Cloud is on.** WiFi takes over the ESP32's ADC2, which those jacks use. The shelf, jacks, 3D board and upload all refuse parts that need them; Cloud templates use D13, D5, MD and I2C only. +- **Cloud and BLE cannot be in the same project** (radio and flash budget). +- **Secrets never sit in the code panel.** The preview shows `********`; real values are put in only inside the Upload handler and masked in compile logs. The device key stays in this browser's localStorage (per account); the WiFi password stays in sessionStorage unless "remember on this computer" is ticked. The server never sees the WiFi password. In MicroPython mode both go into `/config.json`, written over USB at Upload and never shown or logged; uploading a project without Cloud removes an earlier project's `/config.json`. +- **Unsaved dashboard edits are never lost silently.** Switching boards, leaving TinkerBit Cloud from the top bar, or starting an upload asks first (`canLeave` in [router.js](src/iot/router.js)). +- **Telemetry** sends only the variables of input parts that the program actually reads, at most every 5 s. Dashboard controls arrive instantly (retained MQTT state with versions and acks). + +Local development: `cd services/iot-api && npm run dev` (see its readme), then `npm start` here; the dev server proxies `/api/iot`. + +### 4.7 Edge AI + +Students teach the board to tell 2–4 things apart by recording examples, then use "If the AI thinks it is …" blocks. The model runs on the ESP32 itself; no server and no internet are involved. Two kinds: **Motion** (moves made with the MPU6050) and **Sensors** (moments the wired sensors notice together, such as an empty room or someone at the door). + +**Arduino mode only for now.** The recorder and the AI program are Arduino sketches, and flashing them would replace the TinkerBit firmware. In MicroPython mode (the default) the Edge AI page says "Coming soon in MicroPython", AI templates are greyed out, and Upload refuses a project with AI blocks ("Edge AI is coming soon in MicroPython. Remove it from your project to upload."). Use `?board=arduino` for Edge AI lessons. + +| Piece | Where | Notes | +|-------|-------|-------| +| Page | [AiView.jsx](src/beginner-studio/components/ai/AiView.jsx), [ThingList.jsx](src/beginner-studio/components/ai/ThingList.jsx) | Opened by the top-bar "Edge AI" button (its dot and tooltip say what is missing). Split 30/70: the things the AI knows on the left; on the right what it learns, get the board ready, teach it, try it and use it. Stacks under 900 px | +| Rules and limits | [aiKinds.js](src/beginner-studio/domain/ai/aiKinds.js) | Kinds, which readings Sensors uses (in a fixed sorted order), name checks, `aiProblem()` (the one next step, shown in the top bar and on Upload), Cloud keys `ai_` | +| Saved state | [aiState.js](src/beginner-studio/domain/ai/aiState.js), [autosave.js](src/beginner-studio/domain/autosave.js), [useAiActions.js](src/beginner-studio/hooks/useAiActions.js) | `ai: {kind, things, samples, sig}` is saved with the project (autosave v1 with an optional field, so older tabs ignore it). One recording is one undo step; undo is paused while recording | +| Model | [knn.js](src/beginner-studio/domain/ai/knn.js) | 3 nearest neighbours on standardised features; a tie goes to the nearest. "Not sure" past 3× the usual same-thing gap. The check leaves out each example's whole recording, so near-copies do not count | +| Recorder | [useAiRecorder.js](src/beginner-studio/hooks/useAiRecorder.js), [aiLine.js](src/beginner-studio/domain/ai/aiLine.js) | "Put the recorder on the board" uploads a sketch that prints `TBAI1,…` lines at 9600 baud: a hello every 2 s with the kind, parts signature and feature count; one `F` line per example; a movement level; `E,no_sensor`. Record collects 10 examples and stops by itself; leaving the page or losing the board keeps what it got | +| Firmware | [aiFirmware.js](src/beginner-studio/domain/ai/aiFirmware.js), [motionSensor.js](src/beginner-studio/domain/motionSensor.js) | Motion: 100 readings a second, a move starts when it jolts past a line and is kept for 1 s (200 ms from just before); 24 features (average, spread, lowest, highest of 6 axes). Sensors: 5 readings over about 1 s, averaged. `aiClassify()` repeats the browser's steps in C++ | +| Blocks | [condition.js](src/beginner-studio/domain/condition.js), [codegen.js](src/beginner-studio/domain/codegen.js) | "If the AI thinks it is" offers the things, Nothing (Motion only) and Not sure. The loop asks once per pass: Motion waits up to 2 s for a move, Sensors reads for about 1 s. An If about a removed thing becomes `if (false)` and blocks Upload | + +Rules the software enforces: + +- **The learned examples go into the sketch only on Upload and Copy.** The code panel shows a short stand-in that answers Not sure, because the full table is long. +- **Examples recorded with other parts cannot be mixed in.** Each recording carries the parts signature; when the parts change, the page asks to clear the old examples and Upload refuses until they are recorded again. +- **Upload checks the AI first** (2 things, 10 examples each, matching parts) and offers "Open Edge AI" instead of uploading a program that cannot answer. +- **Cloud** gets one 0/1 reading per thing (`ai_wave` …), titled "AI: Wave" on the dashboard. + +Templates: Magic Wand (motion, light and buzzer), Room Mood (sensors, light), Phone AI Alert (motion and Cloud). They come with the things named; the examples are recorded by the student. + +### 4.8 MicroPython on the board (Beginner default) + +Beginner Studio writes MicroPython by default. Upload sends the program to the board over USB through the MicroPython raw REPL. There is no compile step and no server in the path, so uploads take seconds and keep working offline once the page has loaded. The board runs the **TinkerBit firmware**: MicroPython 1.24.1 for the classic ESP32, with the `tinkerbit` kit library and two C modules built in. + +```mermaid +flowchart LR + tree[Wiring + program tree] --> py[generatePython] + py --> panel[Code panel] + py --> up[uploadMicroPython] + up -- "raw REPL at 115200, base64 file writes" --> fs["/main.py, /boot.py, /config.json"] + fs --> run[Soft reset runs main.py] + menu[Update board] -- "esptool, SHA-256 checked" --> fw[TinkerBit firmware] +``` + +**Which language.** [boardLanguage.js](src/beginner-studio/domain/boardLanguage.js): MicroPython is the default. `?board=arduino` switches this browser to Arduino (remembered in `localStorage` as `tb.boardLanguage`), and `?board=micropython` switches back. In Arduino mode Upload compiles and flashes (section 4.5), which replaces the firmware, so going back to MicroPython needs Update board. A MicroPython project never falls back to Arduino on its own. + +| Piece | Where | Notes | +|-------|-------|-------| +| Code generator | [pycodegen.js](src/beginner-studio/domain/pycodegen.js) | One object per wired part by jack name, values, setup lines, then `while True:` with the program tree. Each action prints a line (`LED: ON`). `micropythonGaps()` lists what is not ported; today that is only the Edge AI block | +| Kit library | [prototypes/micropython/lib/tinkerbit/](prototypes/micropython/lib/tinkerbit/) | `VERSION` 0.2.0, `API` 2. `board.py` is the only file with GPIO numbers. One cached object per jack, jack-ownership checks with friendly errors, friendly units, `stop_all()`. RFID (`rc522.py`), heartbeat (`max30102.py`), BLE (`ble.py`) and Cloud (`cloud.py`) included | +| Firmware build | [prototypes/micropython/firmware/](prototypes/micropython/firmware/) | `build.sh` builds MicroPython 1.24.1 `ESP32_GENERIC` in Docker. `manifest.py` freezes the library in; `frozen/_boot.py` holds serial safe mode; C modules `tbsys` and `tbcloud`. The image is 1,781,600 bytes, with 15 % of the app partition free | +| Bundled firmware | [static/firmware/](static/firmware/) | `tinkerbit-esp32-v1.24.1.bin`, served with the site | +| Board check | [boardInfo.js](src/beginner-studio/micropython/boardInfo.js) | A `TB_INFO` line: language, MicroPython version, chip, firmware (`tinkerbit` or `stock`), library API and version. Refuses chips other than the classic ESP32. A board that only prints the ESP32 boot text is reported as Arduino | +| Raw REPL link | [replLink.js](src/beginner-studio/micropython/replLink.js) | Ctrl-C, then the raw REPL; file writes as base64 in commands of about 2 KB, to `.tmp` then renamed; hard reset; safe-mode recovery; soft reset into `main.py` | +| Upload | [upload.js](src/beginner-studio/micropython/upload.js), [libraryFiles.js](src/beginner-studio/micropython/libraryFiles.js) | Steps below. A hash stamp in `/tb_lib.txt` decides when the library files are written again | +| Update board | [installFirmware.js](src/beginner-studio/micropython/installFirmware.js), [UpdateBoardDialog.jsx](src/beginner-studio/components/layout/UpdateBoardDialog.jsx) | Account menu → Update board. Shows what the board runs. Fetches the bundled `.bin`, checks its SHA-256, chip and partition table, and flashes it with [esptool-flash.js](src/lib/web-serial/esptool-flash.js) (the same four reset strategies as Arduino uploads). The only place the firmware is installed | + +**Upload, in order** ([upload.js](src/beginner-studio/micropython/upload.js)): + +1. Enter the raw REPL (2.5 s). If the board does not answer, restart it in safe mode and try again. A board running Arduino gets "This board does not have MicroPython. Choose Update board…". +2. Read `TB_INFO`. Cloud projects need the TinkerBit firmware. A firmware whose library API differs from the page's (`FIRMWARE_API = 2`) asks for Update board (older) or a page reload (newer). +3. Remove leftover `.tmp` files (a cut cable can leave one), then call `tinkerbit.stop_all()`. Ctrl-C stops the Python code but not PWM, so without this a motor, servo or tone from the last program would keep going. +4. Write the library if its stamp changed. On the TinkerBit firmware only `/boot.py` is written, because the library is frozen in, and an old `/lib/tinkerbit` copy is removed. On stock MicroPython the whole library goes into `/lib`. +5. Cloud projects write `/config.json`; other projects remove an earlier one. +6. Write `/main.py`, soft-reset into it, and watch 1.5 s for an error line, which Upload shows. + +**On the board:** + +- **Power-up safety.** `boot.py` drives the active-low relay pins HIGH, and drives LOW the pumps, locks and buzzers the last program used (the library lists them in `/tb_boot.json`), before `main.py` starts. Measured at about 0.8 s after reset; the pins float as inputs before that. +- **Serial safe mode.** For 300 ms after every boot the board listens for `TB_SAFE`. If it arrives, `main.py` is skipped and the board answers `TB_SAFE_OK`. On the TinkerBit firmware this check lives in frozen `_boot.py`, so a student's files cannot break it; on stock MicroPython it is in `boot.py`. The page sends `TB_SAFE` for 2.5 s after a hard reset; a 500 ms burst failed 10 of 10 times on real boot timing. Safe mode does not use the BOOT button, because GPIO 0 is also the A4 jack. +- **HC-05.** The program moves UART0 to 9600 and turns off Ctrl-C, so the monitor and the Cloud checklist open at 9600 (`micropythonBaud`), and Upload gets in through safe mode. HC-05 modules set to 38400 are not handled. +- **Cloud after a soft reset.** A soft reset does not stop FreeRTOS tasks, so frozen `_boot.py` ends the last program's Cloud connection (`tbcloud.stop()`). + +**Differences a teacher notices:** + +- The code panel shows Python, and Copy copies it. +- There is no Stop button: Upload stops the last program first, and the monitor's Start restarts the board. +- Cloud settings go to the board over USB, not to the compile server. + +**Status.** Measured so far on one CH340 board, driven from a Python host rather than Chrome ([RESULTS.md](prototypes/micropython/RESULTS.md)): + +- Opening the port with DTR/RTS low does not reset the board. +- Safe mode recovered 10 of 10 times. +- A 3 KB upload takes 0.5–1.2 s, and 25 KB takes 3.7–3.8 s. +- About 154 KB of Python heap is free after loading the library (measured with library 0.1.0). + +Still open: Cloud memory and 24-hour stability (check 1), 8 kHz mic sampling (check 2), HC-05 upload-only mode (check 4), any CP210x board, and runs through the Chrome page. The migration notes are in [MIGRATION_EDGE_CASES.md](prototypes/micropython/MIGRATION_EDGE_CASES.md). + +**Tests.** + +- Studio unit tests in [test/unit/beginner-studio/](test/unit/beginner-studio/): + - `micropython-codegen.test.js` + - `micropython-repl.test.js` + - `micropython-coming-soon.test.jsx` + - `update-board.test.jsx` + - `serial-monitor-restart.test.jsx` +- The prototype has pytest suites in [prototypes/micropython/tests/](prototypes/micropython/tests/) against a simulated board ([board_sim.py](prototypes/micropython/sim/board_sim.py)), plus Playwright tests of the test page (`tests/e2e/page.spec.js`). + +--- + +## 5. Failures, limits, and where to look + +### 5.1 Common failures and what we already do + +| What you see | Likely cause | What the app / you should do | +|--------------|--------------|------------------------------| +| Failed to open serial port | Arduino IDE monitor, another tab, or a stuck handle | Close other serial apps. Stop the in-app monitor. Unplug/replug. Connect retries the open. | +| Update board or an Arduino upload stuck at 5% | Chip not in download mode (laptop USB) | Hold BOOT. App tries four reset strategies, then tells you to hold BOOT. | +| "This board does not have MicroPython" | New kit with the Arduino demo, or the board was last used in Advanced or Arduino mode | Account menu → Update board (once per board). | +| "Older TinkerBit firmware" / "newer TinkerBit firmware than this page" | The firmware's library API differs from the page's | Update board, or reload the page. | +| "Cloud needs the TinkerBit firmware" | Plain MicroPython on the board | Update board. | +| Monitor silent after plugging in | Some laptops start the board in its flashing mode on plug-in | Start restarts the board; if still silent after 4 s, press RST once. | +| Serial empty or garbage | Baud mismatch | Beginner MicroPython = 115200 (9600 with an HC-05). Arduino kit sketches = 9600. Blynk = 115200. Press Start again after an upload. | +| DHT 255 / NaN | Polled too fast or on GPIO 33 | Bit-bang + 2 s wait + retries. Prefer A1. | +| Soil always 0% | Wrong jack or dead ADC | Percent map; raw printed; fail if raw ≈ 0. | +| MQ-2 jumps around | Single ADC sample | Average 16 samples. Heater needs about a minute. | +| Relays click at power-on | Active-low board | Setup drives MD pins HIGH (off). | +| HW-605 not found | I2C at 400 kHz or bad cable | Init at 100 kHz on SDA 21 / SCL 22. | +| Ultrasonic heats up | Echo driven as OUTPUT | D5 reserved; Echo pin stays INPUT. | +| Board never runs after reset with something on A4 | GPIO 0 held LOW | Use another jack; label says BOOT. | +| RFID and LED fight | Shared GPIO 33 | D13 and 3D are exclusive. | +| Cloud board never goes online | 5 GHz-only WiFi, login-page WiFi, eduroam, or wrong password | Serial monitor explains the WiFi reason code. Use 2.4 GHz or a phone hotspot. | +| Cloud board "keeps reconnecting" warning | Brown-out on USB power, or two boards flashed with the same key | Check cable/power; make a new key for one board. | +| Cloud board paused | It sent data too fast (flooding) | Add a Wait block, upload, press "Turn back on" in Settings. | +| MPU6050 not found | Cable not fully in I2C, or a module at another address | Setup tries 0x68 and 0x69 and says so in Board messages; it retries every 5 s. Edge AI shows "cannot find the motion sensor". | +| Edge AI always says Not sure | Moves done differently from the recordings, or parts changed | Record more examples the way it will be used; the check on the Edge AI page shows which things get mixed up. | + +### 5.2 Technical limits + +- MicroPython uploads run at 115200 over the raw REPL: a 25 KB file takes about 3.7 s. The firmware's library API (2) must match the page. +- TinkerBit firmware: 1.78 MB, with 15 % of the app partition left for growth. +- Arduino compile: payload max 128 KB; compile timeout 3 minutes. +- Only Uno, ESP32, and ESP32-S3 FQBNs. +- Projects are not saved to the cloud. TinkerBit Cloud stores board data only. +- Cloud: 2.4 GHz WPA2-Personal or open WiFi only (no captive portals or Enterprise); readings every 5 s at most; 6 controls per board (`switch1..4`, `slider1..2`). +- Upload needs a secure context (HTTPS or localhost) and a Chromium browser. +- HC-05 and the USB serial monitor cannot be used as two independent ports; they are the same UART. +- Edge AI: Arduino mode only. 2–4 things, 10–40 examples each, names up to 16 letters. The recorder replaces the student's program until the next Upload. Sound is not a kind yet. + +### 5.3 Repository map + +| Topic | Path | +|-------|------| +| Page build | [webpack.config.js](webpack.config.js) | +| Host routes and headers | [vercel.json](vercel.json) | +| Login gate | [middleware.js](middleware.js) | +| Google session | [api/auth/](api/auth/), [lib/auth/session.mjs](lib/auth/session.mjs) | +| Beginner Studio | [src/beginner-studio/](src/beginner-studio/) | +| Advanced IDE | [src/containers/gui.jsx](src/containers/gui.jsx) | +| Maker kit Blockly | [static/extensions/makerEsp32/](static/extensions/makerEsp32/) | +| Browser flash | [src/lib/web-serial/](src/lib/web-serial/) | +| MicroPython upload, board check, Update board | [src/beginner-studio/micropython/](src/beginner-studio/micropython/) | +| MicroPython code generator | [src/beginner-studio/domain/pycodegen.js](src/beginner-studio/domain/pycodegen.js) | +| TinkerBit library, firmware build, simulator, hardware results | [prototypes/micropython/](prototypes/micropython/) | +| Bundled firmware | [static/firmware/](static/firmware/) | +| Sketch compile | [services/compile-api/server.js](services/compile-api/server.js) | +| Cloud service, broker, deploy | [services/iot-api/](services/iot-api/) | +| IoT Dashboard (full page) | [src/iot/](src/iot/) | +| Cloud firmware | [cloudFirmware.js](src/beginner-studio/domain/cloudFirmware.js) (Arduino), [cloud.py](prototypes/micropython/lib/tinkerbit/cloud.py) + [tbcloud](prototypes/micropython/firmware/cmodules/tbcloud/) (MicroPython) | +| Edge AI (model, recorder, firmware) | [src/beginner-studio/domain/ai/](src/beginner-studio/domain/ai/), [src/beginner-studio/components/ai/](src/beginner-studio/components/ai/) | + +This file is the product document for TinkerBit: what it offers, how a person uses it, how the kit is wired, how programs reach the board (MicroPython upload, or compile and flash), and what we already do when hardware or USB does not behave. diff --git a/ARCHITECTURE.pdf b/ARCHITECTURE.pdf new file mode 100644 index 00000000000..31c43e47de2 Binary files /dev/null and b/ARCHITECTURE.pdf differ diff --git a/animated/rj11-hub-widget.html b/animated/rj11-hub-widget.html new file mode 100644 index 00000000000..2126c3aeee4 --- /dev/null +++ b/animated/rj11-hub-widget.html @@ -0,0 +1,748 @@ + + + + + +RJ11 Hub Board + + + + + + + + + + + + + +
+ +
+
+
+ + 100% + + +
+
+
+ + + + + diff --git a/animated/rj11-hub_1.html b/animated/rj11-hub_1.html new file mode 100644 index 00000000000..b8f14c1b748 --- /dev/null +++ b/animated/rj11-hub_1.html @@ -0,0 +1,737 @@ + + + + + +RJ11 Hub Board + + + + + + + + + + + +
+ +
+
+
+ + 100% + + +
+
+
+ + + + + diff --git a/api/auth/callback.mjs b/api/auth/callback.mjs new file mode 100644 index 00000000000..76a47fcb3a2 --- /dev/null +++ b/api/auth/callback.mjs @@ -0,0 +1,148 @@ +import { + OAUTH_STATE_COOKIE, + SESSION_COOKIE, + SESSION_MAX_AGE_SEC, + clearCookie, + createSessionToken, + getAuthBaseUrl, + isAuthDisabled, + logAuthEvent, + parseCookies, + sanitizeNextPath, + serializeCookie +} from '../../lib/auth/session.mjs'; + +function redirectLogin (res, errorCode) { + const q = errorCode ? `?error=${encodeURIComponent(errorCode)}` : ''; + res.statusCode = 302; + res.setHeader('Location', `/login${q}`); + res.setHeader('Cache-Control', 'no-store'); + res.end(); +} + +export default async function handler (req, res) { + if (req.method !== 'GET') { + res.statusCode = 405; + res.end('Method Not Allowed'); + return; + } + + if (isAuthDisabled()) { + res.statusCode = 302; + res.setHeader('Location', '/choose'); + res.end(); + return; + } + + const clientId = process.env.GOOGLE_CLIENT_ID; + const clientSecret = process.env.GOOGLE_CLIENT_SECRET; + if (!clientId || !clientSecret || !process.env.AUTH_SECRET) { + logAuthEvent('callback_misconfigured'); + redirectLogin(res, 'config'); + return; + } + + const query = req.query || {}; + if (query.error) { + logAuthEvent('callback_google_error', {error: String(query.error)}); + redirectLogin(res, 'denied'); + return; + } + + const code = query.code; + const state = query.state; + if (!code || !state) { + logAuthEvent('callback_missing_params'); + redirectLogin(res, 'invalid'); + return; + } + + const cookies = parseCookies(req.headers.cookie); + const rawState = cookies[OAUTH_STATE_COOKIE]; + let stored = null; + try { + stored = rawState ? JSON.parse(Buffer.from(rawState, 'base64url').toString('utf8')) : null; + } catch (err) { + stored = null; + } + + if (!stored || !stored.state || stored.state !== state) { + logAuthEvent('callback_state_mismatch'); + res.setHeader('Set-Cookie', clearCookie(OAUTH_STATE_COOKIE)); + redirectLogin(res, 'invalid'); + return; + } + + const next = sanitizeNextPath(stored.next); + const baseUrl = getAuthBaseUrl(req); + const redirectUri = `${baseUrl}/api/auth/callback`; + + let tokenJson; + try { + const tokenRes = await fetch('https://oauth2.googleapis.com/token', { + method: 'POST', + headers: {'Content-Type': 'application/x-www-form-urlencoded'}, + body: new URLSearchParams({ + code: String(code), + client_id: clientId, + client_secret: clientSecret, + redirect_uri: redirectUri, + grant_type: 'authorization_code' + }) + }); + tokenJson = await tokenRes.json(); + if (!tokenRes.ok || !tokenJson.access_token) { + logAuthEvent('callback_token_exchange_failed'); + redirectLogin(res, 'invalid'); + return; + } + } catch (err) { + logAuthEvent('callback_token_exchange_error'); + redirectLogin(res, 'invalid'); + return; + } + + let profile; + try { + const profileRes = await fetch('https://openidconnect.googleapis.com/v1/userinfo', { + headers: {Authorization: `Bearer ${tokenJson.access_token}`} + }); + profile = await profileRes.json(); + if (!profileRes.ok || !profile.sub) { + logAuthEvent('callback_profile_failed'); + redirectLogin(res, 'invalid'); + return; + } + } catch (err) { + logAuthEvent('callback_profile_error'); + redirectLogin(res, 'invalid'); + return; + } + + let sessionToken; + try { + sessionToken = await createSessionToken({ + sub: profile.sub, + email: profile.email || '', + name: profile.name || profile.email || 'User', + picture: profile.picture || '' + }); + } catch (err) { + logAuthEvent('callback_session_failed'); + redirectLogin(res, 'config'); + return; + } + + logAuthEvent('callback_success', {sub: profile.sub}); + res.statusCode = 302; + res.setHeader('Set-Cookie', [ + serializeCookie(SESSION_COOKIE, sessionToken, { + maxAge: SESSION_MAX_AGE_SEC, + httpOnly: true + }), + clearCookie(OAUTH_STATE_COOKIE) + ]); + res.setHeader('Location', next); + res.setHeader('Cache-Control', 'no-store'); + res.end(); +} diff --git a/api/auth/google.mjs b/api/auth/google.mjs new file mode 100644 index 00000000000..97f9a9017f6 --- /dev/null +++ b/api/auth/google.mjs @@ -0,0 +1,61 @@ +import {randomBytes} from 'crypto'; +import { + OAUTH_STATE_COOKIE, + STATE_MAX_AGE_SEC, + getAuthBaseUrl, + isAuthDisabled, + logAuthEvent, + sanitizeNextPath, + serializeCookie +} from '../../lib/auth/session.mjs'; + +export default async function handler (req, res) { + if (req.method !== 'GET') { + res.statusCode = 405; + res.end('Method Not Allowed'); + return; + } + + if (isAuthDisabled()) { + res.statusCode = 302; + res.setHeader('Location', sanitizeNextPath(req.query && req.query.next)); + res.end(); + return; + } + + const clientId = process.env.GOOGLE_CLIENT_ID; + const clientSecret = process.env.GOOGLE_CLIENT_SECRET; + if (!clientId || !clientSecret || !process.env.AUTH_SECRET) { + logAuthEvent('google_start_misconfigured'); + res.statusCode = 503; + res.setHeader('Content-Type', 'text/html; charset=utf-8'); + res.end('Auth unavailable

Sign-in is not configured yet. Set GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, and AUTH_SECRET.

'); + return; + } + + const next = sanitizeNextPath(req.query && req.query.next); + const state = randomBytes(24).toString('hex'); + const statePayload = Buffer.from(JSON.stringify({state, next}), 'utf8').toString('base64url'); + const baseUrl = getAuthBaseUrl(req); + const redirectUri = `${baseUrl}/api/auth/callback`; + + const params = new URLSearchParams({ + client_id: clientId, + redirect_uri: redirectUri, + response_type: 'code', + scope: 'openid email profile', + state, + access_type: 'online', + prompt: 'select_account' + }); + + logAuthEvent('google_start'); + res.statusCode = 302; + res.setHeader('Set-Cookie', serializeCookie(OAUTH_STATE_COOKIE, statePayload, { + maxAge: STATE_MAX_AGE_SEC, + httpOnly: true + })); + res.setHeader('Location', `https://accounts.google.com/o/oauth2/v2/auth?${params.toString()}`); + res.setHeader('Cache-Control', 'no-store'); + res.end(); +} diff --git a/api/auth/logout.mjs b/api/auth/logout.mjs new file mode 100644 index 00000000000..314a977ab22 --- /dev/null +++ b/api/auth/logout.mjs @@ -0,0 +1,29 @@ +import { + SESSION_COOKIE, + clearCookie, + isAuthDisabled, + logAuthEvent +} from '../../lib/auth/session.mjs'; + +export default async function handler (req, res) { + if (req.method !== 'POST' && req.method !== 'GET') { + res.statusCode = 405; + res.end('Method Not Allowed'); + return; + } + + logAuthEvent('logout'); + res.setHeader('Set-Cookie', clearCookie(SESSION_COOKIE)); + res.setHeader('Cache-Control', 'no-store'); + + if (req.method === 'GET') { + res.statusCode = 302; + res.setHeader('Location', '/login'); + res.end(); + return; + } + + res.statusCode = 200; + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify({ok: true, disabled: isAuthDisabled()})); +} diff --git a/api/auth/me.mjs b/api/auth/me.mjs new file mode 100644 index 00000000000..308a297e43c --- /dev/null +++ b/api/auth/me.mjs @@ -0,0 +1,39 @@ +import { + isAuthDisabled, + readSessionFromRequest +} from '../../lib/auth/session.mjs'; + +export default async function handler (req, res) { + if (req.method !== 'GET') { + res.statusCode = 405; + res.end('Method Not Allowed'); + return; + } + + res.setHeader('Cache-Control', 'no-store'); + res.setHeader('Content-Type', 'application/json'); + + if (isAuthDisabled()) { + res.statusCode = 200; + res.end(JSON.stringify({ + authenticated: true, + disabled: true, + user: {sub: 'dev', email: 'dev@localhost', name: 'Dev', picture: ''} + })); + return; + } + + const user = await readSessionFromRequest(req); + if (!user) { + res.statusCode = 401; + res.end(JSON.stringify({authenticated: false})); + return; + } + + res.statusCode = 200; + res.end(JSON.stringify({ + authenticated: true, + disabled: false, + user + })); +} diff --git a/api/waitlist-export.mjs b/api/waitlist-export.mjs new file mode 100644 index 00000000000..0672e7b4a62 --- /dev/null +++ b/api/waitlist-export.mjs @@ -0,0 +1,67 @@ +import {createHash, timingSafeEqual} from 'node:crypto'; + +import {WAITLIST_KEY, getRedisConfig, redisPipeline, sendJson} from '../lib/waitlist/store.mjs'; + +const sha256 = value => createHash('sha256').update(String(value)) + .digest(); + +const providedToken = req => { + const auth = String(req.headers.authorization || ''); + if (auth.toLowerCase().startsWith('bearer ')) { + return auth.slice(7).trim(); + } + return (req.query && req.query.token) ? String(req.query.token) : ''; +}; + +const csvCell = value => { + let text = String(value); + // Stop spreadsheet apps from treating a cell as a formula. + if (/^[=+\-@]/.test(text)) { + text = `'${text}`; + } + return /[",\n]/.test(text) ? `"${text.replace(/"/g, '""')}"` : text; +}; + +export default async function handler (req, res) { + if (req.method !== 'GET') { + res.setHeader('Allow', 'GET'); + sendJson(res, 405, {ok: false, error: 'method_not_allowed'}); + return; + } + + const expected = process.env.WAITLIST_EXPORT_TOKEN; + if (!expected || expected.length < 16) { + sendJson(res, 503, {ok: false, error: 'export_not_configured'}); + return; + } + if (!timingSafeEqual(sha256(providedToken(req)), sha256(expected))) { + sendJson(res, 401, {ok: false, error: 'unauthorized'}); + return; + } + + const config = getRedisConfig(); + if (!config) { + sendJson(res, 503, {ok: false, error: 'not_configured'}); + return; + } + + try { + const [flat] = await redisPipeline(config, [['ZRANGE', WAITLIST_KEY, 0, -1, 'WITHSCORES']]); + const rows = ['email,signed_up_at']; + for (let i = 0; i < (flat || []).length; i += 2) { + const signedUp = new Date(Number(flat[i + 1])).toISOString(); + rows.push(`${csvCell(flat[i])},${signedUp}`); + } + const day = new Date().toISOString() + .slice(0, 10); + res.statusCode = 200; + res.setHeader('Content-Type', 'text/csv; charset=utf-8'); + res.setHeader('Content-Disposition', `attachment; filename="tinkerbit-waitlist-${day}.csv"`); + res.setHeader('Cache-Control', 'no-store'); + res.setHeader('X-Robots-Tag', 'noindex'); + res.end(`${rows.join('\n')}\n`); + } catch (err) { + console.error('[waitlist-export] read failed', err && err.message); + sendJson(res, 502, {ok: false, error: 'store_failed'}); + } +} diff --git a/api/waitlist.mjs b/api/waitlist.mjs new file mode 100644 index 00000000000..2a138653730 --- /dev/null +++ b/api/waitlist.mjs @@ -0,0 +1,65 @@ +import { + WAITLIST_KEY, + getRedisConfig, + normalizeEmail, + readJsonBody, + redisPipeline, + sendJson +} from '../lib/waitlist/store.mjs'; + +const RATE_LIMIT_PER_HOUR = 10; + +const clientIp = req => { + const forwarded = String(req.headers['x-forwarded-for'] || ''); + return forwarded.split(',')[0].trim() || 'unknown'; +}; + +export default async function handler (req, res) { + if (req.method !== 'POST') { + res.setHeader('Allow', 'POST'); + sendJson(res, 405, {ok: false, error: 'method_not_allowed'}); + return; + } + + const body = await readJsonBody(req); + + // Honeypot: real visitors never see or fill the "company" field. + if (body.company) { + sendJson(res, 200, {ok: true}); + return; + } + + const email = normalizeEmail(body.email); + if (!email) { + sendJson(res, 400, {ok: false, error: 'invalid_email'}); + return; + } + + const config = getRedisConfig(); + if (!config) { + console.error('[waitlist] Redis is not configured (KV_REST_API_URL / KV_REST_API_TOKEN).'); + sendJson(res, 503, {ok: false, error: 'not_configured'}); + return; + } + + try { + const rateKey = `waitlist:rl:${clientIp(req)}`; + const [attempts] = await redisPipeline(config, [ + ['INCR', rateKey], + ['EXPIRE', rateKey, 3600] + ]); + if (attempts > RATE_LIMIT_PER_HOUR) { + sendJson(res, 429, {ok: false, error: 'rate_limited'}); + return; + } + + // NX keeps the first signup time; duplicates are a normal success for the visitor. + const [added] = await redisPipeline(config, [ + ['ZADD', WAITLIST_KEY, 'NX', Date.now(), email] + ]); + sendJson(res, 200, {ok: true, duplicate: added === 0}); + } catch (err) { + console.error('[waitlist] store failed', err && err.message); + sendJson(res, 502, {ok: false, error: 'store_failed'}); + } +} diff --git a/docs/AUTH.md b/docs/AUTH.md new file mode 100644 index 00000000000..214e6bf83fd --- /dev/null +++ b/docs/AUTH.md @@ -0,0 +1,51 @@ +# TinkerBit Google Sign-In + +The IDE and mode pages are gated behind Google OAuth. Guests who open `/choose`, `/beginner`, or `/ide` are redirected to `/login`. + +## Setup + +1. Create a Google Cloud **OAuth 2.0 Web client**. +2. Authorized redirect URIs: + - `https://www.tinkerbit.io/api/auth/callback` + - `http://127.0.0.1:3000/api/auth/callback` (local `vercel dev`) +3. Copy `.env.example` → `.env.local` (never commit secrets). +4. Set Vercel project env vars: + - `GOOGLE_CLIENT_ID` + - `GOOGLE_CLIENT_SECRET` + - `AUTH_SECRET` (32+ random characters) + - `AUTH_BASE_URL=https://www.tinkerbit.io` + - `CLARITY_ID` (Microsoft Clarity project ID; optional) + +## Local + +Auth APIs + middleware need Vercel: + +```bash +npx vercel env pull .env.local +npx vercel dev +``` + +`npm start` (webpack-dev-server) alone does **not** run middleware. On localhost it will warn and continue if `/api/auth` is unreachable. For a real login test, use `vercel dev`. + +Optional non-production bypass: `AUTH_DISABLED=1` (ignored when `VERCEL_ENV=production`). + +## Routes + +| Path | Purpose | +|------|---------| +| `/login` | Sign-in page | +| `/choose` | Post-login Beginner / Advanced chooser | +| `/beginner` | Beginner Studio — visual RJ11 wiring + click blocks + live Arduino C++ | +| `/ide` | Full (Advanced) OpenBlock IDE with upload | +| `/api/auth/google` | Start Google OAuth | +| `/api/auth/callback` | OAuth callback → session cookie → `/choose` by default | +| `/api/auth/me` | Current user JSON | +| `/api/auth/logout` | Clear session | + +After sign-in, users land on `/choose`. **Advanced** opens `/ide`. **Beginner** opens `/beginner` (React wiring + block codegen studio; no Scratch VM on that route). + +Session cookie: `tb_session` (httpOnly, SameSite=Lax, Secure in production). + +## Clarity + +When `CLARITY_ID` is set, sessions are tagged with `page` (`landing` / `login` / `choose` / `beginner` / `ide`), signed-in users are identified (hashed), and custom events fire for sign-in, mode choice, board select/connect, and upload outcomes. Beginner Studio also fires `beginner_ide_opened`. diff --git a/docs/COMPILE_BACKEND_PLAN.md b/docs/COMPILE_BACKEND_PLAN.md new file mode 100644 index 00000000000..707cd918b90 --- /dev/null +++ b/docs/COMPILE_BACKEND_PLAN.md @@ -0,0 +1,144 @@ +# Compile backend: migration plan + +Status: plan, not started. It replaces the current `services/compile-api` setup (one Node process running `arduino-cli` on the shared EC2 host `13.127.144.30`) with a pinned, sandboxed, queued compile service on its own host. The browser upload flow does not change. + +## Why +| Problem today | Where | Risk | +|---|---|---| +| No sign-in, rate limit or concurrency cap on `POST /api/compile` | `services/compile-api/server.js` | Anyone can run gcc on our box at will. CORS only limits browsers | +| Full compiler output is returned to the caller | `server.js` error path (`log: err.stderr`) | `#include "/etc/..."` can echo server file contents into the log | +| Every request builds from scratch in a fresh temp folder | `compileSketch()` | 30 students uploading the same template means 30 identical slow builds | +| Core and library versions are unpinned (`core install esp32:esp32`, `lib install Blynk`) | `install-on-ec2.sh` | A rebuilt server can quietly compile differently from the old one | +| Runs as a plain user on the same box as Mosquitto + iot-api + SQLite | EC2 host | A compile burst slows Cloud, and a compromise reaches Cloud data | +| `/devices/*` and `/extensions/*` (JS the IDE runs) are fetched over plain HTTP | `vercel.json` rewrites to `http://13.127.144.30` | Code can be injected into every IDE session | + +## Decisions +- **Keep `arduino-cli`.** It's the right compiler for Uno/ESP32/ESP32-S3. We don't switch to PlatformIO or rewrite in Go or Rust: the slow part is the compiler, not the Node wrapper. +- **No serverless and no in-browser (WASM) compile.** The ESP32 toolchain is over 1 GB, so cold starts would be slow and the build cache would be lost. And there is no practical WASM build of the ESP32 compiler. +- **Keep the API contract.** `POST {source, fqbn}` returns `{hex, log}` (Uno) or `{format:'esptool', images:[{address, data}], log}` (ESP32), so `src/lib/web-serial/compile-client.js` keeps working through the whole migration. A job API is added next to it, not instead of it. +- **Supported boards stay** `arduino:avr:uno`, `esp32:esp32:esp32`, `esp32:esp32:esp32s3`. The limits stay at 128 KB of source and 180 s for a compile. + +## Target architecture +``` +Browser ──/api/compile──► Vercel rewrite ──HTTPS──► nginx (compile.tinkerbit.io) + ▼ + compile-gateway (Node 22) + · checks tb_session (jose, AUTH_SECRET) + · per-user + global limits + · result cache (sha256 of source+fqbn+IMAGE_TAG) + · job queue, N workers = CPU cores + ▼ + docker run --rm compile-worker: + pinned arduino-cli + cores + libraries + --network none · read-only root · non-root + --cpus 1 · --memory 1.5g · --pids-limit 256 · timeout + warm build cache volume (core archives only) +``` + +## Phases +Each phase ships and is tested on its own. Phases 0–1 change the current server in place; phases 2–5 run alongside it until the switch. + +### Phase 0: Quick safety fixes on the current server (about a day) +- [ ] Require the `tb_session` cookie. Copy `verifySession` from `services/iot-api/src/auth.js` (jose + `AUTH_SECRET`). Vercel forwards the cookie on rewrites, as `/api/iot` already relies on. + - `/ide` and `/beginner` call it same-origin, so no frontend change is needed. + - Localhost dev keeps working via `AUTH_DISABLED=1`. +- [ ] Concurrency cap: at most `max(1, cores-1)` compiles at once. Requests over the cap wait up to 60 s, then get `503 {error:'Compile server busy, try again in a minute'}` with `Retry-After`. +- [ ] Per-user limit: 6 compiles per minute and 60 per hour, with a `429` and a friendly message. +- [ ] Clean the log before returning it: + - replace absolute paths (`/tmp/compile-xxx/sketch/` → `sketch:`, toolchain paths → ``); + - keep only the lines with `error:` / `warning:` plus 2 lines of context; + - cap at 8 KB. + - Refuse sketches that `#include` an absolute path or `..` (`400 'Only kit libraries can be included'`). +- [ ] Map the new `401` / `429` / `503` responses in `compile-client.js` and `friendlyUpload.js` to short student messages ("Sign in again", "Too many uploads, wait a minute", "Server busy"). +- [ ] nginx: `limit_req` on `/api/compile` keyed on the real client IP. `set_real_ip_from` with Vercel's ranges + `real_ip_header X-Forwarded-For` fixes the same gap for `/api/iot`. +- [ ] Serve `/devices/*` and `/extensions/*` over HTTPS through the `api.tinkerbit.io` nginx, and update the two `vercel.json` rewrites. + +### Phase 1: Pinned worker image +- [ ] `services/compile-worker/Dockerfile` (Debian slim): + - arduino-cli at a fixed version; + - `arduino:avr@` and `esp32:esp32@` — use the versions on the current server (`arduino-cli core list` there) so output matches; + - libraries at fixed versions: ESP32Servo, Adafruit SSD1306 + GFX, MFRC522, SparkFun MAX3010x, Blynk; + - a non-root `builder` user. +- [ ] `lock.json` lists every version, and its SHA forms the image tag (`IMAGE_TAG`). Changing a version means a new tag, which also clears the result cache. +- [ ] Worker entry `compile.sh `: + - reads the sketch from `/in/sketch.ino` and writes `/out/result.json` (the same shape as today); + - moves the ESP32 image collection and `boot_app0` handling from `server.js` into `worker/collect.js` so the logic isn't duplicated. +- [ ] Build-time warm-up: compile one sketch per board inside the image, so the core archives are cached in the image (the first real compile skips building the core). +- [ ] Golden tests (`services/compile-worker/test/`): + - every Beginner template (`scripts/check-templates.js` can emit them) plus a Blynk and an Uno sketch compiles; + - flash sizes stay within ±2% of the old server; + - the `0x1000/0x8000/0xe000/0x10000` image set is present for ESP32. +- [ ] CI builds the image and runs the golden tests on every change to `services/compile-worker` or `lock.json`. + +### Phase 2: Gateway, queue and cache +- [ ] `services/compile-gateway/` (Node 22, no framework, same style as iot-api): + - `POST /api/compile`: the old synchronous contract. It waits for the job and holds the request for at most 170 s. + - `POST /api/compile/jobs` returns `{jobId, position}`; `GET /api/compile/jobs/:id` returns `{state: queued|running|done|failed, position, result?}`. This avoids long-held requests through Vercel and lets the UI show "3 ahead of you". + - `GET /api/compile/health` (liveness) and `/readyz` (Docker reachable, disk > 15%, queue below the limit). +- [ ] Queue: in-memory FIFO with N workers; fair per user (round-robin across users, so one class can't starve another); limit of 50 queued jobs. + - Jobs are lost on restart; clients get `503` and retry. + - Redis/SQS only if we ever run more than one gateway. +- [ ] Result cache: + - key `sha256(IMAGE_TAG + fqbn + source)`; + - on disk, capped at 2 GB with LRU eviction, holding only the output files (hex or ESP images + cleaned log); + - never cache failures or sketches with Cloud secrets: skip the cache when the source contains `CLOUD_WIFI_PASS`/`CLOUD_DEVICE_KEY` defines. + - Templates and lessons will mostly hit the cache. +- [ ] Each job: + - writes the sketch to a fresh temp folder and runs `docker run --rm --network none --read-only --tmpfs /tmp:size=512m --cpus 1 --memory 1.5g --pids-limit 256 --security-opt no-new-privileges --user builder`, with `/in` mounted read-only and `/out` writable; + - is killed after 180 s; + - deletes the temp folder in `finally`. +- [ ] Logs: JSON lines with job id, user hash (not the email), fqbn, cache hit, queue ms, compile ms, result. The sketch source is never logged (Cloud sketches carry the WiFi password). +- [ ] Metrics: `/metrics` (text), showing queue length, p50/p95 compile time and cache hit rate, for the pilot dashboard. + +### Phase 3: Its own host +- [ ] A new EC2 instance for compiles only (start with c7i.xlarge, 4 vCPU; ESP32 compiles are CPU-bound): + - Elastic IP, DNS `compile.tinkerbit.io`, certbot, nginx; + - only 443 open (22 restricted). +- [ ] Deploy with the same tools as iot-api: `deploy.sh` with release folders, pre-deploy health check, and automatic rollback if `/readyz` fails. +- [ ] Optional later: ECS/Fargate instead of EC2. Containers per job would then be Fargate tasks, which cost more per compile but need no server care. Decide after a month of metrics. + +### Phase 4: Frontend (small) +- [ ] `compile-client.js`: use the job API when the gateway advertises it (`health` returns `{ok, jobs: true}`), else fall back to the synchronous call. +- [ ] `useBoardUpload` / `friendlyUpload.js`: show "Waiting for the compile server (2 ahead)" and "Compiling…" separately. Retry once automatically on `503`. + +### Phase 5: Switch and clean up +- [ ] Load test: `tools/load-compile.mjs` with 30 users uploading the same template + 10 different sketches at once. Targets: + - p95 under 20 s on a cache hit; + - p95 under 90 s on a miss; + - no `5xx` other than planned `503`s. +- [ ] Switch the `vercel.json` rewrite `/api/compile*` → `https://compile.tinkerbit.io/api/compile*`, and keep the old server for one week as a rollback path. +- [ ] Then remove `compile-api` from the shared host: stop the service, remove its nginx upstream and delete `services/compile-api`. Update `ARCHITECTURE.md` sections 4.5 and 5.2. + +## Edge cases +| Case | Handling | +|---|---| +| Session expired mid-lesson | `401` → "Sign in again" with a link back to the same page; the project is already autosaved | +| Localhost dev without sign-in | `AUTH_DISABLED=1` on a local gateway, or keep proxying to the old dev target | +| Whole class presses Upload at once | Fair queue + cache; position shown; `503` with `Retry-After` beyond 50 queued | +| Identical template sketches | Cache hit, instant | +| Cloud sketch (contains secrets) | Never cached, never logged; log cleaner also masks the defines | +| `#include "/etc/passwd"` or `../` | Refused before compile; the container also has no host files mounted | +| Infinite macro expansion / huge output | 180 s kill, 8 KB log cap, `--pids-limit`, memory limit | +| Sketch tries network (library download) | `--network none`; libraries are only what's in the image | +| New library needed (e.g. Edge AI needs none) | Edit `lock.json` → new image tag → golden tests → deploy | +| Core upgrade changes flash layout | Golden tests compare the image set and sizes before deploy | +| Gateway restarts mid-job | Job lost; client sees `503`, auto-retries once | +| Disk fills with cache | LRU cap 2 GB; `/readyz` fails below 15% free | +| Docker daemon down | `/readyz` fails; nginx returns `503`; deploy rolls back | +| Vercel holds long requests | Job API (poll every 2 s) instead of a single 3-minute request | +| Advanced IDE (`/ide`) Blynk sketches | Blynk is in the image; `detectCompileLibraries` logic moves into the worker | + +## Cost (rough, ap-south-1) +- Compile host c7i.xlarge on demand: about $130/month. Use a 1-year Savings Plan (about 35% off) once the pilot is confirmed. +- The shared host can then shrink, because it only runs Mosquitto + iot-api + nginx. + +## Files +- New: + - `services/compile-worker/` (`Dockerfile`, `lock.json`, `compile.sh`, `collect.js`, `test/`) + - `services/compile-gateway/` (`src/`, `deploy/`, `test/`, `readme.md`) + - `tools/load-compile.mjs` +- Changed: + - `src/lib/web-serial/compile-client.js`, `src/beginner-studio/domain/friendlyUpload.js`, `src/beginner-studio/hooks/useBoardUpload.js` + - `vercel.json`, `services/iot-api/deploy/nginx-iot.conf` + - `ARCHITECTURE.md` +- Removed after the switch: `services/compile-api/`. diff --git a/docs/EDGE_AI_PROJECTS.md b/docs/EDGE_AI_PROJECTS.md new file mode 100644 index 00000000000..61c40196f04 --- /dev/null +++ b/docs/EDGE_AI_PROJECTS.md @@ -0,0 +1,637 @@ +# Edge AI projects with the TinkerBit kit + +Edge AI means the decision is made **on the board itself**: the ESP32 reads its sensors, runs a +small model, and acts, with no internet or cloud in the loop. This guide is a set of +project-based learning units built on the TinkerBit kit (Maker ESP32 on the RJ11 Hub plus its +plug-in modules). Each project starts from a real-world driving question and ends with a working +build that students present. + +Every project is tagged with one of two tracks: + +- **Track A, Studio now:** built today in Beginner Studio with blocks (read a sensor, if/then, + wait, repeat, print, drive an output). The "intelligence" is a rule that the student writes and + tunes by hand. These projects are the baseline that later ML projects improve on. +- **Track B, Arduino + ML:** written in the Arduino IDE. The board either learns on its own + (running statistics, nearest-neighbour) or runs a model trained on a computer with Edge Impulse, + TensorFlow Lite Micro or scikit-learn. + +Beginner Studio and the main block editor have no machine-learning blocks today, so every +Track B project needs Arduino code. + +--- + +## 1. What's in the kit + +| Module | Jack on the hub | Signal | Useful data for AI | +| --- | --- | --- | --- | +| Push Button | D13 or A1-A4 | Digital in | Record a sample, confirm a label | +| Potentiometer | A1-A4 | Analog 0-4095 | Pick a label, set a target value | +| LED | D13 or A1-A4 | Digital / PWM out | Show the predicted class | +| Relay Module | D13 or A1-A4 | Digital out | Act on a decision (lamp, pump) | +| 4-Ch Relay | MD | 4 digital outs | One channel per class | +| Servo Motor | D13 or A1-A4 | PWM out | Point at the answer, open a lid | +| L293D Motor Driver | MD | 2 DC motors | Fan or wheels driven by a model | +| Stepper Motor | ST | 4-wire stepper | Precise movement on a decision | +| OLED Screen | I2C or I2C1 | I2C display | Show the class and its confidence | +| MQ-2 Gas Sensor | A1-A4 | Analog 0-4095 | Smoke and gas level over time | +| Microphone | A1-A4 | Analog | Sound level and audio samples | +| Heartbeat HW-605 (MAX30102) | I2C or I2C1 | I2C | Pulse waveform (red/IR) and BPM | +| Capacitive Soil Moisture | A1-A4 | Analog, 0-100 % | Soil drying curve | +| DHT11 Temp & Humid | A1 | One-wire digital | Temperature and humidity, 1 reading/s | +| HC-SR04 Ultrasonic | D5 only | Trig IO26 / Echo IO25 | Distance in cm, about 15-20 readings/s | +| RFID RC522 | 3D | SPI | Card ID, time of use | +| Bluetooth (BLE) | Built into the ESP32 | Radio | Send results to a phone, scan signal strength | +| HC-05 Bluetooth | UART | Serial | Send results to a phone (classic Bluetooth) | + +The ESP32 itself (typical ESP32-WROOM-32): 240 MHz dual-core processor, about 520 KB of RAM +(roughly 300 KB free for a sketch), 4 MB of flash, and a single-precision floating-point unit. +That is enough for small neural networks (tens of KB), decision trees and nearest-neighbour +models. It is not enough for camera vision or speech recognition beyond a few words. + +--- + +## 2. How each track works + +### Track A, Studio now +1. Plug the modules into the hub in Beginner Studio and build the program from blocks. +2. Use **Print variable** and **Wait** blocks to watch the sensor in the serial monitor. +3. Pick a threshold by looking at the numbers, write the if/then rule, upload with **Upload** + (Chrome or Edge). +4. Discuss with students where the rule fails (noise, a different room, a different person). + That failure is the reason the Track B version exists. + +### Track B, Arduino + ML +1. **Collect.** Write a short Arduino sketch that prints one line of comma-separated readings at a + steady rate over USB serial (for example `distance,loudness` every 50 ms at 115200 baud). +2. **Label and train.** Pick one route: + - **Edge Impulse** (free, browser based): stream the serial data in with + `edge-impulse-data-forwarder`, label the recordings, then add a processing block + (Spectral analysis for movement or pulse, MFE/MFCC for audio, Raw for slow sensors) and a + learning block (Classification, Anomaly detection K-means, or Regression). + - **scikit-learn + micromlgen:** save the serial log as CSV, train a decision tree, random + forest or SVM in Python, and export it to a plain C header with `micromlgen`. + - **TensorFlow Lite Micro:** train a small Keras model, convert it to a `.tflite` file and + run it with the EloquentTinyML or TensorFlowLite_ESP32 library. +3. **Check it fits.** Edge Impulse shows the estimated RAM, flash and time per prediction; + aim for under about 100 KB of RAM and under 100 ms. +4. **Deploy.** Export as an Arduino library (Edge Impulse) or include the header, open the + example sketch in the Arduino IDE, choose the ESP32 board, add the outputs (OLED, LED, relay, + servo) and upload. +5. **On-device learning** (no computer): some projects below learn while running, by storing + labelled samples or running averages in RAM. These are the best first ML projects because + students see the board learn in front of them. + +--- + +## 3. Hardware rules for ML projects + +- **The analog jacks A1-A4 are on ESP32 ADC2 pins** (IO4, IO15, IO2, IO0). ADC2 readings fail + while WiFi is running, and Beginner Studio advises keeping WiFi and BLE off while reading them. + For projects that also use the radio, use the DHT11, HC-SR04, HW-605 or RFID, which are not + analog, or read the analog sensors first and switch the radio on afterwards. +- **A4 is IO0, the BOOT pin.** Do not plug a button into A4: holding it at reset stops the board + from starting. A2 (IO15) and A3 (IO2) are also boot-strapping pins: fine for sensors, LEDs and + relays, but if the board will not start or upload, unplug what is on them and retry. The DHT11 + must use A1. +- **The HC-05 on UART shares the USB serial port.** Unplug it while collecting training data over + USB, or the data stream and the Bluetooth module will interfere. +- **D13 and 3D share IO33.** With the RFID reader on 3D, use A1-A4 for buttons, LEDs and servos. +- **D5 is reserved for the HC-SR04** (Trig IO26, Echo IO25). +- **The OLED and HW-605 share one I2C bus** (SDA 21, SCL 22). Plug them into I2C and I2C1; both + work at the same time. +- **The MQ-2 heater needs about a minute to warm up.** Throw away readings from the first + minute, and record training data only after warm-up. Its values are raw, not calibrated ppm. +- **Microphone sampling.** `analogRead` in a tight timed loop gives a few kHz to around 10 kHz; + audio models usually expect 8-16 kHz. First check what the module outputs: print it fast while + quiet. A value that wobbles around a middle value (about 2000) is raw audio and supports + sound classification. A value that sits near zero and rises with noise is a loudness envelope, + which only supports loudness-pattern projects (claps, knocks, noise level). +- **DHT11 is slow** (one reading per second, about +/-2 degrees C). Use it for slowly changing + situations, not fast events. + +--- + +## 4. How to run a project + +Every project below follows the same six-stage cycle. A "session" is about 45 minutes. + +1. **Ask.** Read the driving question, discuss where this problem appears in real life, and agree + on what "working" means (the success check). +2. **Build.** Plug the modules into the listed jacks and test each one on its own. +3. **Collect.** Watch or record sensor data. In Track B, label every recording and keep some + data, ideally from people or days not used for training, aside for testing. +4. **Model.** Track A: write and tune the rule. Track B: train or teach the model, then deploy it. +5. **Test and improve.** Measure against the success check with new data, find the failures, and + fix them with better data or features. +6. **Present.** Show the live demo and a poster or slide covering the problem, the data, the + model, the results, and its limits and ethics. + +**Assessment (same for every project):** a working build; data quality (enough, labelled, +balanced); honest testing on new data; a clear explanation of how the model decides; and +reflection on limits, fairness and privacy. + +--- + +## 5. Projects + +Difficulty: **Starter** (first lessons), **Intermediate** (needs Arduino IDE), **Advanced** +(careful data collection or signal processing). + +| # | Project | Track | Level | Time | Main modules | +| --- | --- | --- | --- | --- | --- | +| 1 | Clap lamp | A | Starter | 2 sessions | Microphone, LED | +| 2 | Sound classifier | B | Intermediate | 4-5 sessions | Microphone, OLED | +| 3 | Voice switch | B | Advanced | 6-8 sessions | Microphone, Relay | +| 4 | Motor health monitor | B | Intermediate | 4 sessions | L293D, Microphone | +| 5 | Heart-rate display with alert | A | Starter | 2 sessions | HW-605, OLED | +| 6 | Resting vs active | B | Intermediate | 4 sessions | HW-605, OLED | +| 7 | Calm or alert indicator | B | Advanced | 6 sessions | HW-605, OLED | +| 8 | Presence alert | A | Starter | 2 sessions | HC-SR04, Servo | +| 9 | Hand-gesture controller | B | Intermediate | 5 sessions | HC-SR04, Servo, Relay | +| 10 | Smart dustbin | B | Intermediate | 4 sessions | HC-SR04, Servo | +| 11 | Room comfort classifier | B | Intermediate | 5 sessions over a week | DHT11, L293D fan | +| 12 | Gas and smoke anomaly detector | A to B | Starter to Intermediate | 4 sessions | MQ-2, DHT11 | +| 13 | Predictive garden watering | B | Intermediate | 4 sessions over 1-2 weeks | Soil, DHT11, Relay | +| 14 | Teach the board (kNN trainer) | B | Starter | 3 sessions | HC-SR04, Microphone, Potentiometer | +| 15 | Personal fan | B | Intermediate | 4 sessions plus a few days | DHT11, Potentiometer, L293D | +| 16 | Results over BLE | A | Starter | 1-2 sessions | DHT11, BLE | +| 17 | Which room am I in? | B | Advanced | 6 sessions | BLE, several kits | +| 18 | Smart door with unusual-access alert | A to B | Intermediate to Advanced | 5-6 sessions | RFID, HC-SR04, Servo | + +### Sound (microphone) + +#### Project 1: Clap lamp +**Driving question:** Can a lamp tell a clap from everyday classroom noise? + +**Track:** A. **Level:** Starter. **Time:** 2 sessions. + +**Kit:** Microphone (A1), LED (D13), or Relay (D13) switching a low-voltage lamp. + +**Milestones:** +1. In Beginner Studio, read the microphone and print `soundLevel` every 0.1 s. +2. Fill a table of values for silence, talking, music and clapping. +3. Choose a threshold and build the rule: if `soundLevel` is above it, turn the LED on, wait + 10 s, turn it off. +4. Test 10 claps and 5 minutes of normal talking; count caught claps and false triggers. +5. Retune the threshold and test again. + +**What the AI learns:** Nothing yet. The student is the model, choosing the threshold by hand. + +**Showcase:** Live demo plus the results table (claps caught vs false triggers). + +**Success check:** At least 8 of 10 claps caught, at most 2 false triggers in 5 minutes of talk. + +**Extend it:** Try a double-clap rule, then compare with the trained model in project 2. + +#### Project 2: Sound classifier (clap, whistle, voice, silence) +**Driving question:** Can the board recognise what it hears without sending audio to the cloud? + +**Track:** B. **Level:** Intermediate (needs a raw-audio microphone output). **Time:** 4-5 +sessions. + +**Kit:** Microphone (A1), OLED (I2C), LED (D13). + +**Milestones:** +1. Run the microphone check from section 3 to confirm the module gives raw audio. +2. Write a sketch that records 1-second clips at a steady rate (about 8 kHz) into RAM and prints + each clip over serial; save the clips and upload them to Edge Impulse. +3. Record about 2 minutes per class (clap, whistle, voice, silence) in the real classroom. +4. In Edge Impulse, use an MFE processing block and a classification block; study the confusion + matrix. +5. Deploy as an Arduino library: the OLED shows the class and confidence, and the LED lights on + "clap". +6. Test with classmates whose voices were not in the training data. + +**What the AI learns:** The frequency pattern of each sound class. + +**Showcase:** Live demo plus a poster of the confusion matrix and the hardest mistakes. + +**Success check:** At least 80 % accuracy on test data, and it works for someone not in the +training data. + +**Extend it:** Add a "door knock" class and compare against the hand-made rule from project 1. + +#### Project 3: Two-word voice switch ("on" / "off") +**Driving question:** Can we control a light by voice with no internet connection? + +**Track:** B. **Level:** Advanced (stretch goal; accuracy depends on the microphone module). +**Time:** 6-8 sessions. + +**Kit:** Microphone (A1), Relay (D13), OLED (I2C). + +**Milestones:** +1. Reuse the audio capture pipeline from project 2. +2. Collect "on", "off", "noise" and "unknown" (other words), with 10+ speakers and 50+ clips per + word. +3. Train a keyword-spotting model in Edge Impulse (MFCC features plus classification). +4. Deploy and only act above a confidence threshold (for example 0.8), with a 2-second cooldown. +5. Count false triggers during 10 minutes of normal conversation. + +**What the AI learns:** The sound shape of two words, separated from everything else. + +**Showcase:** Live voice demo plus a chart of accuracy per speaker. + +**Success check:** At least 7 of 10 commands obeyed, at most 1 false trigger in 10 minutes. + +**Extend it:** Discuss why datasets need many voices, accents and ages. + +#### Project 4: Motor health monitor +**Driving question:** Can a machine warn us before it breaks? + +**Track:** B. **Level:** Intermediate. **Time:** 4 sessions. + +**Kit:** L293D with a DC motor or fan (MD), Microphone (A1) mounted next to the motor, OLED (I2C). + +**Milestones:** +1. Run the motor at two or three fixed speeds. +2. Record several minutes of normal running sound at each speed. +3. In Edge Impulse, train anomaly detection (K-means) on normal data only. +4. Deploy: the OLED shows the anomaly score, and the motor stops if the score stays high for + 2 seconds. +5. Test with faults: tape a small weight to the blade, touch the shaft lightly, loosen the mount. + +**What the AI learns:** What normal sounds like, so anything else stands out. + +**Showcase:** Demo of a fault being caught, plus a graph of anomaly score over time. + +**Success check:** All three faults flagged; 5 minutes of normal running with no alarm. + +**Extend it:** Collect fault examples and train a classifier that names the fault. + +### Body (Heartbeat HW-605) + +These projects are for learning only. They are not medical devices. Get consent before +recording anyone's pulse, and do not share the data outside the class. + +#### Project 5: Heart-rate display with alert +**Driving question:** What does my heart rate say about what I am doing? + +**Track:** A. **Level:** Starter. **Time:** 2 sessions. + +**Kit:** HW-605 (I2C), OLED (I2C1), LED (D13). + +**Milestones:** +1. In Beginner Studio, read the heartbeat and show the number on the OLED. +2. Check it against a manual pulse count (count for 30 seconds and double it). +3. Record each student's BPM seated and after 20 jumping jacks. +4. Set an alert threshold: if `heartRate` is above it, turn the LED on. +5. Discuss why one threshold does not suit everyone. + +**What the AI learns:** Nothing yet; the threshold is chosen by hand. + +**Showcase:** A class chart of resting vs active BPM. + +**Success check:** The display stays within 5 BPM of the manual count. + +**Extend it:** Move on to project 6. + +#### Project 6: Resting vs active classifier +**Driving question:** Can the board tell from a pulse alone whether someone has just exercised? + +**Track:** B. **Level:** Intermediate. **Time:** 4 sessions. + +**Kit:** HW-605 (I2C), OLED (I2C1). + +**Milestones:** +1. Write a sketch that prints the raw IR value at about 50 Hz (MAX30105 library). +2. Record 10-second windows from at least 8 students, seated and after exercise. +3. Keep two students' data out for testing. +4. Train in Edge Impulse with spectral analysis plus classification. +5. Deploy: the OLED shows "resting" or "active". Test on the held-out students. + +**What the AI learns:** The pulse-waveform pattern of each state. + +**Showcase:** Results per student and a discussion of who it worked worst for. + +**Success check:** At least 80 % accuracy on the held-out students. + +**Extend it:** Add a "recovering" class. + +#### Project 7: Calm or alert indicator +**Driving question:** Can heart-rate variability show when someone is calm? + +**Track:** B. **Level:** Advanced. **Time:** 6 sessions. + +**Kit:** HW-605 (I2C), OLED (I2C1), LED (D13). + +**Milestones:** +1. Detect beats with `checkForBeat` and measure the time between beats. +2. Compute RMSSD (variation between beats) over 30 seconds. +3. Each student records a 2-minute calm baseline with slow breathing. +4. The board learns each student's baseline and shows "alert" when RMSSD falls well below it. +5. Test during a timed quiz and during relaxation. + +**What the AI learns:** Each person's own normal, then deviations from it. + +**Showcase:** Before/after graphs and a class-written set of consent and privacy rules. + +**Success check:** The indicator moves in the expected direction for most students. + +**Extend it:** Combine BPM and RMSSD in a logistic regression model. + +### Distance (HC-SR04) + +#### Project 8: Presence alert +**Driving question:** How does an automatic door know you are coming? + +**Track:** A. **Level:** Starter. **Time:** 2 sessions. + +**Kit:** HC-SR04 (D5), Servo (A1), LED (D13). + +**Milestones:** +1. In Beginner Studio, read the distance and print it. +2. Walk towards the sensor and past it; note the readings. +3. Rule: if the distance is under 50 cm, turn the servo to 90 degrees and the LED on; otherwise + back to 0. +4. Test 10 approaches and 10 walk-pasts at 30 cm; count wrong openings. + +**What the AI learns:** Nothing yet; a fixed distance rule. + +**Showcase:** Demo plus the count of false openings (the number project 10 must beat). + +**Success check:** Opens for every approach; false openings recorded honestly. + +**Extend it:** Move on to project 10. + +#### Project 9: Hand-gesture controller (approach, swipe, hold) +**Driving question:** Can one distance sensor understand several hand gestures? + +**Track:** B. **Level:** Intermediate. **Time:** 5 sessions. + +**Kit:** HC-SR04 (D5), Servo (A1), Relay (D13), OLED (I2C). + +**Milestones:** +1. Write a sketch that prints the distance 20 times per second. +2. Record 40+ one-second examples each of approach, swipe, hold and "nothing" with the data + forwarder. +3. Train in Edge Impulse (spectral or raw features plus a small neural network). +4. Deploy: swipe moves the servo, hold toggles the relay, and the OLED names the gesture. +5. Test with classmates who did not record training data. + +**What the AI learns:** The shape of the distance signal over one second for each gesture. + +**Showcase:** Live gesture demo plus accuracy per gesture. + +**Success check:** At least 85 % accuracy with new users. + +**Extend it:** Add a "double tap" gesture. + +#### Project 10: Smart dustbin that ignores passers-by +**Driving question:** Can the bin tell someone who wants to use it from someone walking past? + +**Track:** B. **Level:** Intermediate. **Time:** 4 sessions. + +**Kit:** HC-SR04 (D5), Servo (A1). + +**Milestones:** +1. Reuse the project 8 build and log distance at 20 Hz in 2-second windows. +2. Record "approach to use" and "walk past" from different angles and several people. +3. Compute features (closest distance, speed, how long the person stayed close) and train a + decision tree (micromlgen) or use Edge Impulse. +4. Deploy and repeat project 8's test. + +**What the AI learns:** Movement patterns that show intent. + +**Showcase:** Side-by-side comparison of false openings: rule (project 8) vs model. + +**Success check:** Fewer false openings than project 8, with no missed uses in 20 trials. + +**Extend it:** Count uses per day and send the count over BLE (the HC-SR04 is not analog, so BLE +does not disturb it). + +### Environment + +#### Project 11: Room comfort classifier +**Driving question:** What does "comfortable" mean for our class, and can the board learn it? + +**Track:** B. **Level:** Intermediate. **Time:** 5 sessions spread over a week. + +**Kit:** DHT11 (A1), OLED (I2C), L293D fan (MD). + +**Milestones:** +1. Log temperature and humidity every minute (Beginner Studio print blocks work for this). +2. Several times a day, the class votes: comfortable, too hot, too humid or cold. Record the + time of each vote. +3. Match votes to readings in a spreadsheet and export a CSV. +4. Train a small decision tree (depth 3) in scikit-learn, draw it, and export it with micromlgen. +5. Deploy: the OLED shows the comfort class and the fan runs on "too hot". + +**What the AI learns:** The class's own comfort zones, as a readable set of rules. + +**Showcase:** The printed decision tree next to the rule the class would have written by hand. + +**Success check:** Agrees with the class vote at least 75 % of the time on a held-out day, and +students can read the tree aloud. + +**Extend it:** Add time of day as a feature. + +#### Project 12: Gas and smoke anomaly detector +**Driving question:** How can a sensor know what "normal air" is in this room? + +**Track:** A, then B. **Level:** Starter, then Intermediate. **Time:** 4 sessions. + +**Kit:** MQ-2 (A2), DHT11 (A1), LED (D13), Relay (A3) for an extractor fan. + +**Milestones:** +1. Track A: in Beginner Studio, print the gas level after a 1-minute warm-up and build a fixed + threshold alarm. +2. Track B: in Arduino, learn the room's normal level and spread over 10 minutes (running mean + and standard deviation). +3. Alarm when the reading stays more than 3 standard deviations above normal for 5 seconds; + update the baseline slowly so it follows normal drift. +4. Log a whole school day and count false alarms for both versions. +5. Supervised test only: the teacher releases a short puff of gas from an unlit lighter near + the sensor. + +**What the AI learns:** The room's normal level and how much it usually varies. + +**Showcase:** A graph of a day's readings with both alarm methods marked. + +**Success check:** Detects the test within 10 seconds, with no false alarms over a school day. + +**Extend it:** Train Edge Impulse anomaly detection that also uses temperature and humidity. + +#### Project 13: Predictive garden watering +**Driving question:** Can we water a plant before it gets thirsty instead of after? + +**Track:** B. **Level:** Intermediate. **Time:** 4 sessions spread over 1-2 weeks. + +**Kit:** Soil Moisture (A2), DHT11 (A1), Relay with a small pump (D13), OLED (I2C). + +**Milestones:** +1. Log soil %, temperature and humidity every 10 minutes for several days. +2. Plot the drying curve and measure the drying rate (% per hour). +3. Fit a linear regression of drying rate against temperature and humidity (spreadsheet or + Python). +4. Deploy: the OLED shows "dry in about N hours", and the pump runs when the prediction drops + below 1 hour. +5. Run one pot with the old threshold rule and one with the prediction; compare. + +**What the AI learns:** How fast the soil dries in the current weather. + +**Showcase:** The drying-curve plot with predictions overlaid. + +**Success check:** Predictions within 2 hours of the real time the soil reached the threshold. + +**Extend it:** Send the prediction over BLE (read the soil sensor first, then advertise, because +the analog jacks share ADC2). + +### Teach by example (on-device learning) + +#### Project 14: Teach the board (kNN trainer) +**Driving question:** How does a machine learn from examples? + +**Track:** B. **Level:** Starter (the teacher provides the sketch; no computer training). +**Time:** 3 sessions. + +**Kit:** HC-SR04 (D5), Microphone (A2), Potentiometer (A1) to pick the label, Button (D13) to +record, OLED (I2C). + +**Milestones:** +1. Upload the teacher's sketch, which measures average distance and loudness every second. +2. Turn the potentiometer to choose a label ("nobody", "person quiet", "person talking"); the + OLED shows it. +3. Press the button to save an example; record 5-10 per label. +4. Switch to run mode: the board finds the 3 nearest saved examples and shows the winning label. +5. Experiment: too few examples, wrong examples, and different values of k. + +**What the AI learns:** k-nearest-neighbour: new situations are labelled like the closest +examples it has seen. + +**Showcase:** Live "teach and test" demo for another class. + +**Success check:** Students can explain why a wrong prediction happened and fix it by adding +examples. + +**Extend it:** Add a third feature, such as how fast the distance is changing. + +#### Project 15: Personal fan that learns your preference +**Driving question:** Can a device learn what you like just by watching your choices? + +**Track:** B. **Level:** Intermediate. **Time:** 4 sessions plus a few days of use. + +**Kit:** DHT11 (A1), Potentiometer (A2) to set the speed you like, Button (D13) to save, L293D +fan (MD), OLED (I2C). + +**Milestones:** +1. Manual mode: the potentiometer sets the fan speed. +2. Each button press saves (temperature, humidity, speed) to flash with the Preferences library, + so the data survives power-off. +3. Auto mode: predict the speed from the 3 nearest saved examples, or from a fitted line. +4. Use it for a few days; every manual correction becomes new training data. +5. Plot the learned speed against temperature. + +**What the AI learns:** Your preferred fan speed for each temperature and humidity. + +**Showcase:** The learned speed curve and a demo of switching between manual and auto. + +**Success check:** In auto mode, the speed is within about 15 % of what the user would choose. + +**Extend it:** Add per-user profiles with RFID (move the button to A3, since 3D shares IO33 with +D13). + +### Connected and multi-sensor + +#### Project 16: Send results to a phone over BLE +**Driving question:** What is the difference between sending data and sending a decision? + +**Track:** A. **Level:** Starter. **Time:** 1-2 sessions. + +**Kit:** DHT11 (A1), OLED (I2C), Bluetooth (built into the ESP32). + +**Milestones:** +1. In Beginner Studio, start BLE advertising with a team name. +2. Rule: if the temperature is above 30, send "HOT", otherwise "OK"; show it on the OLED too. +3. Read it on a phone with a BLE scanner app (for example nRF Connect). +4. Discuss what leaves the board and what stays private. + +**What the AI learns:** Nothing yet; the point is edge vs cloud. + +**Showcase:** Phone and board side by side as the status changes. + +**Success check:** The phone shows the new status within a few seconds. + +**Extend it:** Send the comfort class from project 11 instead. + +#### Project 17: Which room am I in? (BLE signal fingerprint) +**Driving question:** Can a device find its location indoors, where GPS does not work? + +**Track:** B. **Level:** Advanced. **Time:** 6 sessions. + +**Kit:** Bluetooth (built in), OLED (I2C), plus three or more other kits running the +**BLE Beacon** template with unique names, one per room. + +**Milestones:** +1. Place the beacon kits in different rooms or corners. +2. Write a sketch that scans BLE and prints the signal strength (RSSI) of each beacon every + second. +3. Walk each room and record labelled readings (2 minutes per room, from several spots). +4. Classify with kNN on the board, smoothing over the last 5 predictions. +5. Do a test walk and record how often the room is right. + +**What the AI learns:** The signal-strength "fingerprint" of each room. + +**Showcase:** A floor plan marked with where it was right and wrong. + +**Success check:** At least 80 % correct on a test walk. + +**Extend it:** Discuss the privacy of tracking people indoors. + +#### Project 18: Smart door with unusual-access alert +**Driving question:** Can a lock notice when something is out of the ordinary? + +**Track:** A, then B. **Level:** Intermediate, then Advanced. **Time:** 5-6 sessions. + +**Kit:** RFID RC522 (3D), HC-SR04 (D5), Servo lock (A1), LED (A2). D13 stays free because it +shares IO33 with 3D. + +**Milestones:** +1. Track A: in Beginner Studio, read the card ID and unlock the servo only for a known card while + someone stands within 40 cm. +2. Track B: connect to WiFi and get the time from the internet (NTP); log each card and the hour + it was used. None of these sensors is analog, so WiFi is fine. +3. Build each card's usual-hours pattern over a week. +4. Flag a tap at an hour that card has rarely used: blink the LED and log it. +5. Agree on privacy rules: what is stored, who can see it, and when it is deleted. + +**What the AI learns:** Each card holder's normal routine, so unusual times stand out. + +**Showcase:** A week's access chart with the flagged taps highlighted. + +**Success check:** Test taps at unusual hours are flagged; normal taps are not. + +**Extend it:** Also flag a card used when nobody is standing at the door. + +--- + +## 6. Not possible with this kit + +- **Vision** (face, object or colour recognition): there is no camera. An ESP32-CAM board is + the usual add-on. +- **Motion gestures, step counting, fall detection**: there is no accelerometer. An MPU-6050 + breakout on the I2C bus (wired to an RJ11 plug for the I2C1 jack) would add this. +- **Full speech recognition or chatbots**: too large for the ESP32. Only a few keywords are + realistic (project 3). +- **Calibrated gas or medical readings**: the MQ-2 and HW-605 give relative values for + learning, not certified measurements. + +--- + +## 7. Suggested learning path + +| Step | Project | Track | Idea introduced | +| --- | --- | --- | --- | +| 1 | 1. Clap lamp | A | A rule is a hand-made model | +| 2 | 8. Presence alert | A | Rules fail in real situations | +| 3 | 5. Heart-rate display | A | Sensor noise and personal differences | +| 4 | 16. Results over BLE | A | Edge vs cloud | +| 5 | 14. Teach the board | B | Training vs inference, on the board | +| 6 | 15. Personal fan | B | Regression and personalisation | +| 7 | 11. Room comfort | B | Decision trees learned from data | +| 8 | 12. Gas anomaly | B | Baselines and anomaly detection | +| 9 | 9. Hand gestures | B | Time-series windows and neural networks | +| 10 | 2. Sound classifier | B | Audio features and confusion matrices | +| 11 | 4. Motor health | B | Predictive maintenance | +| 12 | 13. Predictive watering | B | Prediction instead of reaction | +| 13 | 6, 7, 10, 17, 18 | B | Open projects for advanced students | +| 14 | 3. Voice switch | B | Stretch goal: keyword spotting | diff --git a/docs/EDGE_AI_TEACH_MODE_PLAN.md b/docs/EDGE_AI_TEACH_MODE_PLAN.md new file mode 100644 index 00000000000..156b8faf949 --- /dev/null +++ b/docs/EDGE_AI_TEACH_MODE_PLAN.md @@ -0,0 +1,220 @@ +# Edge AI "Teach the board": implementation plan + +Status: plan, not started. Based on the draft "Edge AI Teach Mode" plan, checked against the code on `main` (commit 7ab6a5e4 plus uncommitted MPU6050 work in `condition.js` and `sensorReads.js`). + +## Goal +Students record examples from the motion sensor, the microphone or their wired kit sensors. The browser trains a tiny kNN model, and Upload writes it into the sketch as plain C, so the ESP32 recognises things offline. Nothing changes on the compile server. + +## What changed from the draft (and why) + +| # | Draft said | Plan now | Why | +|---|---|---|---| +| 1 | "Version bump with migration" in autosave | `loadProject` must accept **v1 and v2** | Today `data.v !== VERSION` returns `null`, so a plain bump silently wipes every student's saved project | +| 2 | Hold **Record** while doing the gesture | **Event capture**: click Record once; every detected wave/clap becomes one example; it stops by itself at 10 examples or after 20 s | A student needs both hands to wave the board, so they can't also hold a mouse button. It's also easier for motor-impaired students | +| 3 | Motion window "starts on a threshold, so `still` is recordable" | These contradict each other: a threshold trigger never fires for `still`. Event kinds (Motion, Sound) get a **built-in "Nothing" answer** when no event happens. Sensors stays continuous | Students don't need to record a "nothing" class, and the window lines up with the gesture | +| 4 | Accuracy by leave-one-out per example | **Leave-one-take-out** (group by recording take) | Examples from one take are near-copies, so plain leave-one-out reports 100% for models that fail in real use | +| 5 | Sound sampled at ~4 kHz | **~8 kHz** if ADC2 can keep up (hardware check), else 4 kHz with bands under 2 kHz | At 4 kHz anything above 2 kHz folds back (whistles are 1–3 kHz) | +| 6 | Model arrays always in the generated sketch | The live C++ panel shows `// AI model: 3 things, 72 examples (added at Upload)`. Upload and Copy get the full arrays | ~30 KB of numbers would bury the student's code and recompute on every edit. Same pattern as the hidden Cloud secrets | +| 7 | Separate recorder sketch | Recorder = `generateArduino(connections, [], {aiRecorder: kind})` | It reuses the exact same setup (pinModes, **pumps/solenoids driven off at boot**, DHT/ultrasonic helpers) and the same feature C code as the real sketch, so there is no second code path to drift | +| 8 | "Train" stores a model | The model is **always computed from the samples** (kNN training is just standardising). Train is the step that shows the accuracy | Saved state can never hold a stale model | +| 9 | Cloud: "a reading named after the thing" | One 0/1 reading per thing, `ai_` (regex `^[a-zA-Z][a-zA-Z0-9_]{0,31}$`). It counts toward the server's 24-key limit | Existing alert rules work unchanged (`ai_wave > 0`) | + +## Decisions to confirm before coding +1. **Event capture with a built-in "Nothing" answer** for Motion and Sound (row 2/3). This means held poses such as "tilted left" aren't AI things in v1; the Tilt block covers those. *Recommended.* +2. **"Ask the AI" blocks the loop** for up to 2 s (it waits for an event, then classifies). A background task would let LEDs keep blinking, but it would share the I2C bus with OLED/HW-605 across tasks and need a mutex. *Recommended: blocking in v1.* +3. **One AI per project, 2–4 things, 10–40 examples per thing.** + +## Phases +Each phase ends green (`npx jest --testPathIgnorePatterns node_modules -- beginner-studio`) and can be committed separately. + +### Phase 0: Hardware checks (before Phase 3) +- [ ] The kit mic outputs raw audio, not only an envelope: scope it, or print 2,000 raw `analogRead` values for a clap and a whistle. If it's only an envelope, Sound uses loudness + time-slice features only, and Clap or Whistle becomes "Clap or Knock". +- [ ] How fast ADC2 `analogRead` runs on GPIO 4 (target ≥8 kHz sustained with `micros()` pacing). +- [ ] MPU6050 boards in the kit: the `WHO_AM_I` value (genuine 0x68; clones return 0x70/0x72/0x98) and the AD0 address (0x68 or 0x69). +- [ ] The MPU6050 at 100 kHz I2C alongside OLED (0x3C) and HW-605 (0x57): no address clash expected; confirm reads at 100 Hz. + +### Phase 1: MPU6050 part (prerequisite, already started) +- Add `mpu6050` to `domain/modules.js`: I2C, `extraValues: [{name:'tiltAngle'}, {name:'shakeLevel'}]`, action `read_motion`. The uncommitted `condition.js`/`sensorReads.js` changes already expect this shape. +- Raw `Wire` driver in codegen (no library): + - wake it with `PWR_MGMT_1 = 0` + - ±2 g / ±250 °/s ranges + - burst-read 14 bytes from `0x3B` + - try 0x68, then 0x69 + - accept any `WHO_AM_I` value but print it. +- Read failure: `tiltAngle = 0`, `shakeLevel = -1`, print `MPU6050: not found - check the I2C cable` once. +- Port rules: I2C or I2C1, shares the bus with OLED/HW-605, works with Cloud (no ADC2). +- Tests: module present, port picking, codegen includes `Wire.h` once even with OLED + HW-605. + +### Phase 2: Core domain (`src/beginner-studio/domain/ai/`) +**`aiKinds.js`** +- Kinds: `motion` (needs mpu6050, event), `sound` (needs mic, event), `sensors` (continuous). +- Sensors kind uses parts with a numeric reading: pot, soil, mq2, dht (temperature + humidity), ultra, ir, pir, reed, ldr, flame, water, mic loudness. + - Excluded: pulse (needs continuous sampling), rfid and hc05 (not numbers), btn (an If block already covers it). +- `availableKinds(connections)` returns the kinds the current wiring allows. +- `featureNames(kind, connections)` and `signature(kind, connections)`: + - The signature covers the kind, `FEATURE_VERSION`, and the sorted module ids of the parts used. + - The jack is not part of it: moving the mic from A1 to A2 keeps the examples. +- Limits: 2–4 things; names 1–16 characters, unique ignoring case, not "Nothing" / "Not sure"; 10 examples per thing before Train, 40 max. + +**`knn.js`** (pure, deterministic) +- Standardise with the mean and standard deviation from the training data. + - A feature whose standard deviation is under 1e-6 gets weight 0 (a constant sensor would otherwise divide by zero). +- k = 3 in Euclidean distance. A 1-1-1 vote goes to the single nearest example. + - With 2 things and k = 3 there are no ties. +- "Not sure" distance limit: for each thing, take the 95th percentile of each example's nearest same-thing distance (leave-one-take-out), times 1.5. Also "Not sure" when the vote is split and the nearest example is beyond the limit. +- `accuracy(samples)`: leave-one-take-out. With a single take per thing, fall back to leave-one-out and set the label "rough guess, record another take". +- `tooAlike(samples)`: the pair of things the leave-one-take-out run confuses most, or whose centres are closer than 1.5 × their average spread. +- `outliers(samples)`: examples nearer to another thing's centre than their own; flagged in the list. +- Imbalance: warn when the largest thing has more than 2× the examples of the smallest. + +**`aiLine.js`** (serial protocol parser) +- The board sends `TBAI1,H,,,` once at start and after every 50 lines, then `TBAI1,F,,` per example and `TBAI1,E,` for errors. +- Each line is checked in order: + 1. The prefix and version must match. + 2. The field count must equal `n` from the header. + 3. Every value must be finite. + 4. The line must be at most 400 characters. +- Lines arriving before a header with the current signature are ignored. The browser can't trust a recorder that was uploaded before the wiring changed. +- Junk is dropped without a message: half-lines, ESP32 boot noise at 115200 shown at 9600, and normal sketch output. +- Error codes: + - `no_mpu`: "Check the I2C cable" + - `mic_flat`: "The mic reads the same value; check the A-port cable" + - `too_fast`: the board is overloaded. + +**`aiFirmware.js`** (C emitters, shared by the recorder and the real sketch) +- `aiCapture(float *f)` per kind. It returns `true` with features, or `false` when no event happened before the timeout. + - **Motion:** a 100 Hz ring buffer, triggered when |accel| − 1 g or |gyro| goes over a threshold calibrated at boot. The window is 1 s, including 200 ms before the trigger. For each of the 6 axes: mean, standard deviation, min and max, giving 24 features. + - **Sound:** the DC offset is removed (running mean). The trigger is loudness above the ambient level × 3, with ambient tracked by a slow EMA when quiet. The window is 0.5 s, including 50 ms before the trigger. Features (13): RMS, peak, zero-crossing rate, Goertzel energy at 4 bands (the bands depend on the sample rate from Phase 0), and RMS in 4 time slices. The buffer is `int16_t[4000]`, 8 KB, held in a static. + - **Sensors:** a 1 s average of each part's existing reader. + - DHT reuses its 2 s cached value. + - Ultrasonic uses the median of 5 readings, and −1 is stored as the last good value. + - This kind is always `true` (no events). +- `aiClassify()`: + - The model data is `const float` arrays in flash: mean, scale, examples, labels and limits. + - The maths is in `float`. + - It returns the thing index, `-1` for "Not sure", or `-2` for "Nothing". +- The recorder loop calls `aiCapture`, prints a `TBAI1,F` line, and repeats. It prints `H` lines periodically and blinks the onboard LED on each capture so the student sees it worked. +- The real sketch: `aiAsk()` runs `aiCapture` (a 2 s event timeout), then `aiClassify`, and stores the result in `aiAnswer`. It prints `AI: wave` / `AI: not sure` / `AI: nothing`, rate-limited. + +### Phase 3: State, autosave, undo +- `state.ai = null | {kind, things:[{id, name}], samples:[{thing, take, f:[...]}], sig}`. Samples are rounded to 4 significant digits. +- `autosave.js`: + - `VERSION = 2`; `loadProject` accepts v1 (with `ai: null`) and v2. + - `cleanAi()` drops anything malformed: unknown thing ids, wrong feature length, non-finite values, more than 4 things. + - `useAutosave` effect deps add `state.ai`. + - Size: ~160 examples × 24 values is ~25 KB, well under quota. A save failure (`false`) shows a status-bar warning; today it's silent. +- `useUndoHistory`: + - The snapshot adds `ai`. + - A take arrives about every second, but `MERGE_MS` is only 700 ms. While recording, merging is forced so one take is one undo step. + - Undo/redo are disabled while recording (otherwise undo would delete samples mid-take). +- `useStudioActions`: `setAiKind` (it clears samples, so the UI asks first), `addThing`, `renameThing`, `removeThing` (it deletes that thing's samples), `addSamples`, `deleteSample`, `deleteTake`, `clearThing`. +- Loading a template or a project replaces `ai`, the same way it replaces wiring. + +### Phase 4: Teach page +- The **AI** button sits in `TopBar.jsx` next to IoT and opens `view: 'ai'` (the same pattern as the Cloud page in `App.jsx`). +- `components/ai/TeachView.jsx` has three steps. + 1. **Pick what it pays attention to** + - It shows only the kinds the wiring allows. + - With none available it says what to wire, e.g. "Add the motion sensor or the microphone", with an Add button. + 2. **Get board ready** + - It uploads the recorder through `uploadCode` (`UploadContext`) and starts listening through `addSerialDataListener` + `createLineSplitter` (as `listenToBoard` in `useCloudLive.js`). + - The page shows "Board ready" once a header with the current signature arrives. + 3. **Teach** + - There is one card per thing: name, example count and a Record button. + - Record shows "Do it now: 10 more" with a live level bar; each captured example appears as a mini sparkline with ✕. + - Train shows "The AI got 18 of 20 right", plus warnings for things that are too alike, outliers and imbalance. + - **Try it** shows live guesses, including "Not sure" and "Nothing", computed in the browser from the recorder stream. +- `hooks/useAiRecorder.js` holds the recording logic. + - The first example after Record is discarded if it started before the click. + - An example in flight when recording stops is dropped. + - On disconnect it keeps what's recorded and shows "Board unplugged — plug it back and click Get board ready". + - When an upload starts, it pauses and stops listening (the pipeline closes the port). + - It keeps a `boardHas: 'recorder' | 'program' | null` flag for the session. +- Leaving the Teach page while the recorder is on the board shows a banner: "The board is running the AI recorder. Upload your program to use it." The Upload button turns highlighted. +- When Web Serial isn't available (Firefox, Safari, phone), things can still be edited, but recording shows the existing "Use Chrome or Edge on a computer" message. +- The serial monitor panel still shows TBAI lines. The Teach page has a "hide AI lines" filter. +- Keyboard: Space starts Record on the focused card, Esc stops it; the cards are buttons with `aria-pressed`. + +### Phase 5: Blocks and codegen +- **Ask the AI** (`ai_ask`): + - It's a silent read in `sensorReads.js` (added to `SILENT_READS` / `READ_BLOCKS`, var `aiAnswer`). + - Codegen inserts it automatically before any `AI thinks it is` condition, exactly like the other sensors. +- **AI thinks it is [thing]** (`ai_is` sensor option in `condition.js`): + - It stores the **thing id**, not the name, so renaming keeps it working. + - The options are the things plus "Not sure" and "Nothing" (event kinds only). +- `blockMeta.js` and `ProgramBlock.jsx` get the labels and the dropdown. + - A block pointing at a deleted thing shows "pick a thing" in red. +- Codegen: + - The model, helpers, `Wire`/buffer setup and `aiAsk` are emitted **only when the program uses AI blocks**. + - AI state alone adds nothing. +- Upload is blocked (via the same path as `cloudUploadProblem`, as a new `aiUploadProblem`) when the program uses AI blocks and any of these holds: + - the AI is missing, or has fewer than 2 things with 10+ examples each ("Teach the AI first"); + - the signature doesn't match the wiring ("You changed the parts the AI listens to. Record again on the AI page."); + - a block points at a deleted thing; + - `kind === 'sound'` while Cloud is wired. In practice the shelf already stops this, but the check stays as a guard for old saves. +- Cloud: when Cloud is on and the program uses AI, each thing becomes a reading `ai_` (0/1, slugs de-duplicated, e.g. `ai_wave`, `ai_wave2`). It's sent only on change, plus the usual heartbeat. If wired readings plus AI keys would exceed 24, Upload is blocked with a clear message. +- Thing names go through `cText` escaping in C strings, so quotes, backslashes and emoji are safe. + +### Phase 6: Templates +They ship with things but no examples, and open on the Teach page: +- **Magic Wand** (MPU6050 + LED + buzzer): `wave`, `circle`, `flick`. +- **Clap or Whistle** (mic + LED): `clap`, `whistle`. If Phase 0 finds only an envelope, it becomes `clap`, `knock`. +- **Room Mood** (LDR + DHT + ultrasonic + LED): `empty`, `someone here`, `lights off`. +- **Phone AI Alert** (Cloud + MPU6050): `knock on door`, `door opens`. A1–A4 aren't used, so the template is legal with Cloud. +- `scripts/check-templates.js` and `check-kit-projects.js` must pass. The templates must be legal under the Cloud and ADC2 rules. + +### Phase 7: Verification and docs +- Unit tests: + - `knn`: two clean clusters give 100%; overlapping clusters give "tooAlike"; a point far from everything gives "Not sure"; constant features; 1-1-1 votes; the leave-one-take-out leakage case. + - `aiLine`: partial lines, a stale signature, the wrong field count, NaN, boot noise. + - `autosave`: v1 to v2 migration, malformed AI data dropped. + - Undo: one take is one step; undo is disabled while recording. + - Codegen: the AI is absent when unused; arrays and lengths are consistent; Upload is blocked in each of the four cases above; the Cloud reading keys; the recorder keeps the pumps off. + - A **JS mirror of `aiClassify`** on 50 fixed vectors must match `knn.predict`. Ties within 1e-5 are allowed, because the board uses `float` and JS uses `double`. +- Size guard: the full sketch for Cloud + Motion with 4×40 examples stays under the 128 KB compile payload. Compile it once through the compile server and record the flash/RAM figures. +- Browser check: Teach page with a fake serial stream (inject lines through `addSerialDataListener`). +- Board runs: one per kind, plus a noisy-room test for Sound, and unplugging mid-take. +- Add an "Edge AI" section to `ARCHITECTURE.md`: the jack rules, the protocol and the limits. + +## Edge cases at a glance +| Area | Case | Handling | +|---|---|---| +| Saved data | Old v1 saves | Migrated, `ai: null` | +| Saved data | Corrupt AI data | Dropped field by field; the rest of the project loads | +| Saved data | Storage full / private mode | Status-bar warning (today it's silent) | +| Wiring | Part removed or added after training | Signature mismatch: Upload blocked, "Record again" | +| Wiring | Part moved to another jack | Examples kept | +| Wiring | Mic + Cloud | Already impossible (A ports are locked); also guarded at Upload | +| Wiring | Two of the same sensor | Features named by connection; both used | +| Wiring | The only AI part deleted | Kind unavailable; blocks red; Upload blocked | +| Recording | Both hands busy | Event capture; no holding needed | +| Recording | Neighbour claps while recording "whistle" | Outlier flag + ✕ on each example | +| Recording | Recorder from before a wiring change | Header signature mismatch; lines ignored; "Get board ready" again | +| Recording | Board unplugged mid-take, or an upload starts | Samples kept, recording paused | +| Recording | First or last example cut by Record/Stop | Discarded | +| Recording | MPU clone / not found | Accept any WHO_AM_I value; `no_mpu` message | +| Training | Constant feature | Weight 0 | +| Training | One take per thing | Leave-one-out fallback, "rough guess" label | +| Training | Uneven counts | Warning above 2× | +| Training | Two things too alike | Named pair + tip ("make them more different") | +| Board | Board still runs the recorder | Banner + highlighted Upload | +| Board | Student uses `wait 5` with AI | Fine, Ask blocks when called; doc tip about loop speed | +| Board | float vs double differences | Mirror test with tolerance | +| Board | I2C shared with OLED/HW-605 | Same task, same bus speed (100 kHz) | +| Board | Sketch size with Cloud | Size guard test + one real compile | +| Names | Rename after blocks use it | Blocks keep the id | +| Names | Quotes / emoji / duplicates / reserved | Escaped in C; unique; "Nothing" and "Not sure" reserved | +| Names | Cloud key limits | Slug + de-duplication; block Upload above 24 keys | +| Browser | No Web Serial | Editing allowed; recording shows the Chrome/Edge message | + +## Files +- New: + - `domain/ai/aiKinds.js`, `knn.js`, `aiLine.js`, `aiFirmware.js` + - `components/ai/TeachView.jsx` (+ `ThingCard.jsx`, `TryIt.jsx`) + - `hooks/useAiRecorder.js` + - tests under `test/unit/beginner-studio/ai/` +- Changed: + - Domain: `modules.js`, `codegen.js`, `condition.js`, `sensorReads.js`, `blockMeta.js`, `autosave.js`, `templates.js`, `cloud.js` + - Hooks: `useStudioActions.js`, `useUndoHistory.js`, `useAutosave.js` + - Components and context: `ProgramBlock.jsx`, `TopBar.jsx`, `App.jsx`, `StudioContext.jsx`, `UploadContext.jsx` + - Docs: `ARCHITECTURE.md` diff --git a/docs/KIT_DEVICE_SPECS.md b/docs/KIT_DEVICE_SPECS.md new file mode 100644 index 00000000000..ad5e3fc6c37 --- /dev/null +++ b/docs/KIT_DEVICE_SPECS.md @@ -0,0 +1,134 @@ +# TinkerBit Maker ESP32 kit: device specs + +The parts Beginner Studio supports, the jack each one plugs into, what it reads or does, and the limits the Studio enforces. The source of truth is [modules.js](../src/beginner-studio/domain/modules.js) (parts), [ports.js](../src/beginner-studio/domain/ports.js) (jacks and rules) and [codegen.js](../src/beginner-studio/domain/codegen.js) (what the generated sketch does). + +**Totals: 29 parts, 16 inputs and 13 outputs.** Three of the outputs also receive data: Bluetooth (BLE), HC-05 Bluetooth and TinkerBit Cloud. + +| Group | Count | +|-------|-------| +| Input controls | 2 | +| Sensors | 14 | +| Outputs (incl. 3 two-way parts) | 13 | +| **Total** | **29** | + +--- + +## 1. Board and jacks + +Board: Maker ESP32 on the RJ11 hub (FQBN `esp32:esp32:esp32`). Serial runs at 9600 baud. + +| Jack | GPIO | Kind | Used by | +|------|------|------|---------| +| A1 | IO4 | Analog / digital | Analog sensors, on/off parts; first choice for the DHT11 | +| A2 | IO15 (strapping) | Analog / digital | Analog sensors, on/off parts | +| A3 | IO2 (strapping) | Analog / digital | Analog sensors, on/off parts | +| A4 | IO0 (BOOT) | Analog / digital | Analog sensors, on/off parts; unplug if Upload acts up | +| D13 | IO33 | Digital | On/off parts (LED, button, relay, servo, ...) | +| D5 | IO25 Echo, IO26 Trig | Ultrasonic | HC-SR04 only | +| ST | IO12, IO13, IO14, IO27 | Stepper | Stepper motor only | +| MD | IO17, IO5 (motor A), IO18, IO19 (motor B) | Motor | L293D motor driver or 4-channel relay | +| I2C, I2C1 | IO21 SDA, IO22 SCL (one shared bus) | I2C | OLED screen, heartbeat sensor, MPU6050 | +| 3D | IO32 SS, IO33 RST, IO34 MISO (+ SCK IO16, MOSI IO23 on board) | SPI | RFID RC522 only | +| UART | IO3 RX, IO1 TX (same as USB serial) | UART | HC-05 only | +| ESP (onboard) | — | Built in | Bluetooth (BLE), TinkerBit Cloud | + +Jack rules: + +- **D13 and 3D cannot be used together**: both use IO33. +- **D5 is kept for the ultrasonic sensor**: driving its Echo pin as an output heats the module. +- **A1–A4 are off while Cloud is on**: they are on ADC2, which WiFi takes over. +- **I2C is one shared bus**: the OLED, heartbeat sensor and MPU6050 can all be plugged in at once; `Wire.begin` runs once. +- **A2, A3, A4 and ST are strapping pins**: A4 (BOOT) is the one most likely to stop an upload. + +### 1.1 More than one of the same part + +Parts that use the shared on/off and analog jacks (D13, A1–A4) can be plugged in more than once, up to the five jacks: button, potentiometer, LED, relay, buzzer, pump, solenoid lock, servo, MQ-2, microphone, soil moisture, DHT11, IR obstacle, PIR, reed switch, LDR, flame and water level. Every other part stays one per board: it has a jack of its own (D5, ST, MD, 3D, UART), a fixed I2C address (OLED, heartbeat, MPU6050) or is built in (BLE, Cloud). + +- The second copy is called "Push Button 2" on the board, in the palette and in Board messages. The first copy shows as "Push Button 1" while there are two. +- Each copy has its own reading: `buttonState` and `buttonState2`, `temperature`/`humidity` and `temperature2`/`humidity2`. A second DHT11 also gets its own 2-second timer (`lastDhtMs2`). +- Each copy gets its own If option, Cloud reading and Edge AI input. A part block (turn LED on, set servo angle, ...) has a "Which part" dropdown to point it at the other copy. +- Copy numbers never change: unplugging Push Button 1 leaves Push Button 2 and its blocks as they were, and the next button plugged in takes number 1 again. +- With Cloud on, only D13 is left for on/off parts, so two copies are not possible then. + +--- + +## 2. Input devices (16) + +### 2.1 Controls (2) + +| Part | Jack | Reading (variable) | Range | Notes | +|------|------|--------------------|-------|-------| +| Push Button | D13, A1–A4 | Pressed or not (`buttonState`) | Yes / no | `INPUT_PULLUP`, pressed reads LOW | +| Potentiometer | A1–A4 | Knob position (`knobValue`) | 0–4095 | Average of 12 readings | + +### 2.2 Sensors (14) + +| Part | Jack | Reading (variable) | Range / unit | Notes | +|------|------|--------------------|--------------|-------| +| MQ-2 Gas Sensor | A1–A4 | Gas level (`gasLevel`) | 0–4095 (raw) | Average of 16 readings. Heater needs about a minute. Not ppm | +| Microphone | A1–A4 | Sound level (`soundLevel`) | 0–4095 (raw) | Average of 12 readings | +| Heartbeat HW-605 (MAX30102) | I2C | Heartbeat (`heartRate`) | bpm; 0 with no finger | I2C at 100 kHz | +| Capacitive Soil Moisture | A1–A4 | Soil moisture (`soilMoisture`) | 0–100 % | Raw ≈3200 in air = 0 %, ≈1200 in water = 100 % | +| DHT11 Temp & Humid | A1 (then A2, A3, D13) | Temperature (`temperature`), humidity (`humidity`) | °C, % | Read at most every 2 s; IO33 (D13) is unreliable for it | +| HC-SR04 Ultrasonic | D5 only | Distance (`distance`) | 2–400 cm; −1 = no echo | Echo stays an input; use the kit cable | +| IR Obstacle Sensor | D13, A1–A4 | Something in front (`obstacleNear`) | Yes / no | Active-low; screw sets the distance | +| PIR Motion Sensor | D13, A1–A4 | Movement (`motionSeen`) | Yes / no | Needs about a minute to settle after power-up | +| Reed Switch | D13, A1–A4 | Magnet near (`magnetNear`) | Yes / no | Active-low; for doors and windows | +| LDR Light Sensor | D13, A1–A4 | Dark or not (`isDark`) | Yes / no | Screw sets how dark | +| Flame Sensor | D13, A1–A4 | Flame seen (`flameSeen`) | Yes / no | Active-low | +| Water Level Sensor | A1–A4 | Water level (`waterLevel`) | 0–4095 (raw) | Only the striped part goes in water | +| MPU6050 Motion | I2C | Tilt (`tiltAngle`), shake (`shakeLevel`) | −90 to 90°; 0–100 (−1 = sensor missing) | Address 0x68 or 0x69, retried every 5 s. Edge AI learns moves from it | +| RFID RC522 | 3D only | Card ID (`rfidUid`) | Hex text | SPI; blocks D13 | + +Yes / no sensors are used as "If ... sees something" blocks; number sensors are compared with <, >, ≤, ≥, = or ≠. + +--- + +## 3. Output devices (13) + +### 3.1 Outputs (10) + +| Part | Jack | Blocks | Limits | Notes | +|------|------|--------|--------|-------| +| LED | D13, A1–A4 | On / off, brightness, blink | Brightness 0–255; blink 20–60000 ms | Brightness is PWM on the same pin | +| Relay Module | D13, A1–A4 | On / off | — | Switches a bigger gadget | +| Buzzer | D13, A1–A4 | Beep, on / off | Beep 20–10000 ms | Kept off while the board starts | +| Water Pump | D13, A1–A4 | On / off | — | Needs its own power adapter; kept off while the board starts | +| Solenoid Lock | D13, A1–A4 | Open / close | — | Needs its 12 V adapter; open a few seconds at a time; kept closed while the board starts | +| Servo Motor | D13, A1–A4 | Set angle | 0–180° | ESP32Servo, 500–2400 µs pulses | +| L293D Motor Driver | MD only | Set speed (motor A or B, forward or backward), stop | Speed 0–255 | Motor A = IO17/IO5, motor B = IO18/IO19 | +| 4-Ch Relay (MD) | MD only | Channel 1–4 on / off, all channels | 4 channels | Active-low; all channels set off at start | +| Stepper Motor | ST only | Move steps | −10000 to 10000 steps; 1–60 RPM | 200 steps per turn | +| OLED Screen | I2C | Show text, show number | 128 × 64 pixels | SSD1306 at address 0x3C | + +### 3.2 Two-way devices (3) + +| Part | Jack | Sends | Receives | Notes | +|------|------|-------|----------|-------| +| Bluetooth (BLE) | Built in | Turn on with a name, send text | — | Cannot be used with Cloud | +| HC-05 Bluetooth | UART only | Send a line of text | Read a line (`hc05Line`) | 9600 baud on the USB serial pins; unplug it if Upload fails | +| TinkerBit Cloud | Built in (WiFi) | Readings (automatic, at most every 5 s), alerts, "send now" | Up to 4 switches and 2 sliders from the phone dashboard | Turns A1–A4 off; cannot be used with BLE; 2.4 GHz WiFi only | + +--- + +## 4. Program blocks that need no part + +| Block | Limits | +|-------|--------| +| Wait | 0–3600 s | +| Repeat | 0–1000 times | +| If … then / otherwise | Compares any reading above, a Cloud switch or slider, or the Edge AI answer | +| Print text, print variable | To Board messages (USB serial, 9600 baud) | + +## 5. Edge AI (uses the parts above) + +| Kind | Learns from | Example | +|------|-------------|---------| +| Motion | MPU6050 (6 axes, 100 readings a second, 24 features per move) | Wave, circle, knock | +| Sensors | The number and yes / no sensors wired in (not button, RFID, heartbeat or HC-05) | Empty room, someone here | + +Limits: 2–4 things, 10–40 examples each, names up to 16 letters. The model runs on the board; no internet needed. + +## 6. Libraries the sketches use + +ESP32Servo (servo), SparkFun MAX3010x (heartbeat), Adafruit SSD1306 and GFX (OLED), MFRC522 (RFID), Stepper (stepper), ESP32 BLE (Bluetooth). The DHT11, ultrasonic and MPU6050 are read without extra libraries. diff --git a/docs/MICROPYTHON_MIGRATION_PLAN.md b/docs/MICROPYTHON_MIGRATION_PLAN.md new file mode 100644 index 00000000000..b9f3c93315f --- /dev/null +++ b/docs/MICROPYTHON_MIGRATION_PLAN.md @@ -0,0 +1,97 @@ +# Full MicroPython migration: plan + +Status: plan, started 2026-11-20. Advanced mode is locked (done, see Phase 0). The goal is a Beginner Studio where everything a student does runs on MicroPython: parts, Cloud (IoT) and Edge AI. No Arduino C++ is left in the student path, and the compile server can be switched off. + +"All platforms" here means every Beginner feature, on desktop Chrome or Edge on Windows, macOS, ChromeOS and Linux, with both kit USB chips (CH340 and CP210x). Phones stay out: Web Serial does not exist there. + +## Where we are + +| Area | State today | +|---|---| +| Parts and control blocks | MicroPython, all ported (library 0.2.0, firmware API 2) | +| Cloud (IoT) | MicroPython (`cloud.py` + `tbcloud` C module, settings in `/config.json`). Not yet proven on hardware: memory and 24 h stability (check 1), the real broker, the WSS fallback | +| Edge AI | **Arduino only**: the recorder and the AI program are C++ sketches, so in MicroPython mode the page says "Coming soon" and AI templates are greyed out | +| `?board=arduino` | Hidden teacher switch; keeps the whole C++ path alive (codegen, Cloud firmware, AI firmware, compile + flash) | +| Advanced IDE | **Locked** (Phase 0) | +| Compile server | Still running, still open (no sign-in, no rate limit, raw compiler logs). Used only by Edge AI and `?board=arduino` now that Advanced is locked | +| Hardware checks | Only safe mode and upload speed measured, on one CH340 board from a Python host. Checks 1, 2, 4, CP210x and the Chrome page runs are open | + +## Decisions (defaults I will follow unless you say otherwise) + +1. **Advanced lock:** `/ide` and the IDE example pages redirect to `/beginner`; the Choose page shows Advanced as paused; unlock with `ADVANCED_MODE=on` and a redeploy. *Done.* +2. **Remove Arduino from Beginner completely** once Phase 2 signs MicroPython off on hardware: no `?board=arduino`, no C++ generators, no compile path in the Studio. +3. **Edge AI examples recorded with the Arduino recorder are recorded again.** The signature gets a MicroPython marker, so the page asks for new examples instead of mixing in data from a different capture loop. Very few projects have Arduino recordings yet, so the cost is small. +4. **Edge AI ships as a library file first** (`/lib/tbai.py`, written at Upload like `boot.py`), so it needs no firmware rebuild. It is frozen into the next firmware (API 3) in Phase 4, which saves RAM. +5. **The compile server is switched off at the end** (Phase 5). You run or approve that step: it changes the EC2 host and `vercel.json`. +6. **Sound is not added as an AI kind.** The Arduino version did not have it either. + +## Phases + +### Phase 0: Lock Advanced (done) +- One switch `ADVANCED_MODE` ([advanced-mode.js](../src/lib/advanced-mode.js), [middleware.js](../middleware.js)). Locked unless it is `on`. +- `/ide`, `/ide.html`, `blocks-only.html`, `compatibility-testing.html`, `player.html` → 302 to `/beginner`, before the sign-in check. The IDE page also sends itself to Beginner (covers local dev). +- The Choose page shows Advanced as "Paused for now"; the Beginner menu hides "Switch mode". Tests: `advanced-mode.test.js`, `choose.test.jsx`, `account-menu.test.jsx`. + +### Phase 1: Edge AI on MicroPython (the main code work) +**Board side, new library module `tbai`** (`prototypes/micropython/lib/tinkerbit/tbai.py` or a top-level `tbai.py`): +- **Motion capture:** a direct port of `aiCaptureMotion` in [aiFirmware.js](../src/beginner-studio/domain/ai/aiFirmware.js). It reads `Motion._sample()` (already g and °/s, the same units as the Arduino driver) every 10 ms, keeps a 20-reading ring, starts a move when the jolt (`|g - 1| + spin/300`) passes 0.35, keeps 100 readings (200 ms before the start), and computes the 24 features (average, spread, lowest, highest of 6 axes). Buffers are `array('f')`, not lists, to avoid filling the heap with float objects. +- **Sensors capture:** 5 readings over about 1 s from the wired parts' existing read methods, averaged, in the fixed sorted order `aiKinds.js` uses. +- **Recorder:** prints the same `TBAI1` lines as the Arduino sketch (`H` hello every 2 s, `F` per example, `L` level, `E,no_sensor`). [aiLine.js](../src/beginner-studio/domain/ai/aiLine.js), [knn.js](../src/beginner-studio/domain/ai/knn.js) and the Edge AI page keep working unchanged. +- **Classifier:** the same steps as `aiClassify()`: standardise with the saved mean and scale, 3 nearest neighbours, most votes, ties to the nearest, Not sure (9) past the distance limit, Nothing (0) when no move came. The model is read once from `/ai_model.bin` (float32 means, scales and examples, loaded with `readinto` into `array('f')`, about 15 KB at most) plus a small `/ai_model.json` (names, k, limit, counts). + +**Studio side:** +- **Recorder upload:** "Put the recorder on the board" sends the recorder through the existing MicroPython upload (no compile). The Edge AI monitor listens at 115200 instead of 9600 in MicroPython mode. +- **Codegen:** [pycodegen.js](../src/beginner-studio/domain/pycodegen.js) emits `ai = tbai.Ai(...)`, one `ai.ask()` per loop pass and `if ai.answer == :` for "If the AI thinks it is …". An If about a removed thing becomes `if False:` and blocks Upload, as in C++. Remove `ai_ask` from `NOT_YET_BLOCKS`. +- **Upload:** writes `/ai_model.bin` and `/ai_model.json` when the program uses AI and removes them otherwise, like `/config.json`. The model no longer lives inside the program, so the code panel needs no "stand-in" and shows the real program. +- **Page:** [AiView.jsx](../src/beginner-studio/components/ai/AiView.jsx) shows the real page in MicroPython mode. The Magic Wand, Room Mood and Phone AI Alert templates open again. +- **Cloud:** one 0/1 reading per thing (`ai_`) through `cloud.set`, as in C++. +- **Signature:** add a MicroPython marker (decision 3). + +**Tests:** +- pytest: capture, features and classify against the board simulator; a recorder line test. +- A shared fixture of fixed vectors with the answers from `knn.js`, checked by both jest and pytest, so the browser and the board can never disagree. +- jest: Python codegen for the AI blocks, model file contents, the recorder upload path, the templates. + +### Phase 2: Prove it on hardware (needs you, with real boards) +I prepare the scripts and checklists; the runs need boards. +- [RESULTS.md](../prototypes/micropython/RESULTS.md) checks 1–5 through the Chrome page, on a CH340 board **and** a CP210x board. +- Check 1 against the real broker (`api.tinkerbit.io`) with a test device: memory after connecting, 24 h, the WSS fallback. Repeat with Phone AI Alert (Cloud + Edge AI together, the tightest memory case). +- Every template on a real board. Edge AI Motion and Sensors end to end: record, train, upload, recognise. +- The new parts (RFID, HC-05, BLE, heartbeat) on hardware. +- OS matrix: Windows, macOS, ChromeOS, Linux (driver install, Connect, Upload, Update board). +- Automated in the meantime: every template's `main.py` runs in the board simulator without errors and prints its ready lines (a CI test, no board needed). + +### Phase 3: Remove Arduino from Beginner (after Phase 2 signs off) +- Delete the `?board=arduino` switch ([boardLanguage.js](../src/beginner-studio/domain/boardLanguage.js)) and the C++ path: + - C++ generators: `codegen.js`, `cloudFirmware.js`, `cloudCerts.js`, the C++ half of `aiFirmware.js`, `motionSensor.js` and `cText.js` (where nothing else needs them); + - the compile-and-flash branch of `useBoardUpload.js` and `UploadContext.jsx`; + - the C++ colouring in `LiveCodePanel.jsx`. +- Rewrite the tests that assert C++ output to assert the Python output instead. Keep each behaviour, not each line. +- A board that still runs an Arduino program keeps getting "Choose Update board" (that path already exists). +- Update ARCHITECTURE.md: Beginner becomes MicroPython-only; section 4.5 then only describes the locked IDE. + +### Phase 4: Make it a product, not a prototype +- Move the library and firmware sources out of `prototypes/micropython/` (for example to `firmware/micropython/`), updating the imports in `libraryFiles.js`, `build.sh` and the tests. +- Freeze `tbai` into the firmware, bump to API 3, rebuild, and bundle the new `.bin` with its SHA-256. +- CI: build the firmware in Docker, run pytest and the Playwright page tests, and publish the `.bin` and its hash as a build artifact. +- Small fixes: + - drop "(MicroPython preview)" from the generated header; + - handle HC-05 modules set to 38400; + - fix the phone layout or show a "use a computer" screen. +- Optional: cache the Beginner page, library and firmware with a service worker, so a classroom can reload without internet. Sign-in still needs the internet once. + +### Phase 5: Switch off the compile server (needs your go-ahead) +With Advanced locked and no C++ left in Beginner, nothing calls `/api/compile`: +- stop the `compile-api` service on EC2 and remove its nginx location; +- remove the `/api/compile`, `/devices/*` and `/extensions/*` rewrites from `vercel.json`. + +This also closes all three security findings: the open compile endpoint, the plain-HTTP IDE scripts and the raw compiler logs. If Advanced comes back later, the compile plan's Phase 0 fixes ([COMPILE_BACKEND_PLAN.md](COMPILE_BACKEND_PLAN.md)) must land before it reopens. + +## Risks +| Risk | What we do | +|---|---| +| Cloud + Edge AI do not fit in memory on a board without PSRAM | Model as `array('f')` from a binary file (about 15 KB); measure in Phase 2; freeze `tbai` in Phase 4; cap examples at 40 per thing | +| MicroPython timing makes motion features differ from what was recorded | Recording and recognising both run the same Python capture, and old Arduino recordings are re-recorded (decision 3) | +| kNN too slow in Python | Up to 160 × 24 multiply-adds per answer, a few tens of ms; `@micropython.native` if needed | +| A hardware check fails after the switch | Phase 3 (removing Arduino) waits for Phase 2; until then `?board=arduino` stays as the escape hatch | +| Removing C++ loses tested behaviour | Tests are rewritten per behaviour before the C++ code is deleted | diff --git a/docs/prompts/cursor-micropython-prototype.md b/docs/prompts/cursor-micropython-prototype.md new file mode 100644 index 00000000000..d6f0118866a --- /dev/null +++ b/docs/prompts/cursor-micropython-prototype.md @@ -0,0 +1,135 @@ +# Cursor prompt: TinkerBit MicroPython prototype on the Maker ESP32 + +Paste everything below the line into Cursor (Agent mode) at the root of the `blockcode-gui` repo. + +--- + +## Role and goal +You are working in the TinkerBit repo (`blockcode-gui`). TinkerBit is a browser studio for the **Maker ESP32 RJ11 kit**. Today Beginner Studio generates Arduino C++ and compiles it on a server (`services/compile-api`), then flashes it over Web Serial. + +We are **evaluating** a MicroPython path for Beginner Studio: no compile server, uploads in about a second, and it works offline. Your job is a **prototype that proves or disproves five risks on real hardware**. It is not a product rewrite. + +**Do not change** Beginner Studio (`src/beginner-studio/`), the Advanced IDE, `services/`, `vercel.json` or the existing tests. All new work goes in `prototypes/micropython/`. Read `ARCHITECTURE.md` first. It is the source of truth for the kit, jacks and rules. + +## The hardware is fixed (do not propose board changes) +- MCU: **classic ESP32, WROOM-32, assume no PSRAM**, 4 MB flash. +- USB-serial: **CP210x (10c4:ea60) or CH340/CH9102 (1a86)**, with the standard DTR/RTS auto-reset circuit. CP210x corrupts data above **115200**, so stay at 115200. +- Jacks: these GPIO numbers may appear **only in `board.py`**. + +| Jack | GPIO | Notes | +|---|---|---| +| ST | 12, 13, 14, 27 | Stepper. GPIO 12 is a strapping pin (flash voltage): never pull it HIGH at boot | +| D13 | 33 | Digital. Conflicts with 3D (shared GPIO 33) | +| 3D | SS 32, RST 33, MISO 34; SCK 16, MOSI 23 | RFID RC522 only | +| D5 | Trig 26, Echo 25 | HC-SR04 only. Echo is always INPUT | +| MD | 17, 5, 18, 19 | L293D or 4-ch relay (active-low: drive HIGH at boot) | +| I2C, I2C1 | SDA 21, SCL 22 | Shared bus at **100 kHz** (OLED 0x3C, MAX30102 0x57, MPU6050 0x68/0x69) | +| A1 | 4 | ADC2 | +| A2 | 15 | ADC2, strapping | +| A3 | 2 | ADC2, strapping | +| A4 | 0 | ADC2, **BOOT pin**: never hold LOW at reset | +| UART | RX 3, TX 1 | HC-05. **Same UART0 as USB serial and the REPL** | +| ESP | — | Onboard BLE / WiFi | + +- **ADC2 (all A jacks) stops working while WiFi is on.** Cloud locks A1–A4. Cloud and BLE never run together. +- The ADC1-only and S3/C3 pin rules from generic guides **do not apply**. We can't move pins. + +## Architecture to prototype +- **Browser:** one HTML file, no framework, libraries pinned to exact versions (esptool-js is fine). It handles the Web Serial transport and the MicroPython raw REPL. +- **Board:** MicroPython plus a `tinkerbit` library. `board.py` is the only file that knows GPIO numbers. +- **Two modes:** Upload (write `main.py`, then soft reset) and Live (one-line commands). +- **Two firmware stages:** + 1. **Stage A, stock MicroPython** (latest stable ESP32_GENERIC) with the library copied to `/lib`. Use it for checks 3, 4 and 5. + 2. **Stage B, custom firmware:** the library frozen in through a manifest, plus a C module for fast ADC sampling and serial safe mode in frozen `_boot.py`. Use it for checks 1 and 2. Build it in Docker (`espressif/idf` image, pinned tag) with a script, `prototypes/micropython/firmware/build.sh`. + +## Library (`prototypes/micropython/lib/tinkerbit/`) +- `__init__.py` (public API) and `board.py` (jack → GPIO, ADC2 flag, strapping flag, conflicts). +- `info()` prints exactly one line: `TB_INFO {json}`. The JSON holds board, rev, mcu, lib `VERSION`, `API`, jack count, unique id (`machine.unique_id` hex), MicroPython version, free flash, free heap, reset cause. +- `begin()` is safe to call twice. +- `stop_all()` turns off motors, the buzzer, LEDs and pumps, drives the MD relays HIGH (off), and stops PWM. +- **One cached object per jack**, so `Led('D13')` returns the same instance each time (code inside loops would otherwise leak PWM channels). +- Track which part owns each jack. Raise friendly errors: D13 + 3D together, a digital part on D5, an A jack while WiFi is on ("A ports are off while Cloud/WiFi is on"). +- Return friendly units: analog 0–4095 averaged over 12 samples, distance in cm (−1 when invalid), soil 0–100 %. +- Minimum parts for the prototype: LED (on/off/brightness), button, pot (A1), HC-SR04 (D5), DHT11 (built-in `dht`, on A1), OLED text (`ssd1306`), MPU6050 raw `Wire` reads (tilt and shake), HC-05 send/read. +- No bare `except:`. Use `except Exception`. +- Default `main.py`: a short LED blink, `info()`, then exit within 1 s. + +## Serial transport (in the test page) +- `requestPort` filtered to the two USB vendor ids, 115200 baud. Use `getPorts()` + the `connect` event to reconnect after a reset without a second picker. +- **Board reset control:** reuse the DTR/RTS sequences in `src/lib/web-serial/web-serial-port.js` and `esptool-flash.js` (read them; copy, don't import). + - Opening the port must **not** reset the board when that can be avoided. Measure and record whether it does on each USB chip. + - Hard reset = an EN pulse through RTS. +- Raw REPL: + - Ctrl-C ×3 (with a timeout) → Ctrl-A → wait for `raw REPL; CTRL-B to exit` → send → Ctrl-D → parse `OK…\x04…\x04>`. + - Prefer raw-paste mode (Ctrl-E, flow-controlled); fall back to 256-byte chunks with delays. +- Safe file writes: create the folders → `.tmp` → write hex chunks with `bytes.fromhex` → remove the old file → rename. Clean up `.tmp` files on connect. +- **Stop:** Ctrl-C; if that fails within 1 s, hard reset through RTS. +- **Serial safe mode (instead of the BOOT button, because A4 = GPIO 0 may have a part on it):** + - Frozen `_boot.py` in Stage B (`boot.py` in Stage A) listens for `TB_SAFE\n` for 300 ms after reset. If it arrives, it skips `main.py` and prints `TB_SAFE_OK`. + - The page's "Recover" button does: hard reset → send `TB_SAFE` repeatedly for 500 ms → wait for `TB_SAFE_OK`. +- Errors: show the last traceback line plus a hint. The "port busy" message names Arduino IDE, Thonny, PuTTY and other TinkerBit tabs. Next to Connect, show "No board listed? Try a data cable". With no Web Serial, show "Use desktop Chrome or Edge". +- **HC-05 mode** (both share UART0): + - The page shows "Unplug HC-05 before Connect or Upload". + - Programs that use HC-05 are **Upload-only**. They call `micropython.kbd_intr(-1)` and switch UART0 to 9600. + - The page monitor switches to 9600 for them. + - Stop = hard reset, then serial safe mode, then back to 115200. +- Firmware install / recovery with esptool-js at 115200 (reuse the four reset strategies from `esptool-flash.js`). If `TB_INFO` never arrives, offer "Install TinkerBit firmware". + +## Cloud check (Stage B only) +- Build a minimal C module around ESP-IDF **esp-mqtt** (TLS with the ISRG Root X1 and X2 roots, a WSS fallback on 443) with the Python API `cloud.begin(ssid, pw, host, device_id, key)`, `cloud.send(dict)`, `cloud.connected()`. Port the reconnect logic from `src/beginner-studio/domain/cloudFirmware.js` (WiFi restart after 3 min, fresh MQTT after 2 min stuck). +- **Credentials:** read from `/config.json` on the board; never put them in `main.py` or in logs. +- Point it at a **test broker** (`test.mosquitto.org:8883`, or a local Mosquitto with TLS), not production `api.tinkerbit.io`, unless I give you a test device. + +## The five checks (the deliverable) +Record each result in `prototypes/micropython/RESULTS.md` as **pass/fail with numbers**, saying which board (CP210x or CH340) and which firmware stage. + +1. **Memory with Cloud on a WROOM without PSRAM (Stage B):** + - Free heap (`gc.mem_free()` + `esp.idf_heap_info`) after boot, after WiFi connects, and after the TLS MQTT connection. + - The connection stays up for 24 h with one send every 5 s, counting reconnects. Pass = at least 30 KB free after connecting and 0 crashes. +2. **Mic sampling rate on GPIO 4 / ADC2 (Stage B C module):** + - The sustained rate for a 0.5 s capture into an `array('h')`, WiFi off. + - Pass = at least 8 kHz with jitter under 10%. Also record the rate from pure Python for comparison. +3. **Connecting without a reset, and serial safe mode, on both USB chips:** + - Does opening the port reset the board? Does safe mode recover a `main.py` running `while True: pass` 10 times out of 10? +4. **HC-05 upload-only mode:** + - A program sends and reads lines at 9600 through HC-05. Stop recovers 10 times out of 10, and the page returns to 115200. +5. **Upload speed:** times for a 3 KB `main.py` and a 25 KB file (raw-paste vs chunked). Pass = 3 KB in under 1.5 s and 25 KB in under 5 s. + +## Testing (required) +- **Simulated board** (`prototypes/micropython/sim/board_sim.py`): CPython speaking the raw REPL protocol. + - It supports Ctrl-A/B/C/D, raw-paste with flow control, and `OK`/`\x04` framing. + - Soft reboot runs `boot.py` then `main.py`. It honours `TB_SAFE`. + - It uses a temp folder as flash and mocks `machine` (Pin, PWM, ADC with an ADC2-locked-by-WiFi flag, I2C, UART, `unique_id`, `reset_cause`), `dht`, `network` and `neopixel`. + - Ctrl-C interrupts a running loop. +- **Playwright** (headless Chrome) drives the test page with a mocked `navigator.serial` wired to the simulator through a WebSocket bridge. Cover: + - probe with the library missing → install → `TB_INFO` OK; + - Run streams output; + - Upload writes `main.py`, and it runs after reset; + - Stop breaks an infinite loop; + - safe mode recovers a stuck `main.py`; + - jack-conflict and ADC2+WiFi errors show friendly text; + - Live commands; + - no `.tmp` files left; + - no console errors. +- Use `npx playwright` from inside `prototypes/micropython/` with its own `package.json`. Don't add dependencies to the root `package.json`. +- Then I run the hardware checks. Write a step-by-step checklist in `RESULTS.md` for me, and **report clearly what you verified in simulation and what still needs real hardware.** + +## Build order +1. `board.py` + library + simulator + unit tests in CPython (pytest). +2. Single-file test page `prototypes/micropython/index.html`: Connect, Install library, Run, Upload, Stop, Recover, console, Live input. +3. Playwright suite against the simulator. +4. Stage B firmware build script + C ADC sampler + frozen library + `_boot.py`. +5. The esp-mqtt Cloud module. +6. `RESULTS.md` with the hardware checklist and empty result tables. + +## Don'ts +- No edits outside `prototypes/micropython/` (except adding that path to `.eslintignore` if lint complains). +- No GPIO numbers outside `board.py`. +- No hardware watchdog, eFuse locking, Secure Boot or flash encryption. +- No real WiFi passwords, device keys or production endpoints in code or commits. +- No frameworks in the test page, and no unpinned CDN versions. +- No commits until I review. Show me the diff summary at the end. + +## Deliverables +- `prototypes/micropython/` containing: `lib/tinkerbit/`, `boot.py`, `main.py`, `firmware/` (Docker build script, manifest, C modules), `sim/`, `index.html`, Playwright tests, pytest tests, `README.md` (flashing, installing the library, safe mode, recovery) and `RESULTS.md`. +- A final message listing: the test results (simulation), what is still unverified on hardware, and any risk you think already fails on paper. diff --git a/lib/auth/session.mjs b/lib/auth/session.mjs new file mode 100644 index 00000000000..9ffa73f1a05 --- /dev/null +++ b/lib/auth/session.mjs @@ -0,0 +1,185 @@ +import {SignJWT, jwtVerify} from 'jose'; + +export const SESSION_COOKIE = 'tb_session'; +export const OAUTH_STATE_COOKIE = 'tb_oauth_state'; +export const SESSION_MAX_AGE_SEC = 60 * 60 * 24 * 7; // 7 days +export const STATE_MAX_AGE_SEC = 60 * 10; // 10 minutes + +const textEncoder = new TextEncoder(); + +export function getAuthBaseUrl (req) { + if (process.env.AUTH_BASE_URL) { + return process.env.AUTH_BASE_URL.replace(/\/$/, ''); + } + if (req && req.headers) { + const host = req.headers['x-forwarded-host'] || req.headers.host; + const proto = req.headers['x-forwarded-proto'] || 'https'; + if (host) { + return `${proto}://${host}`; + } + } + return 'http://127.0.0.1:8601'; +} + +export function isAuthDisabled () { + if (process.env.AUTH_DISABLED !== '1' && process.env.AUTH_DISABLED !== 'true') { + return false; + } + // Never allow disable on Vercel production + return process.env.VERCEL_ENV !== 'production'; +} + +export function getSecretKey () { + const secret = process.env.AUTH_SECRET; + if (!secret || String(secret).length < 32) { + return null; + } + return textEncoder.encode(String(secret)); +} + +export function parseCookies (cookieHeader) { + const out = {}; + if (!cookieHeader || typeof cookieHeader !== 'string') { + return out; + } + cookieHeader.split(';').forEach(part => { + const idx = part.indexOf('='); + if (idx === -1) return; + const key = part.slice(0, idx).trim(); + const value = part.slice(idx + 1).trim(); + if (key) { + out[key] = decodeURIComponent(value); + } + }); + return out; +} + +export function cookieOptions ({maxAge, httpOnly = true} = {}) { + const secure = process.env.NODE_ENV === 'production' || + process.env.VERCEL_ENV === 'production' || + (process.env.AUTH_BASE_URL || '').startsWith('https://'); + const parts = [ + 'Path=/', + 'SameSite=Lax' + ]; + if (httpOnly) { + parts.push('HttpOnly'); + } + if (secure) { + parts.push('Secure'); + } + if (typeof maxAge === 'number') { + parts.push(`Max-Age=${maxAge}`); + } + return parts.join('; '); +} + +export function serializeCookie (name, value, options) { + return `${name}=${encodeURIComponent(value)}; ${cookieOptions(options)}`; +} + +export function clearCookie (name) { + return `${name}=; ${cookieOptions({maxAge: 0, httpOnly: true})}`; +} + +/** + * Allow only same-app relative paths under /choose, /beginner, or /ide (open-redirect safe). + * @param {string} next + * @returns {string} + */ +export function sanitizeNextPath (next) { + if (!next || typeof next !== 'string') { + return '/choose'; + } + let value = next.trim(); + try { + value = decodeURIComponent(value); + } catch (err) { + return '/choose'; + } + if (!value.startsWith('/') || value.startsWith('//') || value.includes('\\')) { + return '/choose'; + } + if (value.includes('://')) { + return '/choose'; + } + const pathOnly = value.split('?')[0].split('#')[0]; + const allowed = + pathOnly === '/choose' || pathOnly === '/choose/' || + pathOnly === '/beginner' || pathOnly === '/beginner/' || + pathOnly === '/beginner.html' || pathOnly === '/choose.html' || + pathOnly === '/ide' || pathOnly.startsWith('/ide/') || pathOnly === '/ide.html' || + pathOnly === '/iot' || pathOnly.startsWith('/iot/') || pathOnly === '/iot.html'; + if (!allowed) { + return '/choose'; + } + return value; +} + +export async function createSessionToken (user) { + const key = getSecretKey(); + if (!key) { + throw new Error('AUTH_SECRET is not configured'); + } + return new SignJWT({ + email: user.email || '', + name: user.name || '', + picture: user.picture || '' + }) + .setProtectedHeader({alg: 'HS256'}) + .setSubject(String(user.sub)) + .setIssuedAt() + .setExpirationTime(`${SESSION_MAX_AGE_SEC}s`) + .sign(key); +} + +export async function verifySessionToken (token) { + const key = getSecretKey(); + if (!key || !token) { + return null; + } + try { + const {payload} = await jwtVerify(token, key, { + algorithms: ['HS256'] + }); + if (!payload || !payload.sub) { + return null; + } + return { + sub: String(payload.sub), + email: payload.email ? String(payload.email) : '', + name: payload.name ? String(payload.name) : '', + picture: payload.picture ? String(payload.picture) : '' + }; + } catch (err) { + return null; + } +} + +export async function readSessionFromRequest (req) { + if (isAuthDisabled()) { + return { + sub: 'dev', + email: 'dev@localhost', + name: 'Dev', + picture: '' + }; + } + const cookies = parseCookies(req.headers.cookie || req.headers.get?.('cookie')); + return verifySessionToken(cookies[SESSION_COOKIE]); +} + +export function logAuthEvent (event, detail = {}) { + const safe = { + event, + ts: new Date().toISOString(), + ...detail + }; + // Never log tokens or secrets + delete safe.token; + delete safe.code; + delete safe.access_token; + delete safe.id_token; + // eslint-disable-next-line no-console + console.log(JSON.stringify(safe)); +} diff --git a/lib/waitlist/store.mjs b/lib/waitlist/store.mjs new file mode 100644 index 00000000000..c6009ffff39 --- /dev/null +++ b/lib/waitlist/store.mjs @@ -0,0 +1,81 @@ +/** + * Waitlist storage on Upstash Redis (REST API, no SDK). + * Emails live in one sorted set: member = lowercased email, score = first signup time (ms). + */ +export const WAITLIST_KEY = 'waitlist:emails'; + +const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/; + +export function normalizeEmail (value) { + const email = String(value || '').trim() + .toLowerCase(); + if (!email || email.length > 254 || !EMAIL_RE.test(email)) { + return null; + } + return email; +} + +/** Vercel's Upstash integration sets KV_REST_API_*; a direct Upstash setup uses UPSTASH_REDIS_REST_*. */ +export function getRedisConfig () { + const url = process.env.KV_REST_API_URL || process.env.UPSTASH_REDIS_REST_URL; + const token = process.env.KV_REST_API_TOKEN || process.env.UPSTASH_REDIS_REST_TOKEN; + if (!url || !token) { + return null; + } + return {url: url.replace(/\/$/, ''), token}; +} + +export async function redisPipeline (config, commands) { + const res = await fetch(`${config.url}/pipeline`, { + method: 'POST', + headers: { + 'Authorization': `Bearer ${config.token}`, + 'Content-Type': 'application/json' + }, + body: JSON.stringify(commands) + }); + if (!res.ok) { + throw new Error(`redis_http_${res.status}`); + } + const results = await res.json(); + return results.map(item => { + if (item && item.error) { + throw new Error(`redis_error_${item.error}`); + } + return item ? item.result : null; + }); +} + +export async function readJsonBody (req) { + if (req.body && typeof req.body === 'object') { + return req.body; + } + if (typeof req.body === 'string') { + try { + return JSON.parse(req.body); + } catch (err) { + return {}; + } + } + const chunks = []; + let size = 0; + for await (const chunk of req) { + size += chunk.length; + if (size > 10 * 1024) { + return {}; + } + chunks.push(chunk); + } + try { + return JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}'); + } catch (err) { + return {}; + } +} + +export function sendJson (res, status, payload) { + res.statusCode = status; + res.setHeader('Content-Type', 'application/json'); + res.setHeader('Cache-Control', 'no-store'); + res.end(JSON.stringify(payload)); +} diff --git a/middleware.js b/middleware.js new file mode 100644 index 00000000000..e984fb92bf0 --- /dev/null +++ b/middleware.js @@ -0,0 +1,81 @@ +/* global Response */ +import { + SESSION_COOKIE, + isAuthDisabled, + parseCookies, + sanitizeNextPath, + verifySessionToken +} from './lib/auth/session.mjs'; + +// The OpenBlock IDE and its example pages. Locked while TinkerBit focuses on Beginner Studio: +// set ADVANCED_MODE=on (and redeploy) to open them again. src/lib/advanced-mode.js holds the +// same switch for the pages themselves. +const ADVANCED_PATHS = [ + '/ide', + '/ide/', + '/ide.html', + '/blocks-only.html', + '/compatibility-testing.html', + '/player.html' +]; + +const advancedModeOn = () => String(process.env.ADVANCED_MODE || '') + .trim() + .toLowerCase() === 'on'; + +export const config = { + matcher: [ + '/ide', + '/ide/', + '/ide.html', + '/blocks-only.html', + '/compatibility-testing.html', + '/player.html', + '/choose', + '/choose/', + '/choose.html', + '/beginner', + '/beginner/', + '/beginner.html', + '/iot', + '/iot/:path*', + '/iot.html' + ] +}; + +export default async function middleware (request) { + const {pathname} = new URL(request.url); + if (ADVANCED_PATHS.includes(pathname)) { + if (!advancedModeOn()) { + // 302, not 301: browsers must not remember this once Advanced comes back. + return Response.redirect(new URL('/beginner', request.url), 302); + } + // The IDE example pages were never behind sign-in; only /ide itself is. + if (!pathname.startsWith('/ide')) { + return; + } + } + + if (isAuthDisabled()) { + return; + } + + // If auth is not configured yet, send users to login (fail closed) + if (!process.env.AUTH_SECRET || !process.env.GOOGLE_CLIENT_ID) { + const url = new URL('/login', request.url); + url.searchParams.set('error', 'config'); + return Response.redirect(url, 302); + } + + const cookies = parseCookies(request.headers.get('cookie') || ''); + const user = await verifySessionToken(cookies[SESSION_COOKIE]); + if (user) { + return; + } + + const requestUrl = new URL(request.url); + const nextPath = sanitizeNextPath(`${requestUrl.pathname}${requestUrl.search}`); + const loginUrl = new URL('/login', request.url); + loginUrl.searchParams.set('next', nextPath); + return Response.redirect(loginUrl, 302); +} diff --git a/module-test/.gitignore b/module-test/.gitignore new file mode 100644 index 00000000000..9805b47d599 --- /dev/null +++ b/module-test/.gitignore @@ -0,0 +1,2 @@ +tools/.out/ +.vercel/ diff --git a/module-test/.vercelignore b/module-test/.vercelignore new file mode 100644 index 00000000000..83676361a1e --- /dev/null +++ b/module-test/.vercelignore @@ -0,0 +1,4 @@ +tools/ +serve.js +start-server.bat +.gitignore diff --git a/module-test/Claude outputs/module-icons.zip b/module-test/Claude outputs/module-icons.zip new file mode 100644 index 00000000000..88557842caf Binary files /dev/null and b/module-test/Claude outputs/module-icons.zip differ diff --git a/module-test/assets/svg/board-top.svg b/module-test/assets/svg/board-top.svg new file mode 100644 index 00000000000..29e0727f360 --- /dev/null +++ b/module-test/assets/svg/board-top.svg @@ -0,0 +1 @@ +5VGND3.3VU1U4PWRRSTBOOTUSB \ No newline at end of file diff --git a/module-test/assets/svg/card-ble-dark.svg b/module-test/assets/svg/card-ble-dark.svg new file mode 100644 index 00000000000..20cf6d12b8f --- /dev/null +++ b/module-test/assets/svg/card-ble-dark.svg @@ -0,0 +1 @@ +Bluetooth (BLE) \ No newline at end of file diff --git a/module-test/assets/svg/card-ble-light.svg b/module-test/assets/svg/card-ble-light.svg new file mode 100644 index 00000000000..9119a55d70f --- /dev/null +++ b/module-test/assets/svg/card-ble-light.svg @@ -0,0 +1 @@ +Bluetooth (BLE) \ No newline at end of file diff --git a/module-test/assets/svg/card-hc05-dark.svg b/module-test/assets/svg/card-hc05-dark.svg new file mode 100644 index 00000000000..4b15175a95e --- /dev/null +++ b/module-test/assets/svg/card-hc05-dark.svg @@ -0,0 +1 @@ +HC-05 Bluetooth \ No newline at end of file diff --git a/module-test/assets/svg/card-hc05-light.svg b/module-test/assets/svg/card-hc05-light.svg new file mode 100644 index 00000000000..653e631b818 --- /dev/null +++ b/module-test/assets/svg/card-hc05-light.svg @@ -0,0 +1 @@ +HC-05 Bluetooth \ No newline at end of file diff --git a/module-test/assets/svg/card-l293d-dark.svg b/module-test/assets/svg/card-l293d-dark.svg new file mode 100644 index 00000000000..03becd5177d --- /dev/null +++ b/module-test/assets/svg/card-l293d-dark.svg @@ -0,0 +1 @@ +L293D Motor Driver \ No newline at end of file diff --git a/module-test/assets/svg/card-l293d-light.svg b/module-test/assets/svg/card-l293d-light.svg new file mode 100644 index 00000000000..492f42af245 --- /dev/null +++ b/module-test/assets/svg/card-l293d-light.svg @@ -0,0 +1 @@ +L293D Motor Driver \ No newline at end of file diff --git a/module-test/assets/svg/card-oled-dark.svg b/module-test/assets/svg/card-oled-dark.svg new file mode 100644 index 00000000000..cb668ac3332 --- /dev/null +++ b/module-test/assets/svg/card-oled-dark.svg @@ -0,0 +1 @@ +OLED Screen \ No newline at end of file diff --git a/module-test/assets/svg/card-oled-light.svg b/module-test/assets/svg/card-oled-light.svg new file mode 100644 index 00000000000..94a3baa0ab9 --- /dev/null +++ b/module-test/assets/svg/card-oled-light.svg @@ -0,0 +1 @@ +OLED Screen \ No newline at end of file diff --git a/module-test/assets/svg/card-relay-dark.svg b/module-test/assets/svg/card-relay-dark.svg new file mode 100644 index 00000000000..a4d238d6969 --- /dev/null +++ b/module-test/assets/svg/card-relay-dark.svg @@ -0,0 +1 @@ +Relay Module \ No newline at end of file diff --git a/module-test/assets/svg/card-relay-light.svg b/module-test/assets/svg/card-relay-light.svg new file mode 100644 index 00000000000..0dbc7ac2ff2 --- /dev/null +++ b/module-test/assets/svg/card-relay-light.svg @@ -0,0 +1 @@ +Relay Module \ No newline at end of file diff --git a/module-test/assets/svg/card-relay4-dark.svg b/module-test/assets/svg/card-relay4-dark.svg new file mode 100644 index 00000000000..f74654e3516 --- /dev/null +++ b/module-test/assets/svg/card-relay4-dark.svg @@ -0,0 +1 @@ +4-Ch Relay (MD) \ No newline at end of file diff --git a/module-test/assets/svg/card-relay4-light.svg b/module-test/assets/svg/card-relay4-light.svg new file mode 100644 index 00000000000..892c26b0127 --- /dev/null +++ b/module-test/assets/svg/card-relay4-light.svg @@ -0,0 +1 @@ +4-Ch Relay (MD) \ No newline at end of file diff --git a/module-test/assets/svg/card-servo-dark.svg b/module-test/assets/svg/card-servo-dark.svg new file mode 100644 index 00000000000..88dff22ed02 --- /dev/null +++ b/module-test/assets/svg/card-servo-dark.svg @@ -0,0 +1 @@ +Servo Motor \ No newline at end of file diff --git a/module-test/assets/svg/card-servo-light.svg b/module-test/assets/svg/card-servo-light.svg new file mode 100644 index 00000000000..4a002c03694 --- /dev/null +++ b/module-test/assets/svg/card-servo-light.svg @@ -0,0 +1 @@ +Servo Motor \ No newline at end of file diff --git a/module-test/assets/svg/card-stepper-dark.svg b/module-test/assets/svg/card-stepper-dark.svg new file mode 100644 index 00000000000..37ca8986855 --- /dev/null +++ b/module-test/assets/svg/card-stepper-dark.svg @@ -0,0 +1 @@ +Stepper Motor \ No newline at end of file diff --git a/module-test/assets/svg/card-stepper-light.svg b/module-test/assets/svg/card-stepper-light.svg new file mode 100644 index 00000000000..7e8ee33f41c --- /dev/null +++ b/module-test/assets/svg/card-stepper-light.svg @@ -0,0 +1 @@ +Stepper Motor \ No newline at end of file diff --git a/module-test/assets/svg/esp-can.svg b/module-test/assets/svg/esp-can.svg new file mode 100644 index 00000000000..b67ba14d228 --- /dev/null +++ b/module-test/assets/svg/esp-can.svg @@ -0,0 +1 @@ +ESP32 \ No newline at end of file diff --git a/module-test/assets/svg/esp-top.svg b/module-test/assets/svg/esp-top.svg new file mode 100644 index 00000000000..5b82dd9e4b5 --- /dev/null +++ b/module-test/assets/svg/esp-top.svg @@ -0,0 +1,2 @@ + \ No newline at end of file diff --git a/module-test/assets/svg/label-3D-dark.svg b/module-test/assets/svg/label-3D-dark.svg new file mode 100644 index 00000000000..f1e54ba162f --- /dev/null +++ b/module-test/assets/svg/label-3D-dark.svg @@ -0,0 +1 @@ +3D \ No newline at end of file diff --git a/module-test/assets/svg/label-3D-light.svg b/module-test/assets/svg/label-3D-light.svg new file mode 100644 index 00000000000..e54c14a2233 --- /dev/null +++ b/module-test/assets/svg/label-3D-light.svg @@ -0,0 +1 @@ +3D \ No newline at end of file diff --git a/module-test/assets/svg/label-A1-dark.svg b/module-test/assets/svg/label-A1-dark.svg new file mode 100644 index 00000000000..8e8797fb44f --- /dev/null +++ b/module-test/assets/svg/label-A1-dark.svg @@ -0,0 +1 @@ +A1 \ No newline at end of file diff --git a/module-test/assets/svg/label-A1-light.svg b/module-test/assets/svg/label-A1-light.svg new file mode 100644 index 00000000000..a6d94ee6a35 --- /dev/null +++ b/module-test/assets/svg/label-A1-light.svg @@ -0,0 +1 @@ +A1 \ No newline at end of file diff --git a/module-test/assets/svg/label-A2-dark.svg b/module-test/assets/svg/label-A2-dark.svg new file mode 100644 index 00000000000..6844d153c81 --- /dev/null +++ b/module-test/assets/svg/label-A2-dark.svg @@ -0,0 +1 @@ +A2 \ No newline at end of file diff --git a/module-test/assets/svg/label-A2-light.svg b/module-test/assets/svg/label-A2-light.svg new file mode 100644 index 00000000000..ae4640c748c --- /dev/null +++ b/module-test/assets/svg/label-A2-light.svg @@ -0,0 +1 @@ +A2 \ No newline at end of file diff --git a/module-test/assets/svg/label-A3-dark.svg b/module-test/assets/svg/label-A3-dark.svg new file mode 100644 index 00000000000..1bc32377c0b --- /dev/null +++ b/module-test/assets/svg/label-A3-dark.svg @@ -0,0 +1 @@ +A3 \ No newline at end of file diff --git a/module-test/assets/svg/label-A3-light.svg b/module-test/assets/svg/label-A3-light.svg new file mode 100644 index 00000000000..4c48bcbc005 --- /dev/null +++ b/module-test/assets/svg/label-A3-light.svg @@ -0,0 +1 @@ +A3 \ No newline at end of file diff --git a/module-test/assets/svg/label-A4-dark.svg b/module-test/assets/svg/label-A4-dark.svg new file mode 100644 index 00000000000..079388b0546 --- /dev/null +++ b/module-test/assets/svg/label-A4-dark.svg @@ -0,0 +1 @@ +A4 \ No newline at end of file diff --git a/module-test/assets/svg/label-A4-light.svg b/module-test/assets/svg/label-A4-light.svg new file mode 100644 index 00000000000..60239323232 --- /dev/null +++ b/module-test/assets/svg/label-A4-light.svg @@ -0,0 +1 @@ +A4 \ No newline at end of file diff --git a/module-test/assets/svg/label-D13-dark.svg b/module-test/assets/svg/label-D13-dark.svg new file mode 100644 index 00000000000..c75dbf6d9ee --- /dev/null +++ b/module-test/assets/svg/label-D13-dark.svg @@ -0,0 +1 @@ +D13 \ No newline at end of file diff --git a/module-test/assets/svg/label-D13-light.svg b/module-test/assets/svg/label-D13-light.svg new file mode 100644 index 00000000000..c79e21e9961 --- /dev/null +++ b/module-test/assets/svg/label-D13-light.svg @@ -0,0 +1 @@ +D13 \ No newline at end of file diff --git a/module-test/assets/svg/label-D5-dark.svg b/module-test/assets/svg/label-D5-dark.svg new file mode 100644 index 00000000000..78499fbfb3c --- /dev/null +++ b/module-test/assets/svg/label-D5-dark.svg @@ -0,0 +1 @@ +D5 \ No newline at end of file diff --git a/module-test/assets/svg/label-D5-light.svg b/module-test/assets/svg/label-D5-light.svg new file mode 100644 index 00000000000..825cd06fb25 --- /dev/null +++ b/module-test/assets/svg/label-D5-light.svg @@ -0,0 +1 @@ +D5 \ No newline at end of file diff --git a/module-test/assets/svg/label-I2C-dark.svg b/module-test/assets/svg/label-I2C-dark.svg new file mode 100644 index 00000000000..83b582c7bb2 --- /dev/null +++ b/module-test/assets/svg/label-I2C-dark.svg @@ -0,0 +1 @@ +I2C \ No newline at end of file diff --git a/module-test/assets/svg/label-I2C-light.svg b/module-test/assets/svg/label-I2C-light.svg new file mode 100644 index 00000000000..6fd3578bb79 --- /dev/null +++ b/module-test/assets/svg/label-I2C-light.svg @@ -0,0 +1 @@ +I2C \ No newline at end of file diff --git a/module-test/assets/svg/label-MD-dark.svg b/module-test/assets/svg/label-MD-dark.svg new file mode 100644 index 00000000000..6871a72ddab --- /dev/null +++ b/module-test/assets/svg/label-MD-dark.svg @@ -0,0 +1 @@ +MD \ No newline at end of file diff --git a/module-test/assets/svg/label-MD-light.svg b/module-test/assets/svg/label-MD-light.svg new file mode 100644 index 00000000000..6481569ca8e --- /dev/null +++ b/module-test/assets/svg/label-MD-light.svg @@ -0,0 +1 @@ +MD \ No newline at end of file diff --git a/module-test/assets/svg/label-ONBOARD-dark.svg b/module-test/assets/svg/label-ONBOARD-dark.svg new file mode 100644 index 00000000000..9aa308ae98c --- /dev/null +++ b/module-test/assets/svg/label-ONBOARD-dark.svg @@ -0,0 +1 @@ +ESP \ No newline at end of file diff --git a/module-test/assets/svg/label-ONBOARD-light.svg b/module-test/assets/svg/label-ONBOARD-light.svg new file mode 100644 index 00000000000..4d9c925a06a --- /dev/null +++ b/module-test/assets/svg/label-ONBOARD-light.svg @@ -0,0 +1 @@ +ESP \ No newline at end of file diff --git a/module-test/assets/svg/label-STEPPER-dark.svg b/module-test/assets/svg/label-STEPPER-dark.svg new file mode 100644 index 00000000000..efab3d03d73 --- /dev/null +++ b/module-test/assets/svg/label-STEPPER-dark.svg @@ -0,0 +1 @@ +ST \ No newline at end of file diff --git a/module-test/assets/svg/label-STEPPER-light.svg b/module-test/assets/svg/label-STEPPER-light.svg new file mode 100644 index 00000000000..0ed3e1e1a57 --- /dev/null +++ b/module-test/assets/svg/label-STEPPER-light.svg @@ -0,0 +1 @@ +ST \ No newline at end of file diff --git a/module-test/assets/svg/label-UART-dark.svg b/module-test/assets/svg/label-UART-dark.svg new file mode 100644 index 00000000000..ff4e90aec54 --- /dev/null +++ b/module-test/assets/svg/label-UART-dark.svg @@ -0,0 +1 @@ +UART \ No newline at end of file diff --git a/module-test/assets/svg/label-UART-light.svg b/module-test/assets/svg/label-UART-light.svg new file mode 100644 index 00000000000..1ec87664635 --- /dev/null +++ b/module-test/assets/svg/label-UART-light.svg @@ -0,0 +1 @@ +UART \ No newline at end of file diff --git a/module-test/assets/svg/u1-top.svg b/module-test/assets/svg/u1-top.svg new file mode 100644 index 00000000000..f91cac9549b --- /dev/null +++ b/module-test/assets/svg/u1-top.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/module-test/assets/svg/u4-top.svg b/module-test/assets/svg/u4-top.svg new file mode 100644 index 00000000000..8178b49e5f3 --- /dev/null +++ b/module-test/assets/svg/u4-top.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/module-test/assets/svg/usb-front.svg b/module-test/assets/svg/usb-front.svg new file mode 100644 index 00000000000..276055581c8 --- /dev/null +++ b/module-test/assets/svg/usb-front.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/module-test/assets/svg/usb-top.svg b/module-test/assets/svg/usb-top.svg new file mode 100644 index 00000000000..15f479d6e49 --- /dev/null +++ b/module-test/assets/svg/usb-top.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/module-test/components/bomotor.js b/module-test/components/bomotor.js new file mode 100644 index 00000000000..49c284e11e1 --- /dev/null +++ b/module-test/components/bomotor.js @@ -0,0 +1,93 @@ +import {Group} from 'three'; + +import {ridgeTexture} from '../lib/parts.js'; +import {lead} from '../lib/breakout.js'; + +/* + * BO motor with wheel: the yellow plastic gearbox with its silver motor, and a 65 mm wheel + * (yellow hub, black tread) on the output shaft, stood as it sits on a robot. Leads end in + * stripped tips for a driver's screw terminal. A loose part: it plugs into a motor driver, not a jack. + */ +const YELLOW = {color: '#f4c21b', rough: 0.55}; +const GB = {x: 0, y: 0, w: 89, d: 53, h: 43}; +const AXLE = {x: 22, z: 78}; +const WHEEL = {r: 78, width: 62, rim: 58}; + +/** Cylinder whose axis runs along y (SVG-style y), centred on (cx, cy, cz). */ +const alongY = (kit, {cx, cy, cz, r, len, side, top, bottom, seg = 48}) => { + const mesh = kit.cylinder({cx: 0, cy: 0, r, z0: -len / 2, z1: len / 2, side, top, bottom, seg}); + mesh.rotation.x = Math.PI / 2; + mesh.position.set(cx, -cy, cz); + return mesh; +}; + +/** Cylinder along x from x0 to x1 at (cy, cz). */ +const alongX = (kit, {x0, x1, cy, cz, r, side, top, bottom, seg = 40}) => { + const mesh = kit.cylinder({cx: 0, cy: 0, r, z0: 0, z1: x1 - x0, side, top, bottom, seg}); + mesh.rotation.y = Math.PI / 2; + mesh.position.set((x0 + x1) / 2, -cy, cz); + return mesh; +}; + +const HUB_SVG = (() => { + let s = ''; + for (let i = 0; i < 6; i++) { + const a = (i / 6) * Math.PI * 2; + const x = 60 + (36 * Math.cos(a)); + const y = 60 + (36 * Math.sin(a)); + s += ``; + } + return `${s}`; +})(); + +const buildScene = kit => { + const g = new Group(); + g.name = 'bomotor'; + const z0 = AXLE.z - (GB.h / 2); + // gearbox, motor can with its end cap and tabs + g.add(kit.box({x: GB.x, y: GB.y, w: GB.w, d: GB.d, h: GB.h, z: z0, color: YELLOW})); + g.add(kit.box({x: GB.x + 8, y: GB.y - 4, w: 12, d: 4, h: 10, z: z0 + 16, color: YELLOW})); + g.add(alongX(kit, {x0: GB.w, x1: GB.w + 60, cy: GB.d / 2, cz: AXLE.z, r: 24, side: {color: '#c6c9cc', rough: 0.3, metal: 0.85}})); + g.add(alongX(kit, {x0: GB.w + 60, x1: GB.w + 66, cy: GB.d / 2, cz: AXLE.z, r: 22, side: {color: '#8a5a2b', rough: 0.6}, top: {color: '#7a4e26', rough: 0.6}})); + [-8, 8].forEach(o => g.add(kit.box({x: GB.w + 66, y: (GB.d / 2) + o - 2, w: 6, d: 4, h: 0.8, z: AXLE.z + 10, color: {color: '#d4d6d8', metal: 0.8, rough: 0.3}}))); + lead(kit, g, ['#d0302a', '#151515'], k => [ + [GB.w + 70, (GB.d / 2) + (k * 16), AXLE.z + 10.4], + [GB.w + 90, (GB.d / 2) + (k * 10), AXLE.z], + [GB.w + 110, (GB.d / 2) + 6 + (k * 3), 20], + [GB.w + 150, (GB.d / 2) + 12 + (k * 3), 1.3] + ], 1.4); + // output shaft and the wheel on the -y side + const wy = -WHEEL.width / 2 - 8; + g.add(alongY(kit, {cx: AXLE.x, cy: -4, cz: AXLE.z, r: 2.6, len: 16, side: {color: '#f6f6f2', rough: 0.4}})); + g.add(alongY(kit, { + cx: AXLE.x, + cy: wy, + cz: AXLE.z, + r: WHEEL.r, + len: WHEEL.width, + seg: 64, + side: {map: ridgeTexture(kit, 'tread', Math.PI * 2 * WHEEL.r, WHEEL.width, 7, '#1a1a1a', '#0a0a0a'), rough: 0.85}, + top: {color: '#181818', rough: 0.8}, + bottom: {color: '#181818', rough: 0.8} + })); + g.add(alongY(kit, { + cx: AXLE.x, + cy: wy, + cz: AXLE.z, + r: WHEEL.rim, + len: WHEEL.width + 1.2, + seg: 48, + side: YELLOW, + top: {map: kit.tex.svg('bo-hub', 120, 120, HUB_SVG, {ppu: 4, base: '#f4c21b'}), rough: 0.5}, + bottom: {map: kit.tex.svg('bo-hub', 120, 120, HUB_SVG, {ppu: 4, base: '#f4c21b'}), rough: 0.5} + })); + return g; +}; + +export default { + id: 'bomotor', + name: 'BO Motor with Wheel', + category: 'output', + kind: 'part', + buildScene +}; diff --git a/module-test/components/btn.js b/module-test/components/btn.js new file mode 100644 index 00000000000..7f7894a121c --- /dev/null +++ b/module-test/components/btn.js @@ -0,0 +1,38 @@ +import {TOP, resistor} from '../lib/parts.js'; + +const CAP_TOP = '' + + '' + + '' + + [[3, 3], [21, 3], [3, 21], [21, 21]].map(([x, y]) => ``).join(''); + +/** Tactile push button: 12 mm switch body with a metal top and a red cap. */ +export default { + id: 'btn', + name: 'Push Button', + category: 'input', + defaultPort: 'D13', + spec: {w: 96, h: 48, jackY: 24, label: 'BUTTON', labelAt: [66, 44]}, + build (kit, g, {options}) { + resistor(kit, g, 38, 38); + g.add(kit.box({ + x: 54, + y: 12, + w: 24, + d: 24, + h: 6, + z: TOP, + color: {color: '#1c1c1c', rough: 0.5}, + faces: {t: {map: kit.tex.svg('btn-top', 24, 24, CAP_TOP, {ppu: 8, base: '#c0c2c4'}), rough: 0.35, metal: 0.5}} + })); + const cap = options.capColor || '#d32f2f'; + g.add(kit.cylinder({ + cx: 66, + cy: 24, + r: 7.5, + z0: TOP + 6, + z1: TOP + 10.4, + side: {color: options.capSide || (options.capColor ? cap : '#9e1c1c'), rough: 0.45}, + top: {color: cap, rough: 0.35} + })); + } +}; diff --git a/module-test/components/buzzer.js b/module-test/components/buzzer.js new file mode 100644 index 00000000000..d15a49a2771 --- /dev/null +++ b/module-test/components/buzzer.js @@ -0,0 +1,49 @@ +import {TOP, sot23} from '../lib/parts.js'; +import {smd, text} from '../lib/breakout.js'; + +/** Active buzzer (12 × 9.5 mm) soldered straight onto the purple RJ11 carrier, with its driver transistor. */ +const W = 84; +const H = 50; +const CX = 60; +const CY = H / 2; +const R = 14.4; + +const TOP_SVG = '' + + '' + + '' + + ''; + +export default { + id: 'buzzer', + name: 'Buzzer', + category: 'output', + defaultPort: 'D13', + spec: { + w: W, + h: H, + jackY: CY, + label: 'BUZZER', + labelAt: [CX, H - 4], + labelSize: 3.6, + holes: [[W - 6, 6], [W - 6, H - 6]], + silk: `` + + `` + + text('+', CX - 7, CY - R - 3.2, {size: 3}) + }, + build (kit, g) { + sot23(kit, g, {x: 34, y: CY - 1.7}); + smd(kit, g, 34, CY + 6); + smd(kit, g, 34, CY - 9); + [-3.8, 3.8].forEach(o => g.add(kit.box({x: CX + o - 0.4, y: CY - 0.4, w: 0.8, d: 0.8, h: 2, z: TOP, color: {color: '#cfd2d5', rough: 0.3, metal: 0.8}}))); + g.add(kit.cylinder({ + cx: CX, + cy: CY, + r: R, + z0: TOP + 1, + z1: TOP + 23.8, + seg: 40, + side: {color: '#141416', rough: 0.45}, + top: {map: kit.tex.svg('buzzer-top', 30, 30, TOP_SVG, {ppu: 12, base: '#141416'}), rough: 0.5} + })); + } +}; diff --git a/module-test/components/card.js b/module-test/components/card.js new file mode 100644 index 00000000000..b0e3b03421b --- /dev/null +++ b/module-test/components/card.js @@ -0,0 +1,44 @@ +import {CARD} from '../lib/board-data.js'; + +const CARD_T = 5; + +/** Jack each output module plugs into in "plugged into board" mode. */ +const CARD_PORTS = { + relay: 'A3', + servo: 'D13', + l293d: 'J0', + relay4: 'J0', + stepper: 'STEPPER1', + oled: 'I2C', + ble: 'I2C1', + hc05: 'UART1' +}; + +/** + * A module without a 3D model yet: a rounded slab with its icon and name, like the studio's + * edit-view card. The face artwork is exported per theme (assets/svg/card--.svg). + */ +const makeCard = mod => ({ + id: mod.id, + name: mod.name, + category: mod.category, + kind: 'card', + color: mod.color, + defaultPort: CARD_PORTS[mod.id] || 'A1', + /** The card slab with its top-left corner at (x, y) world units and its underside at z. */ + buildCard (kit, {theme = 'dark', x = 0, y = 0, z = 0} = {}) { + return kit.slab({ + x, + y, + w: CARD.w, + d: CARD.h, + h: CARD_T, + z, + r: 12, + top: {map: kit.tex.asset(`card-${mod.id}-${theme}`), rough: 0.5}, + side: {color: mod.color, rough: 0.5} + }); + } +}); + +export {CARD_T, CARD_PORTS, makeCard}; diff --git a/module-test/components/dht.js b/module-test/components/dht.js new file mode 100644 index 00000000000..2d5d8b8bd8c --- /dev/null +++ b/module-test/components/dht.js @@ -0,0 +1,29 @@ +import {TOP, resistor} from '../lib/parts.js'; + +const GRILLE = '' + + [0, 1, 2, 3, 4].map(row => [0, 1, 2, 3, 4, 5].map(col => ( + `` + )).join('')).join(''); + +/** DHT11 temperature and humidity sensor: blue vented housing. */ +export default { + id: 'dht', + name: 'DHT11 Temp & Humid', + category: 'sensor', + defaultPort: 'D13', + spec: {w: 112, h: 56, jackY: 28, label: 'DHT11', labelAt: [76, 53]}, + build (kit, g) { + resistor(kit, g, 36, 4); + g.add(kit.slab({ + x: 50, + y: 8, + w: 52, + d: 40, + h: 13, + z: TOP, + r: 1.5, + top: {map: kit.tex.svg('dht-top', 52, 40, GRILLE, {ppu: 8, base: '#4b92e0'}), rough: 0.55}, + side: {color: '#3a7fcf', rough: 0.55} + })); + } +}; diff --git a/module-test/components/drv8833.js b/module-test/components/drv8833.js new file mode 100644 index 00000000000..c200d361843 --- /dev/null +++ b/module-test/components/drv8833.js @@ -0,0 +1,71 @@ +import {TOP} from '../lib/parts.js'; +import {PCB, boardSvg, carrierTraces, pinColumn, screwTerminal, smd, stack, text} from '../lib/breakout.js'; + +/* + * DRV8833 dual motor driver: the small red breakout (18.5 × 16 mm, two 6-pin rows) stacked on the + * purple RJ11 carrier, with screw terminals for motor A, motor B and the motor supply (VM). + */ +const MX = 36; +const MY = 20; +const w = 44; +const d = 38; +const left = pinColumn(6, 3, d / 2); +const right = pinColumn(6, w - 3, d / 2); +const LEFT_NAMES = ['IN1', 'IN2', 'IN3', 'IN4', 'VCC', 'GND']; +const RIGHT_NAMES = ['OUT1', 'OUT2', 'OUT3', 'OUT4', 'VM', 'EEP']; +const TX = MX + w + 14; +const W = TX + 18 + 4; +const H = 84; + +const svg = boardSvg({ + w, + d, + color: PCB.red[0], + pins: [...left, ...right], + extra: LEFT_NAMES.map((n, i) => text(n, 7, left[i].v, {size: 1.6, anchor: 'start'})).join('') + + RIGHT_NAMES.map((n, i) => text(n, w - 7, right[i].v, {size: 1.6, anchor: 'end'})).join('') + + text('DRV8833', w / 2, 3.4, {size: 2.2, weight: 700}) +}); + +const CHIP = '' + + '8833'; + +export default { + id: 'drv8833', + name: 'Motor Driver DRV8833', + category: 'output', + defaultPort: 'STEPPER1', + spec: { + w: W, + h: H, + jackY: MY + (d / 2), + label: 'DRV8833', + labelAt: [MX + (w / 2), H - 5], + labelSize: 3.6, + holes: [[6, 6], [6, H - 6]], + silk: carrierTraces(left.map(p => [MX + p.u, MY + p.v]), MY + (d / 2), {spread: 1.8, width: 0.9}) + + text('MOTOR A', TX + 9, 4, {size: 2.4}) + text('VM', TX + 9, H - 3, {size: 2.4}) + + `` + + `` + }, + build (kit, g) { + const m = stack(kit, g, {x: MX, y: MY, w, d, key: 'drv8833-module', svg, color: PCB.red, pins: [...left, ...right]}); + m.add(kit.box({ + x: 17, + y: 13, + w: 10, + d: 7, + h: 1.2, + z: TOP, + color: {color: '#18191b', rough: 0.45}, + faces: {t: {map: kit.tex.svg('drv8833-chip', 10, 7, CHIP, {ppu: 16, base: '#1a1b1d'}), rough: 0.45}} + })); + smd(kit, m, 18, 24, 'C'); + smd(kit, m, 24, 24, 'C'); + smd(kit, m, 18, 7); + // motor A, motor B and VM screw terminals along the east edge + screwTerminal(kit, g, {x: TX, y: 7, n: 2, pitch: 12, open: 'e'}); + screwTerminal(kit, g, {x: TX, y: 31, n: 2, pitch: 12, open: 'e'}); + screwTerminal(kit, g, {x: TX, y: 55, n: 2, pitch: 12, open: 'e'}); + } +}; diff --git a/module-test/components/esp32-board.js b/module-test/components/esp32-board.js new file mode 100644 index 00000000000..2bd04178f7d --- /dev/null +++ b/module-test/components/esp32-board.js @@ -0,0 +1,378 @@ +import {Group} from 'three'; + +import {CARD, SLAB_T, STUB} from '../lib/board-data.js'; +import {at} from '../lib/kit.js'; +import {PCB_COLOR, PCB_EDGE} from '../lib/pcb.js'; +import {BLACK, buildJack, chipTopSvg, glowDecal, ownCopy, passiveTexture} from '../lib/parts.js'; +import { + ESP_MODULE, + HOLES, + HUB, + HUB_PORTS, + HUB_SCALE as S, + LEDS, + OPEN_ROT, + PASSIVES, + POWER, + TRACES, + TRACE_POINTS, + pathD +} from './hub-layout.js'; + +/* + * RJ11 Hub: ESP32 maker board with 13 RJ11 jacks and USB-C, on the purple house PCB. + * Layout (hub-layout.js) is drawn in hub units (HUB.w × HUB.h, SVG-style y down) and scaled + * by S into world units so the jacks match the module sockets. + */ +const T = SLAB_T / S; + +const SILK = '#f4f4f0'; +const TRACE = '#6531a3'; +const TRACE_HI = '#8455c4'; +const GOLD_PAD = 'url(#hPad)'; +const LEG = '#c9ccce'; +const SILK_FONT = '"Barlow Condensed", "Arial Narrow", "Roboto Condensed", system-ui, sans-serif'; + +// ---- Artwork ---------------------------------------------------------------- + +/** Silkscreen jack names: [hub jack id, x, y, rotation]. */ +const JACK_SILK = [ + ['A4', 157, 58, 90], ['N01', 157, 104, 90], ['STEPPER1', 157, 246, 90], ['A1', 157, 382, 90], ['D13', 157, 537, 90], + ['A3', 396, 186, -90], ['A2', 396, 333, -90], ['UART1', 396, 458, -90], ['J0', 396, 628, -90], + ['I2C', 238, 124, 180], ['I2C1', 312, 124, 180], ['RJ11', 285, 613, 0] +]; + +const silk = (t, x, y, size = 9, rot = 0, anchor = 'middle') => ( + `${t}` +); + +const DEFS = '' + + '' + + '' + + ''; + +/** + * The board's top: purple mask, raised copper traces, gold pads, white silkscreen. + * labels: hub jack id → the name to print beside that jack (defaults to the id). + */ +const boardTopSvg = (labels = {}) => { + let s = `${DEFS}`; + const all = Object.keys(TRACES).reduce((list, k) => list.concat(TRACES[k]), []); + const stubs = [230, 250, 270, 290, 310].map(x => [[x, 355], [x, 378]]); + const shorts = [[[212, 407], [212, 467]], [[332, 407], [332, 440], [282, 440]], [[262, 440], [252, 440], [252, 407]]]; + const group = (list, w) => list.map(p => ( + `` + )).join(''); + const relief = (list, w) => `${group(list, w + 0.6)}` + + `${group(list, w)}` + + `${group(list, w * 0.3)}`; + s += relief([...all, ...stubs, ...shorts], 3); + s += relief([POWER], 6); + stubs.forEach(([[x]]) => { + s += ``; + }); + // ESP32 castellation pads + for (let i = 0; i < 13; i++) { + const y = 220 + (i * 10); + s += ``; + } + for (let i = 0; i < 12; i++) { + s += ``; + } + // passive and LED pads + PASSIVES.forEach(([, , x, y, o]) => { + s += o === 'v' ? + `` : + ``; + }); + LEDS.forEach(l => { + s += ``; + }); + // U4 SOIC legs, U1 SOT-223 legs and tab, SOT-23 legs + for (let i = 0; i < 8; i++) { + const y = 474 + (i * 6.6); + s += ``; + } + [212, 223, 234].forEach(x => { + s += ``; + }); + s += ``; + [471, 481].forEach(y => { + s += ``; + }); + s += ``; + // fuse and ZGA diode pads + s += ``; + s += ``; + // mounting holes: gold ring, dark drill + HOLES.forEach(([x, y, r]) => { + s += ``; + }); + // 5V / GND / 3.3V header pads + [['5V', 676], ['GND', 700], ['3.3V', 724]].forEach(([t, y]) => { + s += ``; + for (let i = 0; i < 5; i++) { + const x = 477 + (i * 16); + s += ``; + } + s += silk(t, 462, y, 11, 0, 'end'); + }); + // port labels + JACK_SILK.forEach(([id, x, y, rot]) => { + s += silk(labels[id] || id, x, y, 10, rot); + }); + // reference designators + PASSIVES.forEach(([ref, , x, y, o]) => { + s += o === 'v' ? silk(ref, x - 8, y, 7, -90) : silk(ref, x, y - 10, 7); + }); + s += silk('U4', 252, 497, 9, -90) + silk('U1', 250, 536, 9) + silk('U1', 341, 463, 7) + silk('ZGA', 252, 569, 8) + + silk('PWR_LED1', 330, 579, 8); + LEDS.forEach(l => { + s += silk(l.ref, l.x, 547, 6.5); + }); + s += silk('RST', 33, 728, 11) + silk('BOOT', 120, 724, 11) + silk('LMS', 190, 656, 11) + silk('USB1', 380, 674, 10); + s += ``; + return s; +}; + +const MODULE_TOP = (() => { + let s = '' + + '' + + ''; + for (let i = 0; i < 13; i++) { + const y = 80 + (i * 10); + s += ``; + } + for (let i = 0; i < 12; i++) { + const x = 22 + (i * 10); + s += ``; + } + return s; +})(); + +const CAN_TOP = '' + + '' + + '' + + '' + + 'ESP-32' + + 'CE' + + '' + + '111S3-3100' + + 'PRC::DB60K1B408' + + ''; + +const USB_TOP = '' + + '' + + '' + + '' + + ''; + +const USB_FRONT = '' + + '' + + '' + + [0, 1, 2, 3, 4, 5].map(i => ``).join(''); + +/** Gold half-holes along one edge of the ESP32 module, as a len × 8 strip. */ +const castStrip = (len, positions) => `` + + positions.map(p => ``).join(''); + +// ---- Ports ------------------------------------------------------------------ + +/** Port records in world units, shaped like the studio's (side, kind, pos.cableX/Y, pos.cardX/Y). */ +const PORTS = HUB_PORTS.map(port => { + const [mx, my] = [port.pos.x, port.pos.y]; + const card = { + left: [mx - STUB - CARD.w, my - (CARD.h / 2)], + right: [mx + STUB, my - (CARD.h / 2)], + top: [mx - (CARD.w / 2), my - STUB - CARD.h], + bottom: [mx - (CARD.w / 2), my + STUB] + }[port.side]; + return {...port, pos: {...port.pos, cardX: card[0], cardY: card[1]}}; +}); + +// ---- Build ------------------------------------------------------------------ + +/** + * The PCB and everything soldered to it, built in hub units inside a group scaled by S. + * labels: silkscreen names for the jacks (see boardTopSvg). + */ +const buildBoard = (kit, {labels = null} = {}) => { + const group = new Group(); + group.scale.setScalar(S); + const topKey = labels ? `hub-top:${Object.keys(labels).map(k => `${k}=${labels[k]}`).join(',')}` : 'hub-top'; + + group.add(kit.slab({ + x: 0, + y: 0, + w: HUB.w, + d: HUB.h, + h: T, + z: -T, + r: 8, + top: {map: kit.tex.svg(topKey, HUB.w, HUB.h, boardTopSvg(labels || {}), {ppu: 4, base: PCB_COLOR}), rough: 0.6}, + side: {color: PCB_EDGE, rough: 0.7} + })); + + // ESP32 module: black PCB with castellations, then the shield can + const mod = {x: ESP_MODULE.x, y: ESP_MODULE.y, w: ESP_MODULE.w, d: ESP_MODULE.d, h: 8, z: 0}; + group.add(kit.box({ + ...mod, + color: {color: '#151515', rough: 0.5}, + faces: {t: {map: kit.tex.svg('hub-esp-top', 154, 215, MODULE_TOP, {ppu: 5, base: '#141414'}), rough: 0.5}} + })); + const side13 = Array.from({length: 13}, (_, i) => 80 + (i * 10)); + const bottom12 = Array.from({length: 12}, (_, i) => 22 + (i * 10)); + const castMat = (key, len, pos) => ({map: kit.tex.svg(`hub-cast-${key}`, len, 8, castStrip(len, pos), {ppu: 6, base: '#151515'}), rough: 0.4}); + group.add(kit.sideDecal({...mod, face: 's', material: castMat('s', 154, bottom12)})); + group.add(kit.sideDecal({...mod, face: 'w', material: castMat('w', 215, side13)})); + group.add(kit.sideDecal({...mod, face: 'e', material: castMat('e', 215, side13.map(p => 215 - p))})); + group.add(kit.box({ + x: 202, + y: 213, + w: 146, + d: 138, + h: 14, + z: 8, + color: {color: '#bdb8ac', rough: 0.35, metal: 0.75}, + faces: {t: {map: kit.tex.svg('hub-can', 146, 138, CAN_TOP, {ppu: 5, base: '#c9c4b8'}), rough: 0.38, metal: 0.55}} + })); + + // U4 SOIC, U1 SOT-223, small SOT-23 + const ic = (key, x, y, w, d, h, dot) => group.add(kit.box({ + x, + y, + w, + d, + h, + color: BLACK, + faces: {t: {map: kit.tex.svg(`hub-ic-${key}`, w, d, chipTopSvg(w, d, dot), {ppu: 6, base: '#1a1b1d'}), rough: 0.45}} + })); + ic('u4', 267, 469, 36, 57, 9, {x: 7, y: 7}); + ic('u1', 206, 522, 34, 28, 11); + ic('sot', 337, 470, 9, 13, 6); + + PASSIVES.forEach(([, kind, x, y, o]) => { + const v = o === 'v'; + const w = v ? 7 : 15; + const d = v ? 13 : 7; + group.add(kit.box({ + x: x - (w / 2), + y: y - (d / 2), + w, + d, + h: kind === 'C' ? 6 : 4.5, + color: kind === 'C' ? '#8a6641' : '#121212', + faces: {t: {map: passiveTexture(kit, kind === 'C' ? 'C' : 'R', !v), rough: 0.45}} + })); + }); + + // fuse and ZGA diode + group.add(kit.box({ + x: 205, + y: 576, + w: 14, + d: 8, + h: 5, + color: '#bdb6aa', + faces: {t: {map: kit.tex.svg('hub-fuse', 14, 8, '' + + '' + + '', {ppu: 8, base: '#e4ddd2'}), rough: 0.5}} + })); + group.add(kit.box({ + x: 242, + y: 577.5, + w: 20, + d: 9, + h: 6, + color: '#141414', + faces: {t: {map: kit.tex.svg('hub-zga', 20, 9, '' + + '', {ppu: 8, base: '#1a1a1a'}), rough: 0.5}} + })); + + // status LEDs with glow + const leds = LEDS.map(led => { + group.add(kit.box({x: led.x - 3, y: led.y - 5, w: 6, d: 10, h: 4, color: {color: '#ece9e0', rough: 0.4}})); + const dot = kit.cylinder({cx: led.x, cy: led.y, r: 2, z0: 4, z1: 4.4, side: kit.basic({color: led.color}), seg: 20}); + dot.castShadow = false; + group.add(dot); + const glow = glowDecal(kit, {cx: led.x, cy: led.y, size: 44, z: 4.6, color: led.color, opacity: led.mode === 'power' ? 0.9 : 0.35}); + group.add(glow); + return {mode: led.mode, glow}; + }); + + // RST and BOOT tactile buttons + [[22, 690], [109, 686]].forEach(([x, y]) => { + group.add(kit.box({x, y, w: 22, d: 18, h: 9, color: {color: '#a7a9ab', rough: 0.35, metal: 0.6}})); + group.add(kit.cylinder({ + cx: x + 11, + cy: y + 9, + r: 5.5, + z0: 9, + z1: 12.5, + side: {color: '#3d2e27', rough: 0.55}, + top: {color: '#5a463c', rough: 0.5}, + seg: 24 + })); + }); + + // LMS slide switch + group.add(kit.box({x: 177, y: 668, w: 26, d: 74, h: 12, color: BLACK})); + group.add(kit.box({x: 184, y: 690, w: 12, d: 20, h: 7, z: 12, color: {color: '#3a3a3a', rough: 0.5}})); + + // USB-C receptacle opening to the south edge + const usb = {x: 352, y: 684, w: 56, d: 68, h: 26, z: 0}; + group.add(kit.box({ + ...usb, + color: {color: '#b8babc', rough: 0.3, metal: 0.85}, + faces: {t: {map: kit.tex.svg('hub-usb-top', 56, 68, USB_TOP, {ppu: 6, base: '#c9cbcd'}), rough: 0.3, metal: 0.7}} + })); + group.add(kit.sideDecal({ + ...usb, + face: 's', + material: {map: kit.tex.svg('hub-usb-front', 56, 26, USB_FRONT, {ppu: 6, base: '#c9cbcd'}), rough: 0.35, metal: 0.5} + })); + + return {group, leds}; +}; + +/** The 13 RJ11 jacks with their colour stripes, in world units. */ +const buildPorts = (kit, theme = 'dark') => PORTS.map(port => { + const color = port.colors[theme] || port.colors.dark; + const fp = port.footprint; + const jack = buildJack(kit, {color, D: port.jack.D, Wd: port.jack.Wd}); + const [cx, cy] = at(fp.x + (fp.w / 2), fp.y + (fp.d / 2)); + jack.position.set(cx, cy, 0); + jack.rotation.z = OPEN_ROT[port.open]; + jack.traverse(obj => { + if (obj.isMesh) { + obj.material = Array.isArray(obj.material) ? obj.material.map(ownCopy) : ownCopy(obj.material); + obj.userData.portId = port.id; + } + }); + return {port, jack, color}; +}); + +/** The RJ11 Hub board with its jacks, in world coordinates. */ +const buildBoardScene = (kit, {theme = 'dark'} = {}) => { + const group = new Group(); + group.name = 'esp32-board'; + const board = buildBoard(kit); + group.add(board.group); + const ports = buildPorts(kit, theme); + ports.forEach(p => group.add(p.jack)); + group.userData.ports = ports; + group.userData.leds = board.leds; + return group; +}; + +export {HUB, S as HUB_SCALE, PORTS, TRACE_POINTS, OPEN_ROT, boardTopSvg, buildBoard, buildPorts, buildBoardScene}; + +export default { + id: 'esp32-board', + name: 'ESP32 RJ11 Hub', + category: 'board', + kind: 'board', + buildScene: buildBoardScene +}; diff --git a/module-test/components/flame.js b/module-test/components/flame.js new file mode 100644 index 00000000000..0385d640dfe --- /dev/null +++ b/module-test/components/flame.js @@ -0,0 +1,92 @@ +import {TOP, soic} from '../lib/parts.js'; +import {PCB, PITCH, boardSvg, carrierPinNames, carrierTraces, holeSvg, led5, rightAngleHeader, smd, stack, text} from '../lib/breakout.js'; + +/* + * Flame sensor — the common 4-pin blue LM393 board (32 × 14 mm, about 2.4 units per mm), mirrored + * so its right-angle header faces the RJ11 socket: header and mounting hole by the socket, the + * PWR and DO LEDs, the tall blue 3296 multi-turn trimmer over the LM393, resistors, then the black + * IR photodiode lying off the far edge to look for flame. + */ +const MX = 40; +const MY = 5; +const w = 76; +const d = 34; +const PIN_V = [0, 1, 2, 3].map(i => 7.85 + (i * PITCH)); +const NAMES = ['AO', 'GND', 'VCC', 'DO']; +const W = MX + w + 5; +const H = MY + d + 13; +const JACK_Y = MY + ((PIN_V[1] + PIN_V[2]) / 2); +const DROP_X = MX - 5; +const TRIM = {u: 34, v: 1.4, w: 9.6, d: 23, h: 24}; +const RES = [[50, 4], [50, 9.6], [50, 22.4], [50, 28]]; +const LEDS = [{u: 15, v: 2.4, label: 'PWR', lit: true}, {u: 15, v: 28.8, label: 'DO', lit: false}]; +const PD = {v: d / 2, legsU: 62}; + +const svg = boardSvg({ + w, + d, + color: PCB.blue[0], + pins: PIN_V.map(v => ({u: 3.2, v})), + extra: holeSvg(17.6, d / 2, 3.4) + + NAMES.map((n, i) => text(n, 9.6, PIN_V[i], {size: 2, anchor: 'start', weight: 700})).join('') + + LEDS.map(l => `` + + text(l.label, l.u + 2.5, l.v < 10 ? l.v + 6.2 : l.v - 2.6, {size: 1.8})).join('') + + RES.map(([u, v]) => ``).join('') + + holeSvg(PD.legsU, PD.v - 1.3, 1.2) + holeSvg(PD.legsU, PD.v + 1.3, 1.2) + + text('Flame', 60, d - 3, {size: 2.2, weight: 700}) +}); + +/** 3296W trimmer top: brass screw at one end and the 103 marking. */ +const TRIM_SVG = `` + + `` + + `` + + `3296 103`; + +export default { + id: 'flame', + name: 'Flame Sensor', + category: 'sensor', + defaultPort: 'A2', + spec: { + w: W, + h: H, + jackY: JACK_Y, + label: 'FLAME SENSOR', + labelAt: [MX + (w / 2), H - 5], + labelSize: 3.6, + holes: [[6, H - 6]], + silk: carrierTraces(PIN_V.map(v => [DROP_X, MY + v]), JACK_Y) + + carrierPinNames(PIN_V.map(v => [0, MY + v]), NAMES, DROP_X - 2.2) + }, + build (kit, g) { + const m = stack(kit, g, {x: MX, y: MY, w, d, key: 'flame-3296-module', svg, color: PCB.blue}); + rightAngleHeader(kit, g, m, {mx: MX, my: MY, vs: PIN_V, dropX: DROP_X}); + + LEDS.forEach(l => m.add(kit.box({ + x: l.u, + y: l.v, + w: 5, + d: 2.6, + h: 1.2, + z: TOP, + color: {color: '#e8e5dc', rough: 0.4}, + faces: {t: l.lit ? kit.basic({color: '#ff4a3a'}) : {color: '#f2f6f8', rough: 0.15}} + }))); + m.add(kit.box({ + x: TRIM.u, + y: TRIM.v, + w: TRIM.w, + d: TRIM.d, + h: TRIM.h, + z: TOP, + color: {color: '#2a62c4', rough: 0.45}, + faces: {t: {map: kit.tex.svg('flame-3296', TRIM.w, TRIM.d, TRIM_SVG, {ppu: 12, base: '#2f6fd6'}), rough: 0.4}} + })); + soic(kit, m, {x: 22, y: 21, w: 10, d: 8}); + RES.forEach(([u, v], i) => smd(kit, m, u, v, i === 1 ? 'C' : 'R')); + + // black IR photodiode lying off the far edge, legs bent down into its pads + led5(kit, m, {x: PD.legsU + 6, y: PD.v, dir: 'e', cz: TOP + 6.6, color: '#0f1013', opacity: 1, key: 'flame-pd'}); + } +}; diff --git a/module-test/components/hub-layout.js b/module-test/components/hub-layout.js new file mode 100644 index 00000000000..79197de4328 --- /dev/null +++ b/module-test/components/hub-layout.js @@ -0,0 +1,193 @@ +/* + * RJ11 Hub layout: jack footprints, copper traces and parts positions, with no three.js + * imports so the studio's 2D view can use it too. Hub units are SVG-style (y down) on a + * HUB.w × HUB.h board; multiply by HUB_SCALE for world units. + */ +const HUB = {w: 560, h: 750}; +const S = 0.375; +const JACK_ACROSS = 0.8; +const JACK_DEPTH = 0.86; + +/** open: the board edge the plug enters from; x, y, w, d: the jack's footprint box (hub units). */ +const PORT_DEFS = [ + {id: 'A4', open: 'W', x: -32, y: -40, w: 182, d: 120, desc: 'Analog port'}, + {id: 'I2C', open: 'N', x: 153, y: -70, w: 122, d: 180, desc: 'I²C bus port'}, + {id: 'I2C1', open: 'N', x: 277, y: -70, w: 122, d: 180, desc: 'Second I²C bus port'}, + {id: 'TOP-R', open: 'E', x: 403, y: -40, w: 182, d: 120, desc: 'Port'}, + {id: 'N01', open: 'W', x: -32, y: 88, w: 182, d: 122, desc: 'RJ11 port'}, + {id: 'STEPPER1', open: 'W', x: -32, y: 223, w: 182, d: 124, desc: 'Stepper motor port'}, + {id: 'A1', open: 'W', x: -32, y: 368, w: 182, d: 124, desc: 'Analog port'}, + {id: 'D13', open: 'W', x: -32, y: 520, w: 182, d: 124, desc: 'Digital port'}, + {id: 'A3', open: 'E', x: 403, y: 76, w: 182, d: 124, desc: 'Analog port'}, + {id: 'A2', open: 'E', x: 403, y: 223, w: 182, d: 124, desc: 'Analog port'}, + {id: 'UART1', open: 'E', x: 403, y: 360, w: 182, d: 122, desc: 'Serial (UART) port'}, + {id: 'J0', open: 'E', x: 403, y: 518, w: 182, d: 124, desc: 'RJ11 port'}, + {id: 'RJ11', open: 'S', x: 222, y: 622, w: 126, d: 178, desc: 'Bottom RJ11 port, wired to U4'} +]; + +/** Signal traces from each jack (under its housing) to the ESP32 pins. */ +const M = x => 550 - x; +const LEFT = { + 'I2C': [[[214, 104], [214, 130], [194, 130], [194, 220], [198, 220]], [[202, 104], [202, 124], [190, 124], [190, 230], [198, 230]]], + 'A4': [[[140, 14], [186, 14], [186, 240], [198, 240]], [[140, 26], [182, 26], [182, 250], [198, 250]]], + 'N01': [[[140, 143], [178, 143], [178, 260], [198, 260]], [[140, 155], [174, 155], [174, 270], [198, 270]]], + 'STEPPER1': [[[140, 280], [198, 280]], [[140, 290], [198, 290]]], + 'A1': [[[140, 424], [182, 424], [182, 310], [198, 310]], [[140, 436], [186, 436], [186, 320], [198, 320]]], + 'D13': [[[140, 576], [190, 576], [190, 330], [198, 330]], [[140, 588], [194, 588], [194, 340], [198, 340]]] +}; +const mirror = pts => pts.map(([x, y]) => [M(x), y]); +const shiftStart = (pts, ys) => pts.map(([x, y], i) => (i < 2 ? [x, ys] : [x, y])); +const TRACES = { + ...LEFT, + 'I2C1': LEFT.I2C.map(mirror), + 'TOP-R': LEFT.A4.map(mirror), + 'A3': LEFT.N01.map((p, i) => shiftStart(mirror(p), i ? 144 : 132)), + 'A2': LEFT.STEPPER1.map(mirror), + 'UART1': LEFT.A1.map((p, i) => shiftStart(mirror(p), i ? 427 : 415)), + 'J0': LEFT.D13.map((p, i) => shiftStart(mirror(p), i ? 586 : 574)), + 'RJ11': [[[279, 632], [279, 538], [262, 521]], [[291, 632], [291, 538], [308, 521]]] +}; +const POWER = [[372, 692], [372, 666], [232, 666], [232, 552]]; + +const PASSIVES = [ + ['C1', 'C', 212, 398, 'v'], ['R1', 'R', 252, 398, 'v'], ['C2', 'C', 292, 398, 'v'], ['R2', 'R', 332, 398, 'v'], + ['D1', 'D', 272, 440, 'h'], + ['C3', 'C', 212, 476, 'v'] +]; +const LEDS = [ + {ref: 'E1', x: 315, y: 560, color: '#ff2828', mode: 'power'}, + {ref: 'D3', x: 330, y: 560, color: '#288cff', mode: 'activity'}, + {ref: 'D4', x: 345, y: 560, color: '#28dc6e', mode: 'heartbeat'} +]; +const HOLES = [[168, 370, 7], [530, 498, 7], [20, 664, 8]]; + +/** The ESP32 module (black PCB under the shield can) and the can's height, hub units. */ +const ESP_MODULE = {x: 198, y: 140, w: 154, d: 215, h: 22}; + +const f1 = n => Math.round(n * 10) / 10; + +/** Polyline with chamfered corners as an SVG path. */ +const pathD = (pts, c = 6) => { + let d = `M${f1(pts[0][0])},${f1(pts[0][1])}`; + for (let i = 1; i < pts.length - 1; i++) { + const [ax, ay] = pts[i - 1]; + const [bx, by] = pts[i]; + const [cx, cy] = pts[i + 1]; + const l1 = Math.hypot(bx - ax, by - ay); + const l2 = Math.hypot(cx - bx, cy - by); + const r = Math.min(c, l1 / 2, l2 / 2); + d += ` L${f1(bx - ((bx - ax) / l1 * r))},${f1(by - ((by - ay) / l1 * r))}` + + ` L${f1(bx + ((cx - bx) / l2 * r))},${f1(by + ((cy - by) / l2 * r))}`; + } + const last = pts[pts.length - 1]; + return `${d} L${f1(last[0])},${f1(last[1])}`; +}; + +const SIDE = {W: 'left', E: 'right', N: 'top', S: 'bottom'}; +const OPEN_ROT = {W: 0, E: Math.PI, N: -Math.PI / 2, S: Math.PI / 2}; + +const portKind = id => { + if (/^A\d/.test(id)) { + return 'analog'; + } + if (/^I2C/.test(id)) { + return 'i2c'; + } + if (/^UART/.test(id)) { + return 'uart'; + } + if (/^STEPPER/.test(id)) { + return 'stepper'; + } + return 'digital'; +}; + +const STRIPES = { + analog: {dark: '#10b981', light: '#10b981'}, + i2c: {dark: '#06b6d4', light: '#06b6d4'}, + uart: {dark: '#3b82f6', light: '#3b82f6'}, + stepper: {dark: '#9ca3af', light: '#6b7280'}, + digital: {dark: '#8b5cf6', light: '#8b5cf6'} +}; + +/** The jack's housing box after shrinking it about its back edge (where the traces enter). */ +const jackBox = def => { + const p = {...def}; + if (p.open === 'W') { + const back = p.x + p.w; + p.w *= JACK_DEPTH; + p.x = back - p.w; + } else if (p.open === 'E') { + p.w *= JACK_DEPTH; + } else if (p.open === 'N') { + const back = p.y + p.d; + p.d *= JACK_DEPTH; + p.y = back - p.d; + } else { + p.d *= JACK_DEPTH; + } + if (p.open === 'W' || p.open === 'E') { + const c = p.y + (p.d / 2); + p.d *= JACK_ACROSS; + p.y = c - (p.d / 2); + } else { + const c = p.x + (p.w / 2); + p.w *= JACK_ACROSS; + p.x = c - (p.w / 2); + } + return p; +}; + +/** Jack records in world units relative to the hub's top-left corner; pos.x/y is the mouth. */ +const HUB_PORTS = PORT_DEFS.map(def => { + const b = jackBox(def); + const side = SIDE[def.open]; + const cx = (b.x + (b.w / 2)) * S; + const cy = (b.y + (b.d / 2)) * S; + const mouth = { + left: [b.x * S, cy], + right: [(b.x + b.w) * S, cy], + top: [cx, b.y * S], + bottom: [cx, (b.y + b.d) * S] + }[side]; + const kind = portKind(def.id); + const vertical = side === 'top' || side === 'bottom'; + return { + id: def.id, + label: def.id, + desc: def.desc, + side, + kind, + open: def.open, + pos: {x: mouth[0], y: mouth[1], cableX: mouth[0], cableY: mouth[1]}, + footprint: {x: b.x * S, y: b.y * S, w: b.w * S, d: b.d * S}, + jack: {D: (vertical ? b.d : b.w) * S, Wd: (vertical ? b.w : b.d) * S}, + colors: STRIPES[kind] + }; +}); + +/** Each jack's traces in world units (for lighting up the active one). */ +const TRACE_POINTS = Object.keys(TRACES).reduce((all, id) => { + all[id] = TRACES[id].map(line => line.map(([x, y]) => [x * S, y * S])); + return all; +}, {}); + +export { + HUB, + S as HUB_SCALE, + PORT_DEFS, + TRACES, + POWER, + PASSIVES, + LEDS, + HOLES, + ESP_MODULE, + SIDE, + OPEN_ROT, + STRIPES, + pathD, + portKind, + jackBox, + HUB_PORTS, + TRACE_POINTS +}; diff --git a/module-test/components/i2samp.js b/module-test/components/i2samp.js new file mode 100644 index 00000000000..fa9c71818a5 --- /dev/null +++ b/module-test/components/i2samp.js @@ -0,0 +1,69 @@ +import {TOP} from '../lib/parts.js'; +import {PCB, boardSvg, carrierTraces, lead, pinColumn, screwTerminal, smd, stack, text} from '../lib/breakout.js'; + +/* + * I²S amplifier MAX98357A (blue 18 × 19 mm breakout, 7 pins, speaker screw terminal) stacked on + * the purple RJ11 carrier, wired to a 40 mm 8 Ω speaker lying cone-up on the table. + */ +const MX = 36; +const MY = 5; +const w = 46; +const d = 48; +const pins = pinColumn(7, 3, d / 2); +const names = ['LRC', 'BCLK', 'DIN', 'GAIN', 'SD', 'GND', 'VIN']; +const W = MX + w + 6; +const H = MY + d + 12; +const SPK = {cx: W + 70, cy: H / 2, r: 48}; + +const svg = boardSvg({ + w, + d, + color: PCB.purple[0], + pins, + extra: names.map((n, i) => text(n, 7.4, pins[i].v, {size: 1.8, anchor: 'start'})).join('') + + text('MAX98357A', 24, 4, {size: 2.2, weight: 700}) + text('+', 30, 14, {size: 3}) + text('-', 30, 34, {size: 3}) +}); + +const CHIP = ''; + +/** Cone profile (radius, height) from the dust cap out to the surround. */ +const CONE = [[0, 7], [8, 7], [9, 5.6], [40, 12], [44, 12.6], [46, 12]]; + +export default { + id: 'i2samp', + name: 'I²S Amp MAX98357A + Speaker', + category: 'output', + defaultPort: 'UART1', + spec: { + w: W, + h: H, + jackY: MY + (d / 2), + label: 'I2S AMP', + labelAt: [MX + (w / 2), H - 5], + labelSize: 3.6, + holes: [[6, H - 6]], + silk: carrierTraces(pins.map(p => [MX + p.u, MY + p.v]), MY + (d / 2), {spread: 1.6, width: 0.9}) + }, + build (kit, g) { + const m = stack(kit, g, {x: MX, y: MY, w, d, key: 'max98357-module', svg, color: PCB.purple, pins}); + m.add(kit.box({x: 18, y: 20, w: 7, d: 7, h: 1, z: TOP, color: {color: '#18191b', rough: 0.45}, faces: {t: {map: kit.tex.svg('max98357-chip', 7, 7, CHIP, {ppu: 16, base: '#1a1b1d'}), rough: 0.45}}})); + smd(kit, m, 18, 10, 'C'); + smd(kit, m, 18, 32, 'C'); + smd(kit, m, 18, 38); + screwTerminal(kit, m, {x: w - 18, y: 10, n: 2, pitch: 8.4, open: 'e'}); + + // speaker: magnet underneath, steel frame, paper cone and dust cap, two solder tabs + const {cx, cy, r} = SPK; + g.add(kit.cylinder({cx, cy, r: 22, z0: 0, z1: 14, seg: 40, side: {color: '#2a2b2e', rough: 0.4, metal: 0.6}})); + g.add(kit.cylinder({cx, cy, r, z0: 14, z1: 17, seg: 64, side: {color: '#202124', rough: 0.45, metal: 0.4}, top: {color: '#26272a', rough: 0.5}})); + g.add(kit.lathe({key: 'speaker-cone', cx, cy, z: 14, profile: CONE, seg: 56, material: {color: '#1c1c1e', rough: 0.85}})); + g.add(kit.cylinder({cx, cy, r: 9, z0: 19.4, z1: 22, r1: 6, seg: 32, side: {color: '#111113', rough: 0.6}, top: {color: '#111113', rough: 0.6}})); + [-1, 1].forEach(k => g.add(kit.box({x: cx - r - 6, y: cy + (k * 8) - 2, w: 8, d: 4, h: 0.6, z: 16, color: {color: '#d4d6d8', metal: 0.8, rough: 0.3}}))); + lead(kit, g, ['#d0302a', '#151515'], k => [ + [MX + w + 1, MY + 14.2 + ((k + 0.5) * 8.4), TOP + 6 + 10], + [MX + w + 10, MY + 18 + (k * 4), 8], + [cx - r - 20, cy + (k * 6), 1.3], + [cx - r - 4, cy + (k * 8), 16.4] + ], 1.2); + } +}; diff --git a/module-test/components/ir.js b/module-test/components/ir.js new file mode 100644 index 00000000000..99a478e71d0 --- /dev/null +++ b/module-test/components/ir.js @@ -0,0 +1,106 @@ +import {PCB_H} from '../lib/board-data.js'; +import {BLACK, TOP, soic} from '../lib/parts.js'; +import {PCB, PITCH, boardSvg, carrierPinNames, carrierTraces, holeSvg, led5, smd, stack, text} from '../lib/breakout.js'; + +/* + * IR obstacle sensor — the blue MH-B / FC-51 board (31 × 14 mm, about 2.4 units per mm), laid out + * like the real one but mirrored so its right-angle header faces the RJ11 socket: header and + * mounting hole by the socket, power / obstacle LEDs, square trimmer over the LM393, capacitors and + * resistors, then the black receiver (top) and clear emitter (bottom) lying off the far edge. + */ +const MX = 40; +const MY = 5; +const w = 74; +const d = 34; +const SPACER_H = 6; +const PIN_V = [0, 1, 2].map(i => 9 + (i * PITCH)); +const NAMES = ['VCC', 'GND', 'OUT']; +const W = MX + w + 5; +const H = MY + d + 13; +const JACK_Y = MY + PIN_V[1]; +const PIN_DROP_X = MX - 5; +const TRIM = {u: 27, v: 0.8, s: 12, h: 7}; +const RES = [[46, 15.4], [46, 20.4], [46, 25.4], [46, 30.2]]; +const CAPS = [[51, 3.6], [51, 9.6]]; +const LEDS = [{v: 7.2, label: 'PWR', ly: 2.6}, {v: 24.4, label: 'OBS', ly: 31.6}]; + +const svg = boardSvg({ + w, + d, + color: PCB.blue[0], + pins: PIN_V.map(v => ({u: 3.2, v})), + extra: holeSvg(12.5, 16.5, 3) + + text('MH-B', 9, 3, {size: 2.6, weight: 700}) + + text('VCC GND OUT', 9.4, 15.2, {size: 2.2, rot: -90}) + + LEDS.map(l => `` + + text(l.label, 20.5, l.ly, {size: 2})).join('') + + // through-hole pads where the two IR LEDs' legs go in + [7.2 - 1.3, 7.2 + 1.3, 22.2 - 1.3, 22.2 + 1.3].map(v => holeSvg(60.5, v, 1.2)).join('') + + // silk outlines of the passives + [...RES, ...CAPS].map(([u, v]) => ``).join('') +}); + +/** Square cermet trimmer top: blue body, white cross-slot dial. */ +const TRIM_SVG = '' + + '' + + '' + + '' + + '103'; + +export default { + id: 'ir', + name: 'IR Sensor', + category: 'sensor', + defaultPort: 'D13', + spec: { + w: W, + h: H, + jackY: JACK_Y, + label: 'IR SENSOR', + labelAt: [MX + (w / 2), H - 5], + labelSize: 3.6, + holes: [[6, H - 6]], + silk: carrierTraces(PIN_V.map(v => [PIN_DROP_X, MY + v]), JACK_Y) + + carrierPinNames(PIN_V.map(v => [0, MY + v]), NAMES, PIN_DROP_X - 2.2) + }, + build (kit, g) { + // black support under the header edge, then the board itself (no pins underneath) + g.add(kit.box({x: MX, y: MY + PIN_V[0] - 3, w: 6, d: (PITCH * 2) + 6, h: SPACER_H, z: TOP, color: BLACK})); + const m = stack(kit, g, {x: MX, y: MY, w, d, key: 'ir-mhb-module', svg, color: PCB.blue, spacer: SPACER_H}); + + // right-angle header: plastic strip on the board, pins out west then bent down into the carrier + const top = TOP + SPACER_H + PCB_H; + m.add(kit.box({x: 0.8, y: PIN_V[0] - 3, w: 5, d: (PITCH * 2) + 6, h: 2.6, z: TOP, color: {color: '#151515', rough: 0.5}})); + PIN_V.forEach(v => { + m.add(kit.cylinder({cx: 3.2, cy: v, r: 1.4, z0: TOP, z1: TOP + 0.6, side: {color: '#cfd2d5', rough: 0.3, metal: 0.8}, seg: 12})); + g.add(kit.box({x: PIN_DROP_X - 0.7, y: MY + v - 0.7, w: MX + 3.2 - PIN_DROP_X + 1.4, d: 1.4, h: 1.4, z: top + 0.6, color: {color: '#d6b25a', rough: 0.3, metal: 0.85}})); + g.add(kit.box({x: PIN_DROP_X - 0.7, y: MY + v - 0.7, w: 1.4, d: 1.4, h: top + 2 - TOP + 1.2, z: TOP - 1.2, color: {color: '#d6b25a', rough: 0.3, metal: 0.85}})); + }); + + // indicator LEDs: water-clear SMD parts, power lit + LEDS.forEach((l, i) => { + m.add(kit.box({x: 18, y: l.v - 1.4, w: 5, d: 2.8, h: 1.2, z: TOP, color: {color: '#e8e5dc', rough: 0.4}, faces: {t: i === 0 ? kit.basic({color: '#ff4a3a'}) : {color: '#f2f6f8', rough: 0.15}}})); + }); + + // square trimmer over the LM393 + m.add(kit.box({ + x: TRIM.u, + y: TRIM.v, + w: TRIM.s, + d: TRIM.s, + h: TRIM.h, + z: TOP, + color: {color: '#2a62c4', rough: 0.45}, + faces: {t: {map: kit.tex.svg('ir-trimmer', TRIM.s, TRIM.s, TRIM_SVG, {ppu: 14, base: '#2f6fd6'}), rough: 0.4}} + })); + soic(kit, m, {x: 28, y: 21, w: 11, d: 8}); + + // capacitors (top) and the resistor column + CAPS.forEach(([u, v]) => smd(kit, m, u, v, 'C')); + RES.forEach(([u, v]) => smd(kit, m, u, v, 'R')); + + // IR pair: black receiver on top, clear emitter below, legs bent down into the pads + led5(kit, m, {x: 66, y: 7.2, dir: 'e', cz: TOP + 6.6, color: '#111216', opacity: 1, key: 'ir-rx'}); + led5(kit, m, {x: 66, y: 22.2, dir: 'e', cz: TOP + 6.6, color: '#dde8f2', opacity: 0.55, key: 'ir-tx'}); + } +}; diff --git a/module-test/components/irline.js b/module-test/components/irline.js new file mode 100644 index 00000000000..690495be177 --- /dev/null +++ b/module-test/components/irline.js @@ -0,0 +1,108 @@ +import {TOP} from '../lib/parts.js'; +import {PCB, PITCH, holeSvg, smd, text} from '../lib/breakout.js'; + +/* + * IR line-sensor array — the blue 5-channel TCRT5000 board (about 96 × 20 mm, 2.4 units per mm) + * with a small purple RJ11 carrier riding on top of it in the middle. The array's 7-pin header + * (GND, 5V, OUT1–OUT5) stands up into a female header under the carrier; the TCRT5000 sensors + * hang underneath, looking down at the line. + */ +const W = 76; +const H = 44; +const CY = H / 2; +const A = {w: 230, d: 48}; +A.x = (W / 2) - (A.w / 2); +A.y = CY - (A.d / 2); +const GAP = 16; +const A_TOP = -GAP; +const A_Z = A_TOP - 1.6; +const PIN_X = [0, 1, 2, 3, 4, 5, 6].map(i => 50 + ((i - 3) * PITCH)); +const PIN_Y = A.y + 9; +const NAMES = ['GND', '5V', 'OUT1', 'OUT2', 'OUT3', 'OUT4', 'OUT5']; +const STATIONS = [0, 1, 2, 3, 4].map(i => 18 + (i * 48.5)); + +/** Array top artwork in its own frame (u along its length, v across). */ +const ARRAY_SVG = (() => { + let s = ``; + // the two long mounting slots near the ends + [[8, 8], [A.w - 64, A.d - 15]].forEach(([u, v]) => { + s += ``; + }); + // copper traces under the blue mask + s += ''; + STATIONS.forEach((u, i) => { + [[-3.4, -2.8], [3.4, -2.8], [-3.4, 2.8], [3.4, 2.8]].forEach(([du, dv]) => { + s += holeSvg(u + du, 26 + dv, 1.4); + }); + s += text(String(i + 1), u, 37.5, {size: 2.4}); + }); + s += holeSvg(A.w - 7, 7, 2.6) + holeSvg(7, A.d - 7, 2.6); + PIN_X.forEach((x, i) => { + s += holeSvg(x - A.x, 9, 1.8); + s += text(NAMES[i], x - A.x, 14.2, {size: 1.6, rot: -90, anchor: 'end'}); + }); + s += text('TCRT5000-5CH', 150, 6, {size: 2.6, weight: 700}); + return s; +})(); + +export default { + id: 'irline', + name: 'IR Line Sensor Array', + category: 'sensor', + defaultPort: 'I2C1', + spec: { + w: W, + h: H, + jackY: CY, + label: 'LINE ARRAY', + labelAt: [52, H - 5], + labelSize: 3.4, + holes: [[W - 6, 6]], + silk: PIN_X.map((x, i) => `').join('') + + PIN_X.map(x => holeSvg(x, PIN_Y, 1.5, '#d4b15e')).join('') + }, + build (kit, g) { + // female header under the carrier and the array's male header standing up into it + g.add(kit.box({x: PIN_X[0] - 3, y: PIN_Y - 3, w: PITCH * 7, d: 6, h: 9, z: -9, color: {color: '#151515', rough: 0.5}})); + g.add(kit.box({x: PIN_X[0] - 3, y: PIN_Y - 3, w: PITCH * 7, d: 6, h: 3, z: A_TOP, color: {color: '#1d1d1d', rough: 0.5}})); + PIN_X.forEach(x => g.add(kit.box({x: x - 0.7, y: PIN_Y - 0.7, w: 1.4, d: 1.4, h: GAP - 12, z: A_TOP + 3, color: {color: '#d6b25a', rough: 0.3, metal: 0.85}}))); + + // the array board + g.add(kit.slab({ + x: A.x, + y: A.y, + w: A.w, + d: A.d, + h: 1.6, + z: A_Z, + r: 3, + top: {map: kit.tex.svg('irline-5ch-top', A.w, A.d, ARRAY_SVG, {ppu: 6, base: '#2a6fc4'}), rough: 0.55}, + side: {color: '#1c4f8f', rough: 0.6} + })); + const top = A_TOP - TOP; + const on = part => { + part.position.z += top; + g.add(part); + }; + // LM339 (SOIC-14) and the tantalum capacitor + on(kit.box({x: A.x + 128, y: A.y + 20, w: 21, d: 9, h: 2, z: TOP, color: {color: '#151617', rough: 0.45}})); + for (let i = 0; i < 7; i++) { + [A.y + 18.6, A.y + 29].forEach(y => on(kit.box({x: A.x + 129.6 + (i * 3), y, w: 1, d: 1.4, h: 0.6, z: TOP, color: {color: '#cfd2d5', metal: 0.8, rough: 0.3}, shadow: false}))); + } + on(kit.box({x: A.x + 112, y: A.y + 6, w: 7, d: 4.4, h: 3, z: TOP, color: {color: '#e3b52c', rough: 0.4}})); + + // per station: indicator LED, resistors, and the TCRT5000 hanging below + STATIONS.forEach((u, i) => { + const x = A.x + u; + const y = A.y + 26; + on(kit.cylinder({cx: x + 9, cy: y - 7, r: 2.2, z0: TOP, z1: TOP + 2.6, seg: 18, side: {color: '#111214', rough: 0.3}, top: i === 2 ? kit.basic({color: '#ff4a3a'}) : {color: '#1a1b1e', rough: 0.2}})); + const a = new (g.constructor)(); + smd(kit, a, x - 13, y - 9); + smd(kit, a, x - 13, y + 4); + [...a.children].forEach(c => on(c)); + g.add(kit.box({x: x - 7, y: y - 5.6, w: 6.2, d: 11.2, h: 7, z: A_Z - 7, color: {color: '#1d3f8a', rough: 0.35}})); + g.add(kit.box({x: x + 0.8, y: y - 5.6, w: 6.2, d: 11.2, h: 7, z: A_Z - 7, color: {color: '#111214', rough: 0.35}})); + }); + } +}; diff --git a/module-test/components/lcd.js b/module-test/components/lcd.js new file mode 100644 index 00000000000..04fca35df83 --- /dev/null +++ b/module-test/components/lcd.js @@ -0,0 +1,102 @@ +import {TOP} from '../lib/parts.js'; +import {PCB, holeSvg, text} from '../lib/breakout.js'; + +/* + * LCD 16×2 with I²C backpack (PCF8574, address 0x27): the green 80 × 36 mm LCD board on four + * brass standoffs right on the purple RJ11 carrier. The backpack underneath plugs straight down + * into a 4-pin socket on the carrier — no wires. + */ +const LX = 34; +const LY = 4; +const LW = 192; +const LD = 86; +const LIFT = 28; +const W = LX + LW + 6; +const H = LY + LD + 10; +const NAMES = ['GND', 'VCC', 'SDA', 'SCL']; +const HDR = {x: LX + 5, y: LY + 13}; +const PITCH = 6.1; +const HOLES = [[6, 6], [LW - 6, 6], [6, LD - 6], [LW - 6, LD - 6]]; + +const LCD_PCB = `` + + HOLES.map(([x, y]) => holeSvg(x, y, 4.2)).join('') + + Array.from({length: 16}, (_, i) => holeSvg(19 + (i * 6.1), 4.6, 1.8)).join('') + + text('1', 19, 9.6, {size: 2}) + text('16', 110.5, 9.6, {size: 2}); + +/** 16 × 2 characters of 5 × 8 dots, white on the blue backlight. */ +const SCREEN = (() => { + const VW = 155; + const VH = 35; + const lines = [' TinkerBit ', 'Temp: 28.5 C ']; + let s = ``; + const cw = 8.6; + const ch = 13.4; + const x0 = (VW - (16 * cw)) / 2; + lines.forEach((line, r) => { + for (let c = 0; c < 16; c++) { + const x = x0 + (c * cw) + 0.4; + const y = 3 + (r * (ch + 2.2)); + s += ``; + } + s += `${line}`; + }); + return s; +})(); + +export default { + id: 'lcd', + name: 'LCD 16×2 (I²C)', + category: 'output', + defaultPort: 'I2C', + spec: { + w: W, + h: H, + jackY: H / 2, + label: 'LCD 16x2 I2C 0x27', + labelAt: [LX + (LW / 2), H - 5], + labelSize: 3.6, + holes: [[6, 6], [6, H - 6]], + silk: NAMES.map((n, i) => { + const y = HDR.y + 3 + (i * PITCH); + return `` + + holeSvg(HDR.x, y, 1.6, '#d4b15e'); + }).join('') + }, + build (kit, g) { + // standoffs and the LCD board + HOLES.forEach(([u, v]) => g.add(kit.cylinder({cx: LX + u, cy: LY + v, r: 3.2, z0: TOP, z1: TOP + LIFT, seg: 6, side: {color: '#c9a34c', rough: 0.35, metal: 0.8}}))); + const z = TOP + LIFT; + g.add(kit.slab({x: LX, y: LY, w: LW, d: LD, h: 1.6, z, r: 1.5, top: {map: kit.tex.svg('lcd-pcb', LW, LD, LCD_PCB, {ppu: 6, base: PCB.green[0]}), rough: 0.55}, side: {color: PCB.green[1]}})); + // black bezel and the backlit glass + const bx = LX + 11; + const by = LY + 14; + g.add(kit.box({x: bx, y: by, w: 170, d: 58, h: 7.2, z: z + 1.6, color: {color: '#121214', rough: 0.4, metal: 0.3}})); + g.add(kit.box({ + x: bx + 7.5, + y: by + 11.5, + w: 155, + d: 35, + h: 0.4, + z: z + 8.8, + color: '#1d4fd6', + faces: {t: kit.basic({map: kit.tex.svg('lcd-screen', 155, 35, SCREEN, {ppu: 8, base: '#1d4fd6'})})} + })); + // PCF8574 backpack under the left of the LCD, plugged straight down into the carrier's socket + const pz = z - 12; + g.add(kit.box({x: LX, y: LY + 2, w: 98, d: 46, h: 1.6, z: pz, color: {color: PCB.black[0], rough: 0.55}})); + g.add(kit.box({x: LX + 34, y: LY + 14, w: 18, d: 10, h: 2.4, z: pz - 2.4, color: {color: '#151617', rough: 0.45}})); + g.add(kit.box({x: LX + 62, y: LY + 30, w: 10, d: 10, h: 6, z: pz - 6, color: {color: '#2a62bf', rough: 0.45}})); + g.add(kit.box({x: HDR.x - 3, y: HDR.y, w: 6, d: PITCH * 4, h: 9, z: TOP, color: {color: '#151515', rough: 0.5}})); + g.add(kit.box({x: HDR.x - 3, y: HDR.y, w: 6, d: PITCH * 4, h: 2.6, z: pz - 2.6, color: {color: '#1d1d1d', rough: 0.5}})); + NAMES.forEach((n, i) => g.add(kit.box({ + x: HDR.x - 0.7, + y: HDR.y + 3 + (i * PITCH) - 0.7, + w: 1.4, + d: 1.4, + h: pz - 2.6 - (TOP + 9), + z: TOP + 9, + color: {color: '#d6b25a', rough: 0.3, metal: 0.85} + }))); + } +}; diff --git a/module-test/components/ldr.js b/module-test/components/ldr.js new file mode 100644 index 00000000000..376232701f4 --- /dev/null +++ b/module-test/components/ldr.js @@ -0,0 +1,136 @@ +import {TOP, soic} from '../lib/parts.js'; +import {PCB, PITCH, boardSvg, carrierPinNames, carrierTraces, holeSvg, rightAngleHeader, smd, stack, text} from '../lib/breakout.js'; + +/* + * LDR light sensor — the blue LM393 photoresistor board (32 × 14 mm, about 2.4 units per mm), + * laid out like the real one but mirrored so its right-angle header faces the RJ11 socket: + * header, mounting hole and the two LEDs by the socket, 201 resistors, the 3362 trimmer over the + * LM393, capacitors and 103 resistors, then a slightly larger LDR standing up, face to the sky. + */ +const MX = 40; +const MY = 5; +const w = 76; +const d = 34; +const PIN_V = [0, 1, 2].map(i => 7 + (i * PITCH)); +const NAMES = ['VCC', 'GND', 'DO']; +const W = MX + w + 8; +const H = MY + d + 13; +const JACK_Y = MY + PIN_V[1]; +const DROP_X = MX - 5; +const TRIM = {u: 39, v: 1, s: 12.4, h: 7}; +const LDR = {u: 71.5, v: 15.6, r: 8.4, legs: 10}; +const CAPS = [[59.6, 3.4], [59.6, 10.6]]; +const RES = [[59.6, 18.4, '103'], [59.6, 25.6, 'EDT']]; +const RES_V = [[29.6, 3.6], [29.6, 24.6]]; +const LEDS = [{u: 16.4, v: 1.8, lit: true}, {u: 16.4, v: 29.4, lit: false}]; + +const svg = boardSvg({ + w, + d, + color: PCB.blue[0], + pins: PIN_V.map(v => ({u: 3.2, v})), + holes: [[72.6, 2.6, 1.6], [72.6, 31.4, 1.6]], + extra: holeSvg(20, 17.4, 3.6) + + text('VCC', 12.6, 7.4, {size: 2.4, weight: 700}) + + '' + + text('DO', 12.6, 23.4, {size: 2.4, weight: 700}) + + // outlines: LEDs, the vertical 201s, caps (rounded), 103s, LDR pads with + and - + LEDS.map(l => ``).join('') + + RES_V.map(([u, v]) => ``).join('') + + CAPS.map(([u, v]) => ``).join('') + + RES.map(([u, v]) => ``).join('') + + `` + + holeSvg(LDR.u, LDR.v - 3.4, 1.4) + holeSvg(LDR.u, LDR.v + 3.4, 1.4) + + text('+', LDR.u - 5.4, LDR.v - 4.6, {size: 3.2, weight: 700}) + text('-', LDR.u - 5.4, LDR.v + 5.4, {size: 3.4, weight: 700}) +}); + +/** 3362 trimmer top: blue body with its markings and the cross-slot rotor. */ +const TRIM_SVG = '' + + '' + + '1 3362 3' + + '' + + '' + + 'P103' + + 'T020'; + +/** Photoresistor face: cream ceramic with the red-orange CdS track. */ +const FACE_SVG = (() => { + let s = ''; + s += ''; + let path = 'M 4.4 5.4'; + for (let i = 0; i < 6; i++) { + const y = 5.4 + (i * 1.84); + path += ` H ${i % 2 ? 4.4 : 15.6} V ${y + 1.84}`; + } + s += ``; + return s; +})(); + +export default { + id: 'ldr', + name: 'LDR Sensor', + category: 'sensor', + defaultPort: 'A1', + spec: { + w: W, + h: H, + jackY: JACK_Y, + label: 'LDR SENSOR', + labelAt: [MX + (w / 2), H - 5], + labelSize: 3.6, + holes: [[6, H - 6]], + silk: carrierTraces(PIN_V.map(v => [DROP_X, MY + v]), JACK_Y) + + carrierPinNames(PIN_V.map(v => [0, MY + v]), NAMES, DROP_X - 2.2) + }, + build (kit, g) { + const m = stack(kit, g, {x: MX, y: MY, w, d, key: 'ldr-3362-module', svg, color: PCB.blue}); + rightAngleHeader(kit, g, m, {mx: MX, my: MY, vs: PIN_V, dropX: DROP_X}); + + LEDS.forEach(l => m.add(kit.box({ + x: l.u, + y: l.v, + w: 5, + d: 2.6, + h: 1.2, + z: TOP, + color: {color: '#e8e5dc', rough: 0.4}, + faces: {t: l.lit ? kit.basic({color: '#ff4a3a'}) : {color: '#f2f6f8', rough: 0.15}} + }))); + RES_V.forEach(([u, v]) => smd(kit, m, u, v, 'R', true)); + m.add(kit.box({ + x: TRIM.u, + y: TRIM.v, + w: TRIM.s, + d: TRIM.s, + h: TRIM.h, + z: TOP, + color: {color: '#2a62c4', rough: 0.45}, + faces: {t: {map: kit.tex.svg('ldr-3362', TRIM.s, TRIM.s, TRIM_SVG, {ppu: 14, base: '#2f6fd6'}), rough: 0.4}} + })); + soic(kit, m, {x: 40, y: 20, w: 11, d: 8}); + CAPS.forEach(([u, v]) => smd(kit, m, u, v, 'C')); + RES.forEach(([u, v]) => smd(kit, m, u, v, 'R')); + + // LDR standing on its legs, face up + [-3.4, 3.4].forEach(o => m.add(kit.box({ + x: LDR.u - 0.45, + y: LDR.v + o - 0.45, + w: 0.9, + d: 0.9, + h: LDR.legs, + z: TOP, + color: {color: '#cfd2d5', rough: 0.3, metal: 0.8}, + shadow: false + }))); + m.add(kit.cylinder({ + cx: LDR.u, + cy: LDR.v, + r: LDR.r, + z0: TOP + LDR.legs, + z1: TOP + LDR.legs + 3.4, + seg: 40, + side: {color: '#e3a66c', rough: 0.5}, + top: {map: kit.tex.svg('ldr-face-big', 20, 20, FACE_SVG, {ppu: 14, base: '#e8b07a'}), rough: 0.3} + })); + } +}; diff --git a/module-test/components/led.js b/module-test/components/led.js new file mode 100644 index 00000000000..66939e53259 --- /dev/null +++ b/module-test/components/led.js @@ -0,0 +1,30 @@ +import {TOP, glowDecal, resistor} from '../lib/parts.js'; + +/** 5 mm LED module: series resistor and a yellow dome with a soft glow. */ +export default { + id: 'led', + name: 'LED', + category: 'output', + defaultPort: 'A2', + spec: {w: 104, h: 48, jackY: 24, label: 'LED', labelAt: [80, 8]}, + build (kit, g, {options}) { + resistor(kit, g, 50, 13); + if (options.on !== false) { + g.add(glowDecal(kit, {cx: 80, cy: 26, size: 44, z: TOP + 0.2, color: '#ffd628', opacity: 0.55})); + } + g.add(kit.lathe({ + key: 'led5mm', + cx: 80, + cy: 26, + z: TOP, + profile: [[0, 0], [7.5, 0], [7.5, 1.2], [6.6, 1.2], [6.6, 8.6], [6.2, 9.8], [5.2, 10.8], [3.6, 11.5], [0, 11.8]], + material: { + color: '#f2c200', + rough: 0.22, + emissive: '#ffb800', + emissiveIntensity: options.on === false ? 0 : 0.4, + opacity: 0.94 + } + })); + } +}; diff --git a/module-test/components/matrix.js b/module-test/components/matrix.js new file mode 100644 index 00000000000..3b86c226e57 --- /dev/null +++ b/module-test/components/matrix.js @@ -0,0 +1,99 @@ +import {TOP, glowDecal} from '../lib/parts.js'; +import {text} from '../lib/breakout.js'; + +/* + * NeoPixel matrix 8 × 8 on its own purple RJ11 carrier: 64 WS2812B (5050) LEDs soldered straight + * onto the board in a grid, each with its 100 nF capacitor, the data line snaking row by row from + * the socket. Shown with a lit heart. + */ +const P = 22; +const N = 8; +const GX = 46; +const GY = 12; +const W = GX + ((N - 1) * P) + 20; +const H = GY + ((N - 1) * P) + 22; +const CY = H / 2; +const HEART = [ + '.##..##.', + '########', + '########', + '########', + '.######.', + '..####..', + '...##...', + '........' +]; +const ON = '#ff3d5a'; + +const cellX = c => GX + (c * P); +const cellY = r => GY + (r * P); + +/** Lit / unlit 5050 tops. */ +const LIT = '' + + `` + + `` + + '' + + ''; +const OFF = '' + + '' + + '' + + '' + + ''; + +const SILK = (() => { + let s = ''; + // serpentine data path: left to right on even rows, right to left on odd rows + let d = `M 26 ${CY} H 32 V ${cellY(0)} H ${cellX(0) - 6}`; + for (let r = 0; r < N; r++) { + const y = cellY(r); + const [a, b] = r % 2 ? [cellX(N - 1), cellX(0)] : [cellX(0), cellX(N - 1)]; + d += ` M ${a} ${y} H ${b}`; + if (r < N - 1) { + const x = r % 2 ? b - 9 : b + 9; + d += ` M ${b} ${y} H ${x} V ${cellY(r + 1)} H ${b}`; + } + } + s += ``; + // 5V / GND rails down the sides + s += ``; + for (let r = 0; r < N; r++) { + for (let c = 0; c < N; c++) { + const x = cellX(c); + const y = cellY(r); + s += ``; + } + } + s += text('DIN', 31, CY + 7, {size: 2.2}); + return s; +})(); + +export default { + id: 'matrix', + name: 'NeoPixel Matrix 8×8', + category: 'output', + defaultPort: 'N01', + spec: { + w: W, + h: H, + jackY: CY, + label: 'NEOPIXEL 8x8', + labelAt: [GX + (((N - 1) * P) / 2), H - 4.6], + labelSize: 3.6, + holes: [[6, 6], [6, H - 6], [W - 6, 6], [W - 6, H - 6]], + silk: SILK + }, + build (kit, g) { + const lit = kit.basic({map: kit.tex.svg('matrix-lit', 12, 12, LIT, {ppu: 12, base: '#f1f1ee'})}); + const off = {map: kit.tex.svg('matrix-off', 12, 12, OFF, {ppu: 12, base: '#f1f1ee'}), rough: 0.35}; + HEART.forEach((row, r) => row.split('').forEach((ch, c) => { + const x = cellX(c); + const y = cellY(r); + const on = ch === '#'; + g.add(kit.box({x: x - 6, y: y - 6, w: 12, d: 12, h: 3.6, z: TOP, color: {color: '#f1f1ee', rough: 0.4}, faces: {t: on ? lit : off}})); + g.add(kit.box({x: x + 6.6, y: y - 7.4, w: 2.2, d: 4.2, h: 1.2, z: TOP, color: '#8a6641'})); + if (on) { + g.add(glowDecal(kit, {cx: x, cy: y, size: 30, z: TOP + 3.8, color: ON, opacity: 0.55})); + } + })); + } +}; diff --git a/module-test/components/mic.js b/module-test/components/mic.js new file mode 100644 index 00000000000..06da7cf1218 --- /dev/null +++ b/module-test/components/mic.js @@ -0,0 +1,159 @@ +import {Group} from 'three'; + +import {PCB_H} from '../lib/board-data.js'; +import {at} from '../lib/kit.js'; +import {BLACK, TOP, passiveTexture} from '../lib/parts.js'; + +/* + * INMP441 I²S MEMS microphone breakout (round black 14 mm board, about 2.4 units per mm) + * stacked on two 3-pin headers on the purple RJ11 carrier. + */ +const W = 80; +const H = 58; + +const R = 16.8; +const D = R * 2; +const MIC = {x: 54 - R, y: 26 - R}; +const SPACER_H = 6; +const NOTCH = 1.8; +const PIN_DU = 6.4; +const ROWS = [{v: R - 5.9, names: ['SCK', 'WS', 'L/R']}, {v: R + 9.2, names: ['SD', 'VDD', 'GND']}]; +const PINS = ROWS.reduce((all, row) => all.concat([-1, 0, 1].map((k, i) => ({u: R + (k * PIN_DU), v: row.v, name: row.names[i]}))), []); +const LID = {u: R + 2 - 5, v: R + 1.3 - 3.8, w: 10, d: 7.6}; + +const GOLD = '#d4b15e'; + +/** Round outline with the two half-round notches at top and bottom (SVG-style points). */ +const OUTLINE = (() => { + const pts = []; + const notches = [[R, 0], [R, D]]; + for (let i = 0; i < 180; i++) { + const a = (i / 180) * Math.PI * 2; + const x = R + (R * Math.cos(a)); + let y = R + (R * Math.sin(a)); + notches.forEach(([nx, ny]) => { + const dx = x - nx; + const dy = y - ny; + if (Math.hypot(dx, dy) < NOTCH) { + // pull the edge point inward onto the notch circle + y = ny + ((ny === 0 ? 1 : -1) * Math.sqrt(Math.max(0, (NOTCH * NOTCH) - (dx * dx)))); + } + }); + pts.push([x, y]); + } + return pts; +})(); + +/** Board top: black mask, gold edge arcs and the six plated holes. */ +const TOP_SVG = (() => { + const arc = (a0, a1, r) => { + const p = a => [R + (r * Math.cos(a * Math.PI / 180)), R + (r * Math.sin(a * Math.PI / 180))]; + const [x0, y0] = p(a0); + const [x1, y1] = p(a1); + return `M ${x0} ${y0} A ${r} ${r} 0 0 1 ${x1} ${y1}`; + }; + return `` + + `` + + `` + + PINS.map(p => ``).join(''); +})(); + +/** Mic lid: brushed metal can with its laser marking. */ +const LID_SVG = `` + + `` + + '' + + '441CYC738'; + +/** Carrier: traces from the RJ11 socket under the two headers, and the title. */ +const CARRIER_SILK = PINS.map((p, i) => { + const x = MIC.x + p.u; + const y = MIC.y + p.v; + const jy = 26 + ((i - 2.5) * 2.2); + return `'; +}).join(''); + +/** INMP441 MEMS microphone breakout on the RJ11 carrier. */ +export default { + id: 'mic', + name: 'INMP441 Microphone', + category: 'sensor', + defaultPort: 'A4', + spec: { + w: W, + h: H, + jackY: 26, + label: 'INMP441 I2S MIC', + labelAt: [52, 52.5], + labelSize: 4, + holes: [[W - 6, 6], [6, H - 6]], + silk: CARRIER_SILK + }, + build (kit, g) { + // two 3-pin header spacers + ROWS.forEach(row => g.add(kit.box({ + x: MIC.x + R - ((PIN_DU * 3) / 2), + y: MIC.y + row.v - 2.6, + w: PIN_DU * 3, + d: 5.2, + h: SPACER_H, + z: TOP, + color: BLACK + }))); + + // the breakout in its own frame: (u, v) from its bounding box corner, z = 0 underneath + const m = new Group(); + const [mx, my] = at(MIC.x, MIC.y); + m.position.set(mx, my, TOP + SPACER_H); + g.add(m); + + m.add(kit.slab({ + x: 0, + y: 0, + w: D, + d: D, + h: PCB_H, + outline: OUTLINE, + top: {map: kit.tex.svg('inmp441-top', D, D, TOP_SVG, {ppu: 14, base: '#141414'}), rough: 0.5}, + side: {color: '#0c0c0c', rough: 0.6} + })); + + // pin tips and solder + PINS.forEach(p => { + m.add(kit.cylinder({cx: p.u, cy: p.v, r: 1.3, z0: TOP, z1: TOP + 0.8, side: {color: '#cfd2d5', rough: 0.3, metal: 0.8}, seg: 16})); + m.add(kit.box({x: p.u - 0.6, y: p.v - 0.6, w: 1.2, d: 1.2, h: 2, z: TOP, color: {color: '#d6b25a', rough: 0.3, metal: 0.85}, shadow: false})); + }); + + // 0603 resistor and capacitor, then the INMP441 itself + m.add(kit.box({ + x: R - 9.6, + y: R + 1.7 - 1.9, + w: 1.8, + d: 3.8, + h: 1, + z: TOP, + color: '#121212', + faces: {t: {map: passiveTexture(kit, 'R', false), rough: 0.45}} + })); + m.add(kit.box({ + x: R - 6.6, + y: R + 1.5 - 1.6, + w: 2, + d: 3.2, + h: 1.2, + z: TOP, + color: '#8a6641', + faces: {t: {map: passiveTexture(kit, 'C', false), rough: 0.45}} + })); + m.add(kit.box({ + x: LID.u, + y: LID.v, + w: LID.w, + d: LID.d, + h: 2.4, + z: TOP, + color: {color: '#b9bdc1', rough: 0.35, metal: 0.8}, + faces: {t: {map: kit.tex.svg('inmp441-lid', LID.w, LID.d, LID_SVG, {ppu: 20, base: '#cfd2d5'}), rough: 0.4, metal: 0.6}} + })); + } +}; diff --git a/module-test/components/models.js b/module-test/components/models.js new file mode 100644 index 00000000000..82a6e0f290a --- /dev/null +++ b/module-test/components/models.js @@ -0,0 +1,43 @@ +import ir from './ir.js'; +import ldr from './ldr.js'; +import flame from './flame.js'; +import water from './water.js'; +import tsop from './tsop.js'; +import irline from './irline.js'; +import mpu6050 from './mpu6050.js'; +import pir from './pir.js'; +import reed from './reed.js'; +import lcd from './lcd.js'; +import rgb from './rgb.js'; +import strip from './strip.js'; +import matrix from './matrix.js'; +import drv8833 from './drv8833.js'; +import bomotor from './bomotor.js'; +import stepper from './stepper.js'; +import relay from './relay.js'; +import relay4 from './relay4.js'; +import buzzer from './buzzer.js'; +import i2samp from './i2samp.js'; +import pump from './pump.js'; +import solenoid from './solenoid.js'; +import btn from './btn.js'; +import dht from './dht.js'; +import led from './led.js'; +import mic from './mic.js'; +import mq2 from './mq2.js'; +import oled from './oled.js'; +import pot from './pot.js'; +import pulse from './pulse.js'; +import rfid from './rfid.js'; +import servo from './servo.js'; +import soil from './soil.js'; +import ultra from './ultra.js'; + +/** Modelled modules, keyed by the studio's module id. Add a file in components/ and list it here. */ +const MODELS = { + led, btn, dht, pot, mq2, mic, pulse, soil, ultra, rfid, oled, servo, + ir, ldr, flame, water, tsop, irline, mpu6050, pir, reed, + lcd, rgb, strip, matrix, drv8833, bomotor, stepper, relay, relay4, buzzer, i2samp, pump, solenoid +}; + +export default MODELS; diff --git a/module-test/components/mosfet.js b/module-test/components/mosfet.js new file mode 100644 index 00000000000..813cc7ad57e --- /dev/null +++ b/module-test/components/mosfet.js @@ -0,0 +1,52 @@ +import {TOP, axial} from '../lib/parts.js'; +import {screwTerminal, smd, text} from '../lib/breakout.js'; + +/* + * TinkerBit MOSFET adapter: purple RJ11 carrier with a logic-level MOSFET (TO-220), gate resistor, + * flyback diode, status LED, a DC jack for the load's supply and a 2-pole OUT screw terminal. + * Shared by the water pump and the solenoid lock. + */ +const W = 92; +const H = 64; +const CY = H / 2; +const TERM_X = W - 22; + +const TAB = ''; +const BODY = '' + + 'IRLZ44N'; + +const adapterSpec = label => ({ + w: W, + h: H, + jackY: CY, + label, + labelAt: [52, H - 4], + labelSize: 3.4, + holes: [[6, 6], [6, H - 6]], + silk: `` + + `` + + text('OUT', TERM_X + 9, 3.8, {size: 2.4}) + text('12V IN', 49, 4.2, {size: 2.2}) + + text('+', TERM_X - 3, CY - 6, {size: 2.8}) + text('-', TERM_X - 3, CY + 6, {size: 2.8}) +}); + +/** The adapter's parts; returns the world point (x, y, z) where the OUT terminal's wires start. */ +const buildAdapter = (kit, g) => { + smd(kit, g, 36, CY + 8); + smd(kit, g, 36, CY - 12); + g.add(kit.box({x: 36, y: CY - 6, w: 4.4, d: 2.4, h: 1.2, z: TOP, color: {color: '#e8e5dc', rough: 0.4}, faces: {t: kit.basic({color: '#30ff60'})}})); + // TO-220 standing: legs, body, metal tab + [-6.1, 0, 6.1].forEach(o => g.add(kit.box({x: 52 + o - 0.7, y: CY + 12, w: 1.4, d: 1.4, h: 6, z: TOP, color: {color: '#cfd2d5', metal: 0.8, rough: 0.3}, shadow: false}))); + g.add(kit.box({x: 40, y: CY + 8, w: 24, d: 11, h: 22, z: TOP + 6, color: {color: '#141416', rough: 0.4}})); + g.add(kit.sideDecal({face: 's', x: 40, y: CY + 8, w: 24, d: 11, z: TOP + 6, h: 22, material: {map: kit.tex.svg('to220-body', 24, 22, BODY, {ppu: 10, base: '#141416'}), rough: 0.4}})); + g.add(kit.box({x: 40, y: CY + 7, w: 24, d: 3, h: 38, z: TOP + 6, color: {color: '#c9ccce', rough: 0.3, metal: 0.85}})); + g.add(kit.sideDecal({face: 'n', x: 40, y: CY + 7, w: 24, d: 3, z: TOP + 28, h: 16, material: {map: kit.tex.svg('to220-tab', 24, 16, TAB, {ppu: 10, base: '#c9ccce'}), rough: 0.3, metal: 0.8}})); + // 1N5819 flyback diode lying flat, DC jack at the north edge + g.add(axial(kit, {x0: 52, x1: 64, cy: CY - 10, cz: TOP + 2.6, r: 2.6, seg: 20, side: {color: '#151515', rough: 0.4}})); + g.add(axial(kit, {x0: 61, x1: 63, cy: CY - 10, cz: TOP + 2.6, r: 2.65, seg: 20, side: {color: '#cfd2d5', rough: 0.4}})); + g.add(kit.box({x: 40, y: 0, w: 22, d: 34, h: 26, z: TOP, color: {color: '#151517', rough: 0.45}})); + g.add(axial(kit, {x0: 40.5, x1: 41, cy: 13, cz: TOP + 13, r: 7, side: {color: '#0b0b0c'}, bottom: {color: '#050505'}})); + screwTerminal(kit, g, {x: TERM_X, y: CY - 12, n: 2, pitch: 12, open: 'e'}); + return {x: TERM_X + 18, y: CY, z: TOP + 13}; +}; + +export {W as ADAPTER_W, H as ADAPTER_H, adapterSpec, buildAdapter}; diff --git a/module-test/components/mpu6050.js b/module-test/components/mpu6050.js new file mode 100644 index 00000000000..3bcc5e81d11 --- /dev/null +++ b/module-test/components/mpu6050.js @@ -0,0 +1,72 @@ +import {TOP, sot23} from '../lib/parts.js'; +import {PCB, boardSvg, carrierTraces, ledSmd, pinColumn, rightAngleHeader, smd, stack, text} from '../lib/breakout.js'; + +/* + * MPU6050 motion sensor on the GY-521 board (21 × 16 mm, 8-pin header along the long edge), + * right-angle header facing the RJ11 socket, its pins bent down into the carrier. + */ +const MX = 40; +const MY = 5; +const w = 38; +const d = 50; +const pins = pinColumn(8, 3, d / 2); +const names = ['VCC', 'GND', 'SCL', 'SDA', 'XDA', 'XCL', 'AD0', 'INT']; +const DROP_X = MX - 5; +const W = MX + w + 6; +const H = MY + d + 12; + +const AXES = '' + + '' + + '' + + text('X', 27.4, 42.2, {size: 2.2}) + text('Y', 21, 37.4, {size: 2.2}); + +const svg = boardSvg({ + w, + d, + color: PCB.blue[0], + holes: [[w - 5, 5, 3.2], [w - 5, d - 5, 3.2]], + pins, + extra: text('GY-521', 22, 5.2, {size: 3, weight: 700}) + AXES + + names.map((n, i) => text(n, 8.6, pins[i].v, {size: 1.8, anchor: 'start'})).join('') +}); + +const CHIP = '' + + 'MPU-6050'; + +export default { + id: 'mpu6050', + name: 'MPU6050 Motion Sensor', + category: 'sensor', + defaultPort: 'I2C', + spec: { + w: W, + h: H, + jackY: MY + (d / 2), + label: 'MPU6050', + labelAt: [MX + (w / 2), H - 5], + labelSize: 3.6, + holes: [[6, H - 6]], + silk: carrierTraces(pins.map(p => [DROP_X, MY + p.v]), MY + (d / 2), {spread: 1.8, width: 0.9}) + }, + build (kit, g) { + const m = stack(kit, g, {x: MX, y: MY, w, d, key: 'mpu6050-ra-module', svg, color: PCB.blue}); + rightAngleHeader(kit, g, m, {mx: MX, my: MY, vs: pins.map(p => p.v), dropX: DROP_X}); + m.add(kit.box({ + x: 20, + y: 13, + w: 9.6, + d: 9.6, + h: 1.4, + z: TOP, + color: {color: '#18191b', rough: 0.45}, + faces: {t: {map: kit.tex.svg('mpu6050-chip', 9.6, 9.6, CHIP, {ppu: 14, base: '#1a1b1d'}), rough: 0.45}} + })); + sot23(kit, m, {x: 26, y: 25}); + ledSmd(kit, m, 15.6, 26, '#ff3030'); + smd(kit, m, 15.6, 30.6); + smd(kit, m, 27.6, 31, 'C', true); + smd(kit, m, 31.4, 31, 'C', true); + smd(kit, m, 31, 13, 'R', true); + } +}; + diff --git a/module-test/components/mq2.js b/module-test/components/mq2.js new file mode 100644 index 00000000000..54b5e083769 --- /dev/null +++ b/module-test/components/mq2.js @@ -0,0 +1,127 @@ +import {Group} from 'three'; + +import {PCB_H} from '../lib/board-data.js'; +import {at} from '../lib/kit.js'; +import {BLACK, TOP, capacitor, meshCan, resistor, smdLed, soic} from '../lib/parts.js'; + +/* + * Generic MQ-2 gas sensor module (blue, 32 × 22 mm, about 2.4 units per mm) stacked on its + * 4-pin header on the purple RJ11 carrier. The module's own parts are built in a sub-group + * whose TOP is the module's surface, so the shared part helpers work unchanged. + */ +const W = 120; +const H = 70; + +const MOD = {x: 36, y: 12, w: 77, d: 53}; +const SPACER_H = 6; +const PITCH = 6.1; +const PIN_V = [0, 1, 2, 3].map(i => (MOD.d / 2) + ((i - 1.5) * PITCH)); +const PIN_NAMES = ['VCC', 'GND', 'DO', 'AO']; +const SENSOR = {u: 52, v: MOD.d / 2, base: 23, mesh: 19, baseH: 8, meshH: 22}; + +const BLUE = '#1f5fa8'; +const SILK = '#f4f4f0'; + +/** Module top: blue mask, white silkscreen, two mounting holes and the header pads. */ +const MODULE_TOP = `` + + [[3.5, 4], [3.5, MOD.d - 4]].map(([x, y]) => ( + `` + )).join('') + + PIN_V.map(v => ``).join('') + + `` + + `` + + 'PWR' + + `DO`; + +/** Carrier: traces from the RJ11 socket to the header pads, the pin names and the title. */ +const CARRIER_SILK = PIN_V.map((v, i) => { + const y = MOD.y + v; + const jy = (H / 2) + ((y - (MOD.y + (MOD.d / 2))) * 0.45) + 3.5; + return `' + + `${PIN_NAMES[i]}`; +}).join(''); + +/** MQ-2 gas sensor: generic module on its header over the RJ11 carrier. */ +export default { + id: 'mq2', + name: 'MQ-2 Gas Sensor', + category: 'sensor', + defaultPort: 'A3', + spec: { + w: W, + h: H, + jackY: MOD.y + (MOD.d / 2), + label: 'MQ-2 GAS SENSOR', + labelAt: [74, 6], + labelSize: 4.4, + holes: [[6, 6], [W - 6, 6], [6, H - 6]], + silk: CARRIER_SILK + }, + build (kit, g) { + // black header spacer between the carrier and the module + g.add(kit.box({ + x: MOD.x, + y: MOD.y + PIN_V[0] - (PITCH / 2), + w: 6, + d: PITCH * 4, + h: SPACER_H, + z: TOP, + color: BLACK + })); + + // the module, in its own frame: (u, v) from its top-left corner, z = 0 at its underside + const m = new Group(); + const [mx, my] = at(MOD.x, MOD.y); + m.position.set(mx, my, TOP + SPACER_H); + g.add(m); + + m.add(kit.slab({ + x: 0, + y: 0, + w: MOD.w, + d: MOD.d, + h: PCB_H, + r: 1.5, + top: {map: kit.tex.svg('mq2-module-top', MOD.w, MOD.d, MODULE_TOP, {ppu: 8, base: BLUE}), rough: 0.55}, + side: {color: '#123d70', rough: 0.6} + })); + + // header pin tips with solder + PIN_V.forEach(v => { + m.add(kit.cylinder({cx: 3, cy: v, r: 1.5, z0: TOP, z1: TOP + 0.9, side: {color: '#cfd2d5', rough: 0.3, metal: 0.8}, seg: 16})); + m.add(kit.box({x: 2.3, y: v - 0.7, w: 1.4, d: 1.4, h: 2.2, z: TOP, color: {color: '#d6b25a', rough: 0.3, metal: 0.85}, shadow: false})); + }); + + // LM393 comparator, load resistor, decoupling capacitor, PWR and DO LEDs + soic(kit, m, {x: 10, y: 5, w: 12, d: 9.6}); + resistor(kit, m, 9, 18.5); + capacitor(kit, m, 23, 25, false); + smdLed(kit, m, 22, 17.5, '#ff3030'); + smdLed(kit, m, 22.5, MOD.d - 10, '#ff3030'); + + // MQ-2: bakelite base and the double stainless gauze cap + m.add(kit.cylinder({ + cx: SENSOR.u, + cy: SENSOR.v, + r: SENSOR.base, + z0: TOP, + z1: TOP + SENSOR.baseH, + seg: 48, + side: {color: '#a8601f', rough: 0.65}, + top: {color: '#bf6f27', rough: 0.6} + })); + meshCan(kit, m, { + key: 'mq2-gauze', + cx: SENSOR.u, + cy: SENSOR.v, + r: SENSOR.mesh, + z0: TOP + SENSOR.baseH, + z1: TOP + SENSOR.baseH + SENSOR.meshH, + pitch: 1.8, + topBase: '#c9cbcd', + topDot: '#3a3c3e' + }); + } +}; diff --git a/module-test/components/oled.js b/module-test/components/oled.js new file mode 100644 index 00000000000..c39912e73e1 --- /dev/null +++ b/module-test/components/oled.js @@ -0,0 +1,131 @@ +import {Group} from 'three'; + +import {PCB_H} from '../lib/board-data.js'; +import {at} from '../lib/kit.js'; +import {BLACK, TOP} from '../lib/parts.js'; + +/* + * 0.96" I2C OLED (SSD1306, 128 × 64) — the common 27 × 27 mm module, about 2.4 units per mm — + * standing on its 4-pin header over a purple RJ11 carrier. The module is turned a quarter turn so + * its header pins face the RJ11 socket (west), next to the carrier's traces. + */ +const MS = 66; +const MOD = {x: 34, y: 8}; +const W = MOD.x + MS + 6; +const H = MOD.y + MS + 8; +const SPACER_H = 6; +const PITCH = 6.1; +const PIN_U = [0, 1, 2, 3].map(i => (MS / 2) + ((i - 1.5) * PITCH)); +const PIN_V = 4; +const PIN_NAMES = ['GND', 'VCC', 'SCL', 'SDA']; +const GLASS = {u: 1, v: 11, w: 64, d: 46, h: 3.4}; +const ACTIVE = {x: 6, y: 3, w: 52, d: 27}; + +const BLUE = '#1c5d8f'; +const SILK = '#f2f4f6'; + +const MODULE_SVG = `` + + [[3.6, 3.6], [MS - 3.6, 3.6], [3.6, MS - 3.6], [MS - 3.6, MS - 3.6]].map(([x, y]) => ( + `` + )).join('') + + PIN_U.map((u, i) => `` + + `${PIN_NAMES[i]}`).join(''); + +/** The lit screen: yellow status band over a blue body, drawn like 128 × 64 pixels. */ +const SCREEN_SVG = (() => { + const yb = ACTIVE.y + (ACTIVE.d / 4); + const px = ACTIVE.w / 128; + const bars = [9, 14, 11, 18, 22, 16, 25, 20, 13, 17, 23, 19].map((hh, i) => { + const x = ACTIVE.x + 31 + (i * 2.1); + const h = hh * 0.42; + return ``; + }).join(''); + return `` + + `` + + `` + + '' + + `12:45` + + `A0 72%` + + `Tinker` + + `Bit` + + `OLED 128x64` + + `${bars}` + + // the FPC tail and driver area along the bottom of the glass + ``; +})(); + +/** Carrier: traces from the RJ11 socket in under the module to the header pads. */ +const CARRIER_SILK = PIN_U.map((u, i) => { + const jy = (H / 2) + ((i - 1.5) * 2.4); + return `'; +}).join(''); + +/** 0.96" SSD1306 OLED on its header over the RJ11 carrier. */ +export default { + id: 'oled', + name: 'OLED Screen', + category: 'output', + defaultPort: 'I2C', + spec: { + w: W, + h: H, + jackY: H / 2, + label: 'OLED I2C', + labelAt: [17, H - 6], + labelSize: 3.8, + holes: [[6, 6]], + silk: CARRIER_SILK + }, + build (kit, g) { + g.add(kit.box({ + x: MOD.x + PIN_V - 3, + y: MOD.y + PIN_U[0] - (PITCH / 2), + w: 6, + d: PITCH * 4, + h: SPACER_H, + z: TOP, + color: BLACK + })); + + // module frame: (u, v) from its own top-left corner, turned so its north (header) edge faces west + const m = new Group(); + const [mx, my] = at(MOD.x, MOD.y + MS); + m.position.set(mx, my, TOP + SPACER_H); + m.rotation.z = Math.PI / 2; + g.add(m); + + m.add(kit.slab({ + x: 0, + y: 0, + w: MS, + d: MS, + h: PCB_H, + r: 1.5, + top: {map: kit.tex.svg('oled-module-top', MS, MS, MODULE_SVG, {ppu: 10, base: BLUE}), rough: 0.55}, + side: {color: '#123f63', rough: 0.6} + })); + + PIN_U.forEach(u => { + m.add(kit.cylinder({cx: u, cy: PIN_V, r: 1.6, z0: TOP, z1: TOP + 0.9, side: {color: '#cfd2d5', rough: 0.3, metal: 0.8}, seg: 16})); + m.add(kit.box({x: u - 0.7, y: PIN_V - 0.7, w: 1.4, d: 1.4, h: 2.2, z: TOP, color: {color: '#d6b25a', rough: 0.3, metal: 0.85}, shadow: false})); + }); + + // adhesive pad, then the glass panel with the lit screen + m.add(kit.box({x: GLASS.u + 2, y: GLASS.v + 2, w: GLASS.w - 4, d: GLASS.d - 4, h: 0.5, z: TOP, color: {color: '#e8e4d8', rough: 0.8}})); + m.add(kit.box({ + x: GLASS.u, + y: GLASS.v, + w: GLASS.w, + d: GLASS.d, + h: GLASS.h, + z: TOP + 0.5, + color: {color: '#2a2d33', rough: 0.2, metal: 0.1}, + faces: {t: kit.basic({map: kit.tex.svg('oled-screen', GLASS.w, GLASS.d, SCREEN_SVG, {ppu: 14, base: '#22252b'})})} + })); + // FPC folding round the bottom edge + m.add(kit.box({x: (MS / 2) - 10, y: GLASS.v + GLASS.d - 0.5, w: 20, d: 2.4, h: GLASS.h + 0.4, z: TOP, color: {color: '#b8792a', rough: 0.4}})); + } +}; diff --git a/module-test/components/pir.js b/module-test/components/pir.js new file mode 100644 index 00000000000..d4be5aab6e6 --- /dev/null +++ b/module-test/components/pir.js @@ -0,0 +1,112 @@ +import {LatheGeometry, Mesh, Vector2} from 'three'; + +import {at} from '../lib/kit.js'; +import {TOP} from '../lib/parts.js'; +import {PCB, boardSvg, carrierPinNames, carrierTraces, pinColumn, stack} from '../lib/breakout.js'; + +/* + * PIR motion sensor (HC-SR501, green 32 × 24 mm): the white Fresnel dome on its square base on top; + * the BISS0001, trimmers and header sit underneath. Header pins face the RJ11 socket. + */ +const MX = 36; +const MY = 5; +const w = 77; +const d = 58; +const pins = pinColumn(3, 3, d / 2); +const names = ['VCC', 'OUT', 'GND']; +const world = pins.map(p => [MX + p.u, MY + p.v]); +const W = MX + w + 5; +const H = MY + d + 12; +const CX = 42; +const CY = d / 2; +const R = 27.6; + +const svg = boardSvg({w, d, color: PCB.green[0], holes: [[4.5, 4.5, 2.6], [w - 4.5, d - 4.5, 2.6]], pins}); + +/** + * Honeycomb Fresnel lens: hexagonal lens cells drawn in a top view of the dome (2R square), each + * shaded bright in the middle and outlined, the way the HC-SR501 lens looks from above. + */ +const honeycomb = kit => kit.tex.canvas('pir-honeycomb', 2 * R, 2 * R, (ctx, cw) => { + const s = cw / (2 * R); + const cell = 3.4 * s; + const hw = Math.sqrt(3) * cell; + ctx.fillStyle = '#e9e9e3'; + ctx.fillRect(0, 0, cw, cw); + const hex = (cx, cy, r) => { + ctx.beginPath(); + for (let k = 0; k < 6; k++) { + const a = (Math.PI / 3) * k + (Math.PI / 6); + ctx[k ? 'lineTo' : 'moveTo'](cx + (r * Math.cos(a)), cy + (r * Math.sin(a))); + } + ctx.closePath(); + }; + for (let row = -1; row * cell * 1.5 < cw + cell; row++) { + const cy = row * cell * 1.5; + for (let col = -1; col * hw < cw + hw; col++) { + const cx = (col * hw) + (row % 2 ? hw / 2 : 0); + const g = ctx.createRadialGradient(cx - (cell * 0.25), cy - (cell * 0.3), cell * 0.05, cx, cy, cell); + g.addColorStop(0, '#ffffff'); + g.addColorStop(0.55, '#f4f4ef'); + g.addColorStop(1, '#d6d6cf'); + hex(cx, cy, cell * 0.97); + ctx.fillStyle = g; + ctx.fill(); + ctx.lineWidth = Math.max(1, s * 0.35); + ctx.strokeStyle = 'rgba(140, 140, 130, 0.75)'; + ctx.stroke(); + } + } +}, {ppu: 14}); + +/** The dome as a lathe whose texture is projected straight down, so the cells read evenly from above. */ +const dome = kit => kit.geo('pir-dome-honeycomb', () => { + const geo = new LatheGeometry(DOME.map(([r, h]) => new Vector2(r, h)), 48); + geo.rotateX(Math.PI / 2); + const pos = geo.attributes.position; + const uv = geo.attributes.uv; + for (let i = 0; i < pos.count; i++) { + uv.setXY(i, (pos.getX(i) / (2 * R)) + 0.5, (pos.getY(i) / (2 * R)) + 0.5); + } + return geo; +}); + +/** Dome profile: a short skirt, then a slightly flattened hemisphere of Fresnel facets. */ +const DOME = (() => { + const p = [[0, 0], [R, 0], [R, 3]]; + for (let i = 1; i <= 12; i++) { + const a = (i / 12) * (Math.PI / 2); + p.push([R * Math.cos(a), 3 + (24 * Math.sin(a))]); + } + return p; +})(); + +export default { + id: 'pir', + name: 'PIR Motion Sensor', + category: 'sensor', + defaultPort: 'J0', + spec: { + w: W, + h: H, + jackY: MY + (d / 2), + label: 'PIR MOTION', + labelAt: [MX + (w / 2), H - 5], + labelSize: 3.6, + holes: [[6, H - 6]], + silk: carrierTraces(world, MY + (d / 2)) + carrierPinNames(world, names, MX - 1.5) + }, + build (kit, g) { + const m = stack(kit, g, {x: MX, y: MY, w, d, key: 'pir-module', svg, color: PCB.green, pins, spacer: 9}); + // square lens frame, then the dome (segmented rings read as the Fresnel facets) + m.add(kit.slab({x: CX - 29, y: CY - 29, w: 58, d: 58, h: 4, z: TOP, r: 3, top: {color: '#f1f1ec', rough: 0.6}, side: {color: '#e4e4de', rough: 0.6}})); + const lens = new Mesh(dome(kit), kit.mat({map: honeycomb(kit), rough: 0.5})); + lens.position.set(...at(CX, CY), TOP + 4); + lens.castShadow = true; + lens.receiveShadow = true; + m.add(lens); + // two orange adjustment pots and the jumper under the board + [[50, 14], [50, 40]].forEach(([u, v]) => m.add(kit.box({x: u, y: v - 4, w: 8, d: 8, h: 4.5, z: -4.5, color: {color: '#e07a1f', rough: 0.5}}))); + m.add(kit.box({x: 64, y: 22, w: 5, d: 12, h: 5, z: -5, color: {color: '#1a1a1a', rough: 0.5}})); + } +}; diff --git a/module-test/components/pot.js b/module-test/components/pot.js new file mode 100644 index 00000000000..72a2514964c --- /dev/null +++ b/module-test/components/pot.js @@ -0,0 +1,134 @@ +import {TOP, axial, ridgeTexture} from '../lib/parts.js'; + +/* + * Generic 16 mm rotary potentiometer (B10K) mounted on its side on the RJ11 carrier: + * shaft horizontal, pointing east away from the socket, with a black knurled knob. + * About 2.4 units per mm. + */ +const W = 100; +const H = 56; +const CY = H / 2; + +const BODY = {x0: 44, x1: 66, r: 19}; +const AXIS_Z = TOP + 2.5 + BODY.r; +const NUT = {x0: 66, x1: 70, r: 12}; +const BUSH = {x0: 66, x1: 78, r: 8.4}; +const SHAFT = {x0: 78, x1: 84, r: 7}; +const KNOB = {x0: 82, x1: 100, r: 15}; +const CAP = {x0: 100, x1: 102.5, r: 13}; +const LUG_Y = [CY - 12, CY, CY + 12]; +const LUG_X = 47; + +const METAL = {color: '#c3c6c9', rough: 0.3, metal: 0.85}; +const SILK = '#f4f4f0'; + +/** Pads, traces from the socket to the three lugs, and pin names. */ +const CARRIER_SILK = LUG_Y.map((y, i) => ( + `' + + `` + + `${['GND', 'OUT', 'VCC'][i]}` +)).join(''); + +/** Knob front: matte black with a white pointer line (points up once mapped onto the cap). */ +const capSvg = color => `` + + '' + + ''; + +/** Bakelite back wafer with the B10K marking. */ +const BACK_SVG = '' + + '' + + 'B10K'; + +/** Rotary potentiometer: metal-shell pot lying on its side with a knurled knob. */ +export default { + id: 'pot', + name: 'Potentiometer', + category: 'input', + defaultPort: 'A1', + spec: { + w: W, + h: H, + jackY: CY, + label: 'POTENTIOMETER 10K', + labelAt: [56, 52], + labelSize: 3.8, + holes: [[W - 6, 6], [W - 6, H - 6]], + silk: CARRIER_SILK + }, + build (kit, g, {options}) { + const knob = options.knobColor || '#161616'; + + // plastic support under the body, then the three solder lugs + g.add(kit.box({x: BODY.x0 + 2, y: CY - 14, w: BODY.x1 - BODY.x0 - 4, d: 28, h: 2.5, z: TOP, color: {color: '#1d1d1d', rough: 0.6}})); + LUG_Y.forEach(y => g.add(kit.box({ + x: LUG_X - 0.7, + y: y - 1.5, + w: 1.4, + d: 3, + h: AXIS_Z - BODY.r + 4 - TOP, + z: TOP, + color: {color: '#d9dbdd', rough: 0.3, metal: 0.8}, + shadow: false + }))); + + // body: brown bakelite back, metal shell, front ring + g.add(axial(kit, { + x0: BODY.x0, + x1: BODY.x0 + 4, + cy: CY, + cz: AXIS_Z, + r: BODY.r - 0.4, + side: {color: '#6e4522', rough: 0.7}, + bottom: {map: kit.tex.svg('pot-back', 38, 38, BACK_SVG, {ppu: 10, base: '#7a4e26'}), rough: 0.7} + })); + g.add(axial(kit, { + x0: BODY.x0 + 4, + x1: BODY.x1, + cy: CY, + cz: AXIS_Z, + r: BODY.r, + seg: 48, + side: METAL, + top: {color: '#aeb2b6', rough: 0.35, metal: 0.85} + })); + + // threaded bushing, hex nut and the bare shaft + g.add(axial(kit, { + x0: BUSH.x0, + x1: BUSH.x1, + cy: CY, + cz: AXIS_Z, + r: BUSH.r, + seg: 32, + side: {map: ridgeTexture(kit, 'thread', Math.PI * 2 * BUSH.r, BUSH.x1 - BUSH.x0, 1.6, '#c9ccce', '#8c9094'), rough: 0.35, metal: 0.85}, + top: METAL + })); + g.add(axial(kit, {x0: NUT.x0, x1: NUT.x1, cy: CY, cz: AXIS_Z, r: NUT.r, seg: 6, side: METAL, top: METAL, bottom: METAL})); + g.add(axial(kit, {x0: SHAFT.x0, x1: SHAFT.x1, cy: CY, cz: AXIS_Z, r: SHAFT.r, seg: 28, side: {color: '#d4d6d8', rough: 0.25, metal: 0.9}})); + + // knurled knob with a slightly smaller front cap carrying the pointer + g.add(axial(kit, { + x0: KNOB.x0, + x1: KNOB.x1, + cy: CY, + cz: AXIS_Z, + r: KNOB.r, + seg: 48, + side: {map: ridgeTexture(kit, `knurl:${knob}`, Math.PI * 2 * KNOB.r, KNOB.x1 - KNOB.x0, 2.2, knob, '#050505'), rough: 0.6}, + top: {color: knob, rough: 0.55}, + bottom: {color: knob, rough: 0.55} + })); + g.add(axial(kit, { + x0: CAP.x0 - 0.5, + x1: CAP.x1, + cy: CY, + cz: AXIS_Z, + r: CAP.r, + seg: 48, + side: {color: options.knobTop || '#222222', rough: 0.45}, + top: {map: kit.tex.svg(`pot-cap:${options.knobTop || '#222222'}`, 26, 26, capSvg(options.knobTop || '#222222'), {ppu: 10, base: '#222222'}), rough: 0.45} + })); + } +}; diff --git a/module-test/components/pulse.js b/module-test/components/pulse.js new file mode 100644 index 00000000000..bb801f90e76 --- /dev/null +++ b/module-test/components/pulse.js @@ -0,0 +1,40 @@ +import {TOP, chip, resistor} from '../lib/parts.js'; + +const heartPath = (x, y, s) => `M${x},${y + (s * 0.3)} C${x},${y - (s * 0.2)} ${x - s},${y - (s * 0.2)} ${x - s},${y + (s * 0.3)} + C${x - s},${y + (s * 0.7)} ${x},${y + s} ${x},${y + (s * 1.1)} C${x},${y + s} ${x + s},${y + (s * 0.7)} ${x + s},${y + (s * 0.3)} + C${x + s},${y - (s * 0.2)} ${x},${y - (s * 0.2)} ${x},${y + (s * 0.3)} Z`; + +const SENSOR_WINDOW = '' + + '' + + ''; + +/** HW-605 heartbeat sensor (MAX30102): optical sensor window, passives and a small regulator. */ +export default { + id: 'pulse', + name: 'Heartbeat HW-605', + category: 'sensor', + defaultPort: 'I2C', + spec: { + w: 84, + h: 48, + jackY: 24, + label: 'HW-605', + labelAt: [56, 42], + silk: `` + }, + build (kit, g) { + g.add(kit.box({ + x: 48, + y: 18, + w: 14, + d: 12, + h: 2.2, + z: TOP, + color: {color: '#121216', rough: 0.4}, + faces: {t: {map: kit.tex.svg('pulse-sensor', 14, 12, SENSOR_WINDOW, {ppu: 12, base: '#0c0c10'}), rough: 0.2}} + })); + resistor(kit, g, 36, 6); + resistor(kit, g, 36, 38); + chip(kit, g, 66, 34, 7, 6, 1.6); + } +}; diff --git a/module-test/components/pump.js b/module-test/components/pump.js new file mode 100644 index 00000000000..904d1e825b0 --- /dev/null +++ b/module-test/components/pump.js @@ -0,0 +1,37 @@ +import {lead} from '../lib/breakout.js'; +import {axial} from '../lib/parts.js'; +import {ADAPTER_W, adapterSpec, buildAdapter} from './mosfet.js'; + +/** Mini submersible water pump (3–6 V) wired to the MOSFET adapter, with a clear outlet tube. */ +const P = {x0: ADAPTER_W + 40, len: 108, r: 29, cy: 32}; + +export default { + id: 'pump', + name: 'Water Pump + MOSFET Adapter', + category: 'output', + defaultPort: 'J0', + spec: adapterSpec('PUMP DRIVER'), + build (kit, g) { + const out = buildAdapter(kit, g); + const {x0, len, r, cy} = P; + const cz = r; + g.add(axial(kit, {x0, x1: x0 + len, cy, cz, r, seg: 48, side: {color: '#1c1d20', rough: 0.45}, top: {color: '#232428', rough: 0.5}, bottom: {color: '#232428', rough: 0.5}})); + // inlet slots ring and the outlet nozzle on the far end + g.add(axial(kit, {x0: x0 + len - 22, x1: x0 + len - 20, cy, cz, r: r + 0.3, seg: 48, side: {color: '#0c0c0e', rough: 0.6}})); + g.add(axial(kit, {x0: x0 + len, x1: x0 + len + 18, cy, cz: cz + 12, r: 4.4, seg: 24, side: {color: '#232428', rough: 0.4}, top: {color: '#0c0c0e'}})); + // clear silicone tube from the nozzle + lead(kit, g, ['#dfeaf0'], () => [ + [x0 + len + 16, cy, cz + 12], + [x0 + len + 40, cy, cz + 12], + [x0 + len + 62, cy - 20, 6], + [x0 + len + 60, cy - 70, 6] + ], 5.2); + g.children[g.children.length - 1].material = kit.mat({color: '#dfeaf0', rough: 0.1, opacity: 0.45}); + lead(kit, g, ['#d0302a', '#151515'], k => [ + [out.x, out.y + (k * 12), out.z], + [out.x + 14, out.y + (k * 6), 6], + [x0 - 18, cy + (k * 4), 1.3], + [x0 + 2, cy + (k * 6), cz] + ], 1.3); + } +}; diff --git a/module-test/components/reed.js b/module-test/components/reed.js new file mode 100644 index 00000000000..a0b2d65b1fc --- /dev/null +++ b/module-test/components/reed.js @@ -0,0 +1,129 @@ +import {TOP, soic} from '../lib/parts.js'; +import {PCB, PITCH, boardSvg, carrierPinNames, carrierTraces, holeSvg, lead, rightAngleHeader, smd, stack, text} from '../lib/breakout.js'; + +/* + * Reed switch module — the blue HW-072 board (32 × 14 mm, about 2.4 units per mm), the same layout as + * the LDR board, mirrored so its right-angle header faces the RJ11 socket: header, mounting hole and + * the two LEDs by the socket, 201 resistors, the 3362 trimmer over the LM393, capacitors and 103 + * resistors, then the green-tinted glass reed held past the end of the board on its long bent leads. + */ +const MX = 40; +const MY = 5; +const w = 76; +const d = 34; +const PIN_V = [0, 1, 2].map(i => 7 + (i * PITCH)); +const NAMES = ['VCC', 'GND', 'DO']; +const W = MX + w + 22; +const H = MY + d + 8; +const JACK_Y = MY + PIN_V[1]; +const DROP_X = MX - 5; +const TRIM = {u: 39, v: 1, s: 12.4, h: 7}; +const PADS = {u: 71.5, v: 15.6}; +const REED = {u: w + 13, v0: 2, v1: 29.2, r: 2.2, cz: TOP + 4}; +const CAPS = [[59.6, 3.4], [59.6, 10.6]]; +const RES = [[59.6, 18.4, '103'], [59.6, 25.6, 'EDT']]; +const RES_V = [[29.6, 3.6], [29.6, 24.6]]; +const LEDS = [{u: 16.4, v: 1.8, lit: true}, {u: 16.4, v: 29.4, lit: false}]; + +const svg = boardSvg({ + w, + d, + color: PCB.blue[0], + pins: PIN_V.map(v => ({u: 3.2, v})), + holes: [[72.6, 2.6, 1.6], [72.6, 31.4, 1.6]], + extra: holeSvg(20, 17.4, 3.6) + + text('HW-072', 33, 31.4, {size: 2, weight: 700}) + + text('VCC', 12.6, 7.4, {size: 2.4, weight: 700}) + + '' + + text('DO', 12.6, 23.4, {size: 2.4, weight: 700}) + + // outlines: LEDs, the vertical 201s, caps (rounded), 103s, reed pads with + and - + LEDS.map(l => ``).join('') + + RES_V.map(([u, v]) => ``).join('') + + CAPS.map(([u, v]) => ``).join('') + + RES.map(([u, v]) => ``).join('') + + `` + + holeSvg(PADS.u, PADS.v - 3.4, 1.4) + holeSvg(PADS.u, PADS.v + 3.4, 1.4) + + text('+', PADS.u - 5.4, PADS.v - 4.6, {size: 3.2, weight: 700}) + text('-', PADS.u - 5.4, PADS.v + 5.4, {size: 3.4, weight: 700}) +}); + +/** 3362 trimmer top: blue body with its markings and the cross-slot rotor. */ +const TRIM_SVG = '' + + '' + + '1 3362 3' + + '' + + '' + + 'P103' + + 'T020'; + +const GLASS = {color: '#9fd8b4', rough: 0.05, opacity: 0.42}; +const REED_METAL = {color: '#8f8a7e', rough: 0.3, metal: 0.8}; + +export default { + id: 'reed', + name: 'Reed Switch', + category: 'sensor', + defaultPort: 'D13', + spec: { + w: W, + h: H, + jackY: JACK_Y, + label: 'REED SWITCH', + labelAt: [MX + (w / 2), H - 3.6], + labelSize: 3.2, + holes: [[6, H - 5]], + silk: carrierTraces(PIN_V.map(v => [DROP_X, MY + v]), JACK_Y) + + carrierPinNames(PIN_V.map(v => [0, MY + v]), NAMES, DROP_X - 2.2) + }, + build (kit, g) { + const m = stack(kit, g, {x: MX, y: MY, w, d, key: 'reed-hw072-module', svg, color: PCB.blue}); + rightAngleHeader(kit, g, m, {mx: MX, my: MY, vs: PIN_V, dropX: DROP_X}); + + LEDS.forEach(l => m.add(kit.box({ + x: l.u, + y: l.v, + w: 5, + d: 2.6, + h: 1.2, + z: TOP, + color: {color: '#e8e5dc', rough: 0.4}, + faces: {t: l.lit ? kit.basic({color: '#ff4a3a'}) : {color: '#f2f6f8', rough: 0.15}} + }))); + RES_V.forEach(([u, v]) => smd(kit, m, u, v, 'R', true)); + m.add(kit.box({ + x: TRIM.u, + y: TRIM.v, + w: TRIM.s, + d: TRIM.s, + h: TRIM.h, + z: TOP, + color: {color: '#2a62c4', rough: 0.45}, + faces: {t: {map: kit.tex.svg('reed-3362', TRIM.s, TRIM.s, TRIM_SVG, {ppu: 14, base: '#2f6fd6'}), rough: 0.4}} + })); + soic(kit, m, {x: 40, y: 20, w: 11, d: 8}); + CAPS.forEach(([u, v]) => smd(kit, m, u, v, 'C')); + RES.forEach(([u, v]) => smd(kit, m, u, v, 'R')); + + // glass reed past the board's end, across it, on two long bent leads from the + / - pads + const {u, v0, v1, r, cz} = REED; + const len = v1 - v0 - 6; + const glass = kit.cylinder({cx: 0, cy: 0, r, z0: -len / 2, z1: len / 2, seg: 20, side: GLASS, top: GLASS, bottom: GLASS}); + glass.rotation.x = Math.PI / 2; + glass.position.set(u, -((v0 + v1) / 2), cz); + m.add(glass); + m.add(kit.box({x: u - 0.5, y: v0 + 5, w: 1, d: 9, h: 0.5, z: cz - 0.2, color: REED_METAL})); + m.add(kit.box({x: u - 0.5, y: v1 - 14, w: 1, d: 9, h: 0.5, z: cz + 0.25, color: REED_METAL})); + lead(kit, m, ['#cfd2d5', '#cfd2d5'], (k, i) => (i === 0 ? [ + [PADS.u, PADS.v - 3.4, TOP], + [PADS.u, PADS.v - 3.4, TOP + 3], + [PADS.u + 5, v0 + 2, cz + 2], + [u, v0 - 1, cz], + [u, v0 + 4, cz] + ] : [ + [PADS.u, PADS.v + 3.4, TOP], + [PADS.u, PADS.v + 3.4, TOP + 3], + [PADS.u + 5, v1 - 2, cz + 2], + [u, v1 + 1, cz], + [u, v1 - 4, cz] + ]), 0.45); + } +}; diff --git a/module-test/components/relay.js b/module-test/components/relay.js new file mode 100644 index 00000000000..eec8aae40d0 --- /dev/null +++ b/module-test/components/relay.js @@ -0,0 +1,79 @@ +import {TOP, sot23} from '../lib/parts.js'; +import {screwTerminal, smd, text} from '../lib/breakout.js'; + +/* + * 1-channel 5 V relay (active-high) built straight onto the purple RJ11 carrier: the blue relay + * cube, NO / COM / NC screw terminal on the far edge, driver transistor, flyback diode, resistors + * and the PWR / IN LEDs. + */ +const W = 140; +const H = 58; +const CY = 26; +const CUBE = {x: 51, y: CY - 18.5, w: 46, d: 37, h: 37}; +const TERM = {x: 104, y: CY - 18}; + +const CUBE_SVG = '' + + '' + + 'SRD-05VDC-SL-C' + + '10A 250VAC 10A 125VAC' + + '10A 30VDC 10A 28VDC' + + '' + + '5VDC'; + +const outline = (x, y, w, d) => ``; + +const SILK = [ + // VCC, IN and GND from the socket to the driver and the coil + ``, + ``, + ``, + // contacts out to the terminal + ``, + outline(CUBE.x, CUBE.y, CUBE.w, CUBE.d), + outline(36, 8, 4.4, 2.4), outline(36, CY + 14, 4.4, 2.4), + text('PWR', 38.2, 5.4, {size: 2}), text('IN', 38.2, CY + 20.4, {size: 2}), + text('VCC', 34.4, CY - 6, {size: 1.9}), text('GND', 34.4, CY + 7.4, {size: 1.9}), + text('NO', TERM.x + 20.4, CY - 12, {size: 2.4, anchor: 'start', weight: 700}), text('COM', TERM.x + 20.4, CY, {size: 2.4, anchor: 'start', weight: 700}), + text('NC', TERM.x + 20.4, CY + 12, {size: 2.4, anchor: 'start', weight: 700}), + text('Q1', 46, CY - 5, {size: 1.9}), text('D1', 46, CY + 9.4, {size: 1.9}) +].join(''); + +export default { + id: 'relay', + name: 'Relay 1-Channel', + category: 'output', + defaultPort: 'J0', + spec: { + w: W, + h: H, + jackY: CY, + label: 'RELAY 5V', + labelAt: [CUBE.x + (CUBE.w / 2), H - 3.8], + labelSize: 3.4, + holes: [[6, H - 5], [W - 6, H - 5]], + silk: SILK + }, + build (kit, g) { + const led = (x, y, color) => g.add(kit.box({x, y, w: 4.4, d: 2.4, h: 1.2, z: TOP, color: {color: '#e8e5dc', rough: 0.4}, faces: {t: kit.basic({color})}})); + led(36, 8, '#ff3030'); + led(36, CY + 14, '#30ff60'); + smd(kit, g, 36, 13); + smd(kit, g, 36, CY + 8.4); + smd(kit, g, 40.4, CY - 1.1, 'R', true); + sot23(kit, g, {x: 43.4, y: CY - 3}); + // 1N4148 flyback diode with its cathode band + g.add(kit.box({x: 42.6, y: CY + 4, w: 7, d: 2.6, h: 2.2, z: TOP, color: {color: '#c46a2a', rough: 0.3}})); + g.add(kit.box({x: 48, y: CY + 4, w: 0.9, d: 2.62, h: 2.22, z: TOP, color: {color: '#1a1a1a', rough: 0.4}})); + g.add(kit.box({ + x: CUBE.x, + y: CUBE.y, + w: CUBE.w, + d: CUBE.d, + h: CUBE.h, + z: TOP, + color: {color: '#1d58b8', rough: 0.35}, + faces: {t: {map: kit.tex.svg('relay-cube', 46, 37, CUBE_SVG, {ppu: 10, base: '#1f5fc4'}), rough: 0.35}} + })); + screwTerminal(kit, g, {x: TERM.x, y: TERM.y, n: 3, pitch: 12, open: 'e'}); + } +}; diff --git a/module-test/components/relay4.js b/module-test/components/relay4.js new file mode 100644 index 00000000000..53d858fa5b0 --- /dev/null +++ b/module-test/components/relay4.js @@ -0,0 +1,103 @@ +import {JACK, PCB_H} from '../lib/board-data.js'; +import {at} from '../lib/kit.js'; +import {TOP, buildJack, sot23} from '../lib/parts.js'; +import {screwTerminal, smd, text} from '../lib/breakout.js'; + +/* + * 4-channel 5 V relay board built straight onto one purple carrier: two RJ11 jacks (relays 1–2 and + * 3–4) and a DC barrel jack for the relay supply along the jack edge, then per channel a driver + * (transistor, flyback diode, resistors, IN LED), the blue relay cube and its NO / COM / NC terminal. + */ +const W = 156; +const H = 196; +const ROW = 46; +const Y0 = 10; +const CH = [0, 1, 2, 3].map(i => Y0 + (i * ROW)); +const CUBE = {x: 70, w: 46, d: 37, h: 37}; +const TERM_X = 126; +const JACK2_Y = 100; +const DC = {x: -2, y: 150, w: 34, d: 22, h: 26}; +const SOCKET_COLOR = '#8d9093'; + +const CUBE_SVG = '' + + '' + + 'SRD-05VDC-SL-C' + + '10A 250VAC 10A 125VAC' + + '10A 30VDC 10A 28VDC' + + '' + + '5VDC'; + +/** DC barrel jack mouth: dark ring with the centre pin. */ +const DC_FACE = '' + + '' + + ''; + +const outline = (x, y, w, d) => ``; + +const SILK = (() => { + let s = ''; + CH.forEach((y, i) => { + const cy = y + (CUBE.d / 2); + const jackY = i < 2 ? 40 : JACK2_Y; + // signal from its jack, coil supply rail, contacts to the terminal + s += ``; + s += ``; + s += outline(CUBE.x, y, CUBE.w, CUBE.d) + outline(48, y + 2, 4.4, 2.4); + s += text(`IN${i + 1}`, 50.2, y - 0.6, {size: 1.9}) + text(`K${i + 1}`, CUBE.x + 2, y - 2.4, {size: 2, anchor: 'start', weight: 700}); + s += text('NO', TERM_X + 20.4, cy - 12, {size: 2.2, anchor: 'start', weight: 700}) + + text('COM', TERM_X + 20.4, cy, {size: 2.2, anchor: 'start', weight: 700}) + + text('NC', TERM_X + 20.4, cy + 12, {size: 2.2, anchor: 'start', weight: 700}); + }); + s += ``; + s += text('IN1 IN2', 15, 62, {size: 2.4, weight: 700}) + text('IN3 IN4', 15, JACK2_Y + 22, {size: 2.4, weight: 700}); + s += text('DC 5V', 15, DC.y + DC.d + 5, {size: 2.6, weight: 700}) + outline(40, DC.y + 26, 4.4, 2.4) + text('PWR', 42.2, DC.y + 32, {size: 1.9}); + return s; +})(); + +export default { + id: 'relay4', + name: '4-Channel Relay', + category: 'output', + defaultPort: 'J0', + spec: { + w: W, + h: H, + jackY: 40, + label: '4-CH RELAY', + labelAt: [CUBE.x + (CUBE.w / 2), H - 4], + labelSize: 3.6, + holes: [[W - 6, 6], [W - 6, H - 6], [6, H - 6]], + silk: SILK + }, + build (kit, g) { + // second RJ11 jack and the DC barrel jack on the jack edge + const jack2 = buildJack(kit, {color: SOCKET_COLOR}); + jack2.position.set(...at(-2 + (JACK.w / 2), JACK2_Y), PCB_H); + g.add(jack2); + g.add(kit.box({x: DC.x, y: DC.y, w: DC.w, d: DC.d, h: DC.h, z: TOP, color: {color: '#151517', rough: 0.45}})); + g.add(kit.sideDecal({face: 'w', x: DC.x, y: DC.y, w: DC.w, d: DC.d, z: TOP, h: DC.h, material: {map: kit.tex.svg('dc-jack-face', 22, 26, DC_FACE, {ppu: 10, base: '#151517'}), rough: 0.4}})); + g.add(kit.box({x: 40, y: DC.y + 26, w: 4.4, d: 2.4, h: 1.2, z: TOP, color: {color: '#e8e5dc', rough: 0.4}, faces: {t: kit.basic({color: '#ff3030'})}})); + + CH.forEach(y => { + // driver: IN LED, resistors, transistor, flyback diode + g.add(kit.box({x: 48, y: y + 2, w: 4.4, d: 2.4, h: 1.2, z: TOP, color: {color: '#e8e5dc', rough: 0.4}, faces: {t: kit.basic({color: '#30ff60'})}})); + smd(kit, g, 48, y + 7); + smd(kit, g, 48, y + 12); + sot23(kit, g, {x: 56, y: y + 15}); + g.add(kit.box({x: 55, y: y + 23, w: 7, d: 2.6, h: 2.2, z: TOP, color: {color: '#c46a2a', rough: 0.3}})); + g.add(kit.box({x: 60.4, y: y + 23, w: 0.9, d: 2.62, h: 2.22, z: TOP, color: {color: '#1a1a1a', rough: 0.4}})); + // relay cube and its terminal + g.add(kit.box({ + x: CUBE.x, + y, + w: CUBE.w, + d: CUBE.d, + h: CUBE.h, + z: TOP, + color: {color: '#1d58b8', rough: 0.35}, + faces: {t: {map: kit.tex.svg('relay-cube', 46, 37, CUBE_SVG, {ppu: 10, base: '#1f5fc4'}), rough: 0.35}} + })); + screwTerminal(kit, g, {x: TERM_X, y: y + (CUBE.d / 2) - 18, n: 3, pitch: 12, open: 'e'}); + }); + } +}; diff --git a/module-test/components/rfid.js b/module-test/components/rfid.js new file mode 100644 index 00000000000..bcf14e3da44 --- /dev/null +++ b/module-test/components/rfid.js @@ -0,0 +1,204 @@ +import {Group} from 'three'; + +import {PCB_H} from '../lib/board-data.js'; +import {at} from '../lib/kit.js'; +import {BLACK, TOP, passiveTexture} from '../lib/parts.js'; + +/* + * RC522 RFID reader (the common blue 40 × 60 mm board, about 2.4 units per mm) on a small + * purple RJ11 carrier. The module stands on its 8-pin header over the carrier, antenna end + * reaching out east past the carrier's edge. + * + * The module is drawn in its own portrait frame (u across 0..MU, v down 0..MV, header at the + * top, like the photo) and turned so the header edge faces the RJ11 socket: x = v, y = MU - u. + */ +const MU = 96; +const MV = 144; +const W = 58; +const H = 60; +const CY = H / 2; +const SPACER_H = 6; +const PITCH = 6.1; +const PIN_U = Array.from({length: 8}, (_, i) => 38.5 + (i * PITCH)); +const PIN_V = 7; +const PIN_NAMES = ['3.3V', 'RST', 'GND', 'IRQ', 'MISO', 'MOSI', 'SCK', 'SDA']; +const PIN_MID = MU - ((PIN_U[0] + PIN_U[7]) / 2); +const MOD = {x: 30, y: CY - PIN_MID}; + +const BLUE = '#1c5d8f'; +const COIL = '#3a86c4'; +const SILK = '#f2f4f6'; + +/** Portrait (u, v) to the module's landscape frame. */ +const P = (u, v) => [v, MU - u]; + +/** Small SMD parts in portrait coords: [ref, kind, u, v, width along u, depth along v]. */ +const PARTS = [ + ['L1', 'R', 8, 12, 7, 4], ['L2', 'R', 8, 18, 7, 4], ['D1', 'R', 8, 24, 7, 4], + ['C1', 'C', 18, 12.5, 3.6, 2], ['C2', 'C', 18, 18.5, 3.6, 2], ['C3', 'C', 18, 24.5, 3.6, 2], + ['C4', 'C', 37, 16, 3.6, 2], ['R1', 'R', 37, 21, 3.6, 2], ['C5', 'C', 37, 26, 3.6, 2], ['R2', 'R', 37, 31, 3.6, 2], + ['R3', 'R', 65, 16, 3.6, 2], ['C12', 'C', 65, 21, 3.6, 2], ['R4', 'R', 65, 26, 3.6, 2], ['C13', 'C', 65, 31, 3.6, 2], + ...['C10', 'C8', 'C6', 'C7', 'C9', 'C11'].map((ref, i) => [ref, 'C', 31 + (i * 6.8), 57, 2.2, 4]) +]; +const CHIP = {u: 47, v: 16.5, s: 12}; +const XTAL = {u: 77, v: 13, w: 13, d: 6}; +const HOLES = [[6.5, 39], [MU - 6.5, 39], [6.5, MV - 7], [MU - 6.5, MV - 7]]; + +/** Module artwork in portrait coordinates. */ +const PORTRAIT_SVG = (() => { + let s = ``; + // antenna: four printed loops, leads to the tuning capacitors, the wave symbol and the name + for (let k = 0; k < 4; k++) { + const o = k * 1.9; + s += ``; + } + s += ``; + const wave = (side, r) => { + const a = 42 * (Math.PI / 180); + const cx = 48; + const cy = 98; + const dx = side * r * Math.cos(a); + const dy = r * Math.sin(a); + return ``; + }; + [5, 10, 15, 20].forEach(r => { + s += wave(1, r) + wave(-1, r); + }); + s += ``; + s += `RFID-RC522'; + // header pads and their names (printed upside-down, as on the board) + PIN_U.forEach((u, i) => { + s += ``; + s += `${PIN_NAMES[i]}`; + }); + // mounting holes + HOLES.forEach(([u, v]) => { + s += ``; + }); + // part outlines and references + PARTS.forEach(([ref, , u, v, pw, pd]) => { + s += ``; + s += `${ref}`; + }); + // QFN pads around the reader chip + for (let i = 0; i < 8; i++) { + const t = CHIP.v + 1.5 + (i * 1.3); + const l = CHIP.u + 1.5 + (i * 1.3); + s += `` + + `` + + `` + + ``; + } + return s; +})(); + +/** Carrier: traces from the RJ11 socket to the header and a small title. */ +const CARRIER_SILK = PIN_U.map((u, i) => { + const y = MOD.y + (MU - u); + const jy = CY + ((i - 3.5) * 2.3); + return `'; +}).join(''); + +/** RC522 RFID reader on its header over the RJ11 carrier. */ +export default { + id: 'rfid', + name: 'RFID RC522', + category: 'sensor', + defaultPort: 'TOP-R', + spec: { + w: W, + h: H, + jackY: CY, + label: 'RC522', + labelAt: [15, 55], + labelSize: 4.2, + holes: [[5, 5]], + silk: CARRIER_SILK + }, + build (kit, g) { + // 8-pin header spacer + g.add(kit.box({ + x: MOD.x + PIN_V - 3, + y: MOD.y + (MU - PIN_U[7]) - (PITCH / 2), + w: 6, + d: PITCH * 8, + h: SPACER_H, + z: TOP, + color: BLACK + })); + + const m = new Group(); + const [mx, my] = at(MOD.x, MOD.y); + m.position.set(mx, my, TOP + SPACER_H); + g.add(m); + + m.add(kit.slab({ + x: 0, + y: 0, + w: MV, + d: MU, + h: PCB_H, + r: 2, + top: { + map: kit.tex.svg('rc522-top', MV, MU, `${PORTRAIT_SVG}`, {ppu: 8, base: BLUE}), + rough: 0.55 + }, + side: {color: '#123f63', rough: 0.6} + })); + + // header pin tips with solder + PIN_U.forEach(u => { + const [x, y] = P(u, PIN_V); + m.add(kit.cylinder({cx: x, cy: y, r: 1.6, z0: TOP, z1: TOP + 0.9, side: {color: '#cfd2d5', rough: 0.3, metal: 0.8}, seg: 16})); + m.add(kit.box({x: x - 0.7, y: y - 0.7, w: 1.4, d: 1.4, h: 2.2, z: TOP, color: {color: '#d6b25a', rough: 0.3, metal: 0.85}, shadow: false})); + }); + + // SMD parts + PARTS.forEach(([, kind, u, v, pw, pd]) => { + const big = pw >= 7; + m.add(kit.box({ + x: v, + y: MU - u - pw, + w: pd, + d: pw, + h: big ? 2.6 : (kind === 'C' ? 1.4 : 1.1), + z: TOP, + color: kind === 'C' ? '#8a6641' : '#121212', + faces: {t: {map: passiveTexture(kit, kind, pd > pw), rough: 0.45}} + })); + }); + + // MFRC522 reader chip (QFN-32) + m.add(kit.box({ + x: CHIP.v, + y: MU - CHIP.u - CHIP.s, + w: CHIP.s, + d: CHIP.s, + h: 1.3, + z: TOP, + color: {color: '#18191b', rough: 0.45}, + faces: {t: {map: kit.tex.svg('rc522-chip', CHIP.s, CHIP.s, `` + + '', {ppu: 10, base: '#1a1b1d'}), rough: 0.45}} + })); + + // 27.12 MHz HC-49S crystal + m.add(kit.slab({ + x: XTAL.v, + y: MU - XTAL.u - XTAL.w, + w: XTAL.d, + d: XTAL.w, + h: 3.6, + z: TOP, + r: XTAL.d / 2, + top: {color: '#d9dbdd', rough: 0.25, metal: 0.9}, + side: {color: '#a9acaf', rough: 0.3, metal: 0.9} + })); + } +}; diff --git a/module-test/components/rgb.js b/module-test/components/rgb.js new file mode 100644 index 00000000000..818a40abe4e --- /dev/null +++ b/module-test/components/rgb.js @@ -0,0 +1,60 @@ +import {TOP, glowDecal} from '../lib/parts.js'; +import {smd, text} from '../lib/breakout.js'; + +/* + * RGB light — a single WS2812B (5050) NeoPixel soldered straight onto the purple RJ11 carrier, + * with its 100 nF decoupling capacitor, shown lit. + */ +const W = 70; +const H = 46; +const CY = H / 2; +const LED = {x: 50, y: CY}; + +/** Lit 5050 top: white body, glowing window with the three dies and the driver chip. */ +const PIXEL = '' + + '' + + '' + + '' + + '' + + '' + + ''; + +export default { + id: 'rgb', + name: 'RGB Light (NeoPixel)', + category: 'output', + defaultPort: 'N01', + spec: { + w: W, + h: H, + jackY: CY, + label: 'RGB LED', + labelAt: [LED.x - 4, H - 3.8], + labelSize: 3.2, + holes: [[W - 6, 6], [W - 6, H - 6]], + silk: `` + + `` + + // 5V, DIN and GND traces from the socket to the LED's pads + `` + + `` + + `` + + '' + + text('DIN', 36, CY + 8.6, {size: 2.2}) + text('5V', 34.4, CY - 13.6, {size: 2}) + text('GND', 35, CY + 15.2, {size: 2}) + + text('C1', LED.x + 11.8, LED.y - 6.2, {size: 2}) + }, + build (kit, g, {options}) { + const color = options.color || '#9b6bff'; + smd(kit, g, LED.x + 9.6, LED.y - 4.2, 'C', true); + g.add(kit.box({ + x: LED.x - 6, + y: LED.y - 6, + w: 12, + d: 12, + h: 3.8, + z: TOP, + color: {color: '#f1f1ee', rough: 0.4}, + faces: {t: kit.basic({map: kit.tex.svg('ws2812-lit', 12, 12, PIXEL, {ppu: 16, base: '#f1f1ee'})})} + })); + g.add(glowDecal(kit, {cx: LED.x, cy: LED.y, size: 52, z: TOP + 4, color, opacity: 0.85})); + } +}; diff --git a/module-test/components/servo.js b/module-test/components/servo.js new file mode 100644 index 00000000000..9b32734615f --- /dev/null +++ b/module-test/components/servo.js @@ -0,0 +1,181 @@ +import {CatmullRomCurve3, Mesh, TubeGeometry, Vector3} from 'three'; + +import {BLACK, TOP} from '../lib/parts.js'; + +/* + * SG90 micro servo (about 2.4 units per mm) sitting on the table next to a small purple RJ11 + * carrier. Its brown / red / orange lead runs to a black 3-pin plug pushed onto a right-angle + * header on the carrier. + */ +const W = 80; +const H = 48; +const CY = H / 2; +const PITCH = 6.1; +const WIRE_COLORS = ['#5a3a22', '#d0302a', '#f28c1c']; +const HEADER = {x: 32, w: 6, h: 6}; +const PLUG = {x: 40, len: 34, h: 6}; + +// SG90: case 22.5 × 12.2 × 22.7 mm, tabs 32.2 mm wide at 16 mm, output shaft 5.9 mm from one end. +const S = {x: 120, w: 54, d: 29.3, h: 54.5}; +S.y = CY - (S.d / 2); +const TAB = {z: 38, h: 6, reach: 11.5}; +const SHAFT_X = S.x + S.w - 14; +const HORN = {len: 84, hub: 12, tip: 6.4, h: 3.6, z: 66}; + +const BODY = {color: '#2f6fd6', rough: 0.35, opacity: 0.86}; +const WHITE = {color: '#f1f2ee', rough: 0.5}; + +/** Two-arm horn outline (SVG-style points in a hub × len box, arms along y). */ +const HORN_OUTLINE = (() => { + const cx = HORN.hub / 2; + const r = HORN.tip / 2; + const pts = []; + for (let i = 0; i <= 8; i++) { + const a = Math.PI + ((Math.PI * i) / 8); + pts.push([cx + (r * Math.cos(a)), r + (r * Math.sin(a))]); + } + pts.push([HORN.hub, HORN.len / 2]); + for (let i = 0; i <= 8; i++) { + const a = (Math.PI * i) / 8; + pts.push([cx + (r * Math.cos(a)), HORN.len - r + (r * Math.sin(a))]); + } + pts.push([0, HORN.len / 2]); + return pts; +})(); + +const HORN_SVG = `` + + [0.13, 0.2, 0.27, 0.34].map(t => [t, 1 - t]).flat() + .map(t => ``).join(''); + +const STICKER_SVG = '' + + '' + + '' + + 'SG90' + + '9g Micro Servo'; + +const CARRIER_SILK = [0, 1, 2].map(i => { + const y = CY + ((i - 1) * PITCH); + const jy = CY + ((i - 1) * 2.4); + return `'; +}).join(''); + +/** One wire of the servo lead as a tube along SVG-style (x, y, z) points. */ +const wire = (kit, points, color) => { + const curve = new CatmullRomCurve3(points.map(([x, y, z]) => new Vector3(x, -y, z)), false, 'centripetal'); + const mesh = new Mesh(new TubeGeometry(curve, 80, 1.35, 8, false), kit.mat({color, rough: 0.5})); + mesh.castShadow = true; + mesh.receiveShadow = true; + return mesh; +}; + +/** SG90 servo with its lead plugged onto the RJ11 carrier. */ +export default { + id: 'servo', + name: 'SG90 Servo', + category: 'output', + defaultPort: 'D13', + spec: { + w: W, + h: H, + jackY: CY, + label: 'SG90 SERVO', + labelAt: [57, 42], + labelSize: 3.6, + holes: [[W - 6, 6]], + silk: CARRIER_SILK + }, + build (kit, g) { + // right-angle header and the 3-pin plug pushed onto it + const span = PITCH * 3; + g.add(kit.box({x: HEADER.x, y: CY - (span / 2), w: HEADER.w, d: span, h: HEADER.h, z: TOP, color: BLACK})); + [0, 1, 2].forEach(i => g.add(kit.box({ + x: HEADER.x + HEADER.w, + y: CY + ((i - 1) * PITCH) - 0.7, + w: 2.4, + d: 1.4, + h: 1.4, + z: TOP + 2.3, + color: {color: '#d6b25a', rough: 0.3, metal: 0.85} + }))); + g.add(kit.box({ + x: PLUG.x, + y: CY - (span / 2), + w: PLUG.len, + d: span, + h: PLUG.h, + z: TOP + 0.3, + color: {color: '#151515', rough: 0.5}, + faces: {t: {map: kit.tex.svg('servo-plug', PLUG.len, span, `` + + '' + + [0, 1, 2].map(i => ``).join(''), + {ppu: 8, base: '#1a1a1a'}), rough: 0.5}} + })); + + // the lead: three wires fan in from the plug, run along the table and up into the servo + const exitX = PLUG.x + PLUG.len; + WIRE_COLORS.forEach((color, i) => { + const k = i - 1; + g.add(wire(kit, [ + [exitX - 2, CY + (k * PITCH), TOP + 3.3], + [exitX + 6, CY + (k * 4.2), TOP + 2.6], + [exitX + 16, CY + 6 + (k * 2.9), 1.4], + [S.x - 22, CY + 10 + (k * 2.9), 1.4], + [S.x - 8, CY + 3 + (k * 2.9), 5], + [S.x + 1, CY + (k * 2.9), 9] + ], color)); + }); + + // case: lower body, tab plate, upper body, then the gear top + g.add(kit.box({x: S.x, y: S.y, w: S.w, d: S.d, h: TAB.z, z: 0, color: BODY})); + g.add(kit.box({x: S.x - TAB.reach, y: S.y, w: S.w + (TAB.reach * 2), d: S.d, h: TAB.h, z: TAB.z, color: BODY})); + g.add(kit.box({x: S.x, y: S.y, w: S.w, d: S.d, h: S.h - TAB.z - TAB.h, z: TAB.z + TAB.h, color: BODY})); + [S.x - (TAB.reach / 2) - 0.5, S.x + S.w + (TAB.reach / 2) + 0.5].forEach(cx => g.add(kit.cylinder({ + cx, + cy: CY, + r: 2.2, + z0: TAB.z - 0.05, + z1: TAB.z + TAB.h + 0.08, + side: {color: '#0d1b33', rough: 0.6}, + seg: 16 + }))); + g.add(kit.sideDecal({ + face: 's', + x: S.x, + y: S.y, + w: S.w, + d: S.d, + z: 0, + h: TAB.z, + material: {map: kit.tex.svg('sg90-sticker', 54, 54.5, STICKER_SVG, {ppu: 8, base: '#1d4fa8'}), rough: 0.5} + })); + g.add(kit.cylinder({cx: SHAFT_X, cy: CY, r: 14, z0: S.h, z1: S.h + 9.6, seg: 40, side: BODY, top: BODY})); + g.add(kit.cylinder({cx: S.x + 18, cy: CY, r: 6.5, z0: S.h, z1: S.h + 5, seg: 28, side: BODY, top: BODY})); + + // output spline, horn and its hub screw + g.add(kit.cylinder({cx: SHAFT_X, cy: CY, r: 2.6, z0: S.h + 9.6, z1: HORN.z, seg: 18, side: WHITE})); + g.add(kit.slab({ + x: SHAFT_X - (HORN.hub / 2), + y: CY - (HORN.len / 2), + w: HORN.hub, + d: HORN.len, + h: HORN.h, + z: HORN.z, + outline: HORN_OUTLINE, + top: {map: kit.tex.svg('sg90-horn', HORN.hub, HORN.len, HORN_SVG, {ppu: 10, base: '#f1f2ee'}), rough: 0.5}, + side: WHITE + })); + g.add(kit.cylinder({ + cx: SHAFT_X, + cy: CY, + r: 5, + z0: HORN.z, + z1: HORN.z + HORN.h + 1.4, + seg: 28, + side: WHITE, + top: {map: kit.tex.svg('sg90-hub', 10, 10, '' + + '', + {ppu: 12, base: '#f1f2ee'}), rough: 0.4} + })); + } +}; diff --git a/module-test/components/soil.js b/module-test/components/soil.js new file mode 100644 index 00000000000..97342984467 --- /dev/null +++ b/module-test/components/soil.js @@ -0,0 +1,118 @@ +import {TOP, axial, passiveTexture, soic, sot23} from '../lib/parts.js'; + +/* + * Capacitive soil moisture sensor v1.2 on the purple house PCB: RJ11 at the head, the 555 + * oscillator circuit, the white insertion line, then the probe with its capacitive sensing + * trace (a U-shaped electrode and centre finger under the solder mask) tapering to a point. + */ +const W = 190; +const H = 44; +const LINE_X = 64; +const TIP = 176; +const SILK = '#f4f4f0'; + +/** Corner arc as SVG-style points (angles in degrees, y down). */ +const arc = (cx, cy, r, a0, a1, n = 5) => Array.from({length: n + 1}, (_, i) => { + const a = (a0 + (((a1 - a0) * i) / n)) * (Math.PI / 180); + return [cx + (r * Math.cos(a)), cy + (r * Math.sin(a))]; +}); + +/** Board outline: rounded head at the socket end, long probe tapering to a blunt point. */ +const OUTLINE = [ + ...arc(3, 3, 3, 180, 270), + [TIP, 0], + [W, (H / 2) - 1.5], + [W, (H / 2) + 1.5], + [TIP, H], + ...arc(3, H - 3, 3, 90, 180) +]; + +/** Two small SMD passives per row: [ref, kind, x, y, label side]. */ +const PASSIVES = [ + ['C5', 'C', 31, 4, 'e'], ['C6', 'C', 31, 9, 'e'], ['R3', 'R', 31, 33, 'e'], ['R4', 'R', 31, 38, 'e'], + ['R2', 'R', 44, 33, 'n'], + ['C1', 'C', 55, 4, 'w'], ['C2', 'C', 55, 9, 'w'], ['R1', 'R', 55, 16, 'w'], ['C3', 'C', 55, 31, 'w'], ['C4', 'C', 55, 37, 'w'] +]; +const PART = {w: 4, d: 2}; +const D1 = {x: 55, y: 22, w: 4.4}; + +const silkText = (t, x, y, anchor = 'middle', size = 2) => ( + `${t}` +); + +/** The capacitive sensing electrode: copper under purple mask shows as a raised, lighter band. */ +const electrode = (d, width) => `' + + ``; + +const SILK_SVG = (() => { + let s = ''; + // ground pour edge around the probe, then the U electrode and its centre finger + s += `'; + s += electrode(`M ${LINE_X + 6} 9 H 158 A 13 13 0 0 1 158 35 H ${LINE_X + 6}`, 5); + s += electrode(`M ${LINE_X + 10} 22 H 152`, 3.2); + // insertion line + s += ``; + // head: traces, part outlines and reference designators + s += ''; + PASSIVES.forEach(([ref, , x, y, side]) => { + s += ``; + if (side === 'e') { + s += silkText(ref, x + PART.w + 1.3, y + (PART.d / 2), 'start'); + } else if (side === 'w') { + s += silkText(ref, x - 1.3, y + (PART.d / 2), 'end'); + } else { + s += silkText(ref, x + (PART.w / 2), y - 2.2); + } + }); + s += ``; + s += silkText('D1', D1.x - 1.3, D1.y, 'end'); + s += silkText('U2', 46, 2.2) + silkText('U1', 39.5, 15.5, 'end'); + [[62, 6], [62, 38], [36, 24]].forEach(([x, y]) => { + s += ``; + }); + return s; +})(); + +/** + * Capacitive soil moisture sensor v1.2: socket at the head, TLC555 timer and regulator, + * the capacitive sensing trace along the probe, printed title and the white insertion line. + */ +export default { + id: 'soil', + name: 'Capacitive Soil Moisture', + category: 'sensor', + defaultPort: 'A2', + spec: { + w: W, + h: H, + jackY: H / 2, + label: 'Capacitive Soil\nMoisture Sensor v1.2', + labelAt: [116, 22], + labelSize: 7.6, + outline: OUTLINE, + holes: [], + silk: SILK_SVG + }, + build (kit, g) { + soic(kit, g, {x: 41, y: 17, w: 10, d: 8}); + sot23(kit, g, {x: 43, y: 4.2}); + PASSIVES.forEach(([, kind, x, y]) => g.add(kit.box({ + x, + y, + w: PART.w, + d: PART.d, + h: kind === 'C' ? 1.4 : 1.1, + z: TOP, + color: kind === 'C' ? '#8a6641' : '#121212', + faces: {t: {map: passiveTexture(kit, kind, true), rough: 0.45}} + }))); + // D1: orange glass MiniMELF diode with its cathode band + g.add(axial(kit, {x0: D1.x, x1: D1.x + D1.w, cy: D1.y, cz: TOP + 1.1, r: 1.1, seg: 16, side: {color: '#c8642a', rough: 0.2, opacity: 0.92}})); + g.add(axial(kit, {x0: D1.x + 0.6, x1: D1.x + 1.3, cy: D1.y, cz: TOP + 1.1, r: 1.15, seg: 16, side: {color: '#1a1a1a', rough: 0.4}})); + } +}; diff --git a/module-test/components/solenoid.js b/module-test/components/solenoid.js new file mode 100644 index 00000000000..3811c9da43b --- /dev/null +++ b/module-test/components/solenoid.js @@ -0,0 +1,40 @@ +import {lead} from '../lib/breakout.js'; +import {axial} from '../lib/parts.js'; +import {ADAPTER_W, adapterSpec, buildAdapter} from './mosfet.js'; + +/* + * 12 V solenoid door lock (54 × 41 × 28 mm) wired to the MOSFET adapter: open steel frame, the + * tape-wrapped coil and the slanted latch bolt sticking out of the far end. + */ +const L = {x: ADAPTER_W + 46, y: 32 - 49, w: 130, d: 98, h: 67}; +const ZINC = {color: '#c7c9c4', rough: 0.35, metal: 0.8}; +const BOLT = [[0, 0], [30, 0], [44, 34], [0, 34]]; + +export default { + id: 'solenoid', + name: 'Solenoid Lock 12V + MOSFET Adapter', + category: 'output', + defaultPort: 'J0', + spec: adapterSpec('LOCK DRIVER'), + build (kit, g) { + const out = buildAdapter(kit, g); + const {x, y, w, d, h} = L; + // frame: base plate, two end walls, and the side flange with its mounting holes + g.add(kit.box({x, y, w, d, h: 3, z: 0, color: ZINC})); + g.add(kit.box({x, y, w: 4, d, h, z: 0, color: ZINC})); + g.add(kit.box({x: x + w - 4, y, w: 4, d, h, z: 0, color: ZINC})); + g.add(kit.box({x, y: y + d - 4, w, d: 4, h: h - 10, z: 0, color: ZINC})); + [x + 24, x + w - 24].forEach(cx => g.add(kit.cylinder({cx, cy: y + d - 2, r: 4, z0: h - 22, z1: h - 18, seg: 16, side: {color: '#0d0f12'}}))); + // coil wrapped in yellow-black tape, plunger + g.add(axial(kit, {x0: x + 10, x1: x + 90, cy: y + (d / 2) - 4, cz: 35, r: 30, seg: 40, side: {color: '#1d1d1f', rough: 0.6}, top: {color: '#e8c33a', rough: 0.6}, bottom: {color: '#e8c33a', rough: 0.6}})); + g.add(axial(kit, {x0: x + 90, x1: x + w - 4, cy: y + (d / 2) - 4, cz: 35, r: 9, seg: 24, side: ZINC})); + // slanted latch bolt out of the far wall + g.add(kit.slab({x: x + w, y: y + (d / 2) - 21, w: 44, d: 34, h: 26, z: 22, outline: BOLT, top: ZINC, side: ZINC})); + lead(kit, g, ['#d0302a', '#151515'], k => [ + [out.x, out.y + (k * 12), out.z], + [out.x + 14, out.y + (k * 6), 6], + [x - 14, 32 + (k * 4), 1.3], + [x + 6, 32 + (k * 6), 20] + ], 1.3); + } +}; diff --git a/module-test/components/stepper.js b/module-test/components/stepper.js new file mode 100644 index 00000000000..d21cd456c10 --- /dev/null +++ b/module-test/components/stepper.js @@ -0,0 +1,93 @@ +import {TOP} from '../lib/parts.js'; +import {PCB, boardSvg, carrierPinNames, carrierTraces, lead, ledSmd, pinColumn, stack, text} from '../lib/breakout.js'; + +/* + * Stepper 28BYJ-48 + ULN2003: the green ULN2003 driver board (35 × 32 mm) stacked on the purple + * RJ11 carrier, and the 28 mm stepper on the table, its 5-wire lead in the board's white socket. + */ +const MX = 36; +const MY = 5; +const w = 84; +const d = 77; +const pins = pinColumn(6, 3, d / 2); +const names = ['IN1', 'IN2', 'IN3', 'IN4', '-', '+']; +const world = pins.map(p => [MX + p.u, MY + p.v]); +const W = MX + w + 5; +const H = MY + d + 12; +const WIRES = ['#2e6fd8', '#ff8fb6', '#f2d21b', '#f28c1c', '#d0302a']; +const MOTOR = {cx: W + 70, cy: H / 2, r: 33.6, h: 45.6}; + +const svg = boardSvg({ + w, + d, + color: PCB.green[0], + holes: [[5, 5, 3.4], [w - 5, 5, 3.4], [5, d - 5, 3.4], [w - 5, d - 5, 3.4]], + pins, + extra: ['A', 'B', 'C', 'D'].map((n, i) => text(n, 64, 13 + (i * 8), {size: 2.4})).join('') + + text('ULN2003', 36, d - 6, {size: 2.8, weight: 700}) + text('5-12V', 12, d - 12, {size: 2}) +}); + +const DIP = '' + + 'ULN2003APG'; + +const MOTOR_TOP = '' + + '' + + '28BYJ-48 5VDC'; + +export default { + id: 'stepper', + name: 'Stepper 28BYJ-48 + ULN2003', + category: 'output', + defaultPort: 'STEPPER1', + spec: { + w: W, + h: H, + jackY: MY + (d / 2), + label: 'STEPPER', + labelAt: [MX + (w / 2), H - 5], + labelSize: 3.6, + holes: [[6, H - 6]], + silk: carrierTraces(world, MY + (d / 2), {spread: 1.8, width: 0.9}) + carrierPinNames(world, names, MX - 1.5) + }, + build (kit, g) { + const m = stack(kit, g, {x: MX, y: MY, w, d, key: 'uln2003-module', svg, color: PCB.green, pins}); + // DIP-16 with legs, A–D LEDs, jumper and the white 5-pin motor socket + for (let i = 0; i < 8; i++) { + [24, 42].forEach(v => m.add(kit.box({x: 15 + (i * 6.1), y: v - 1, w: 1.4, d: 3, h: 3, z: TOP, color: {color: '#cfd2d5', rough: 0.3, metal: 0.8}, shadow: false}))); + } + m.add(kit.box({ + x: 13, + y: 25.5, + w: 46, + d: 15, + h: 8, + z: TOP + 1.2, + color: {color: '#18191b', rough: 0.45}, + faces: {t: {map: kit.tex.svg('uln2003-dip', 46, 15, DIP, {ppu: 10, base: '#1a1b1d'}), rough: 0.45}} + })); + [0, 1, 2, 3].forEach(i => m.add(kit.cylinder({cx: 70, cy: 13 + (i * 8), r: 3, z0: TOP, z1: TOP + 4, seg: 20, side: {color: '#ff3030', rough: 0.2, opacity: 0.85}, top: {color: '#ff4a4a', rough: 0.2}}))); + ledSmd(kit, m, 14, d - 18, '#ff3030'); + m.add(kit.box({x: 6, y: 50, w: 6, d: 12.2, h: 7, z: TOP, color: {color: '#1a1a1a', rough: 0.5}})); + m.add(kit.box({x: w - 22, y: d - 34, w: 14, d: 30, h: 17, z: TOP, color: {color: '#f2f0ea', rough: 0.5}})); + + // the stepper: can, mounting ears, gear boss and shaft, blue wire box + const {cx, cy, r, h} = MOTOR; + g.add(kit.cylinder({cx, cy, r, z0: 0, z1: h, seg: 56, side: {color: '#c6c9cc', rough: 0.3, metal: 0.85}, top: {map: kit.tex.svg('28byj-top', 68, 68, MOTOR_TOP, {ppu: 6, base: '#cfd2d5'}), rough: 0.3, metal: 0.7}})); + g.add(kit.slab({x: cx - 50, y: cy - 8.5, w: 100, d: 17, h: 1.6, z: h - 1.6, r: 8.4, top: {color: '#c6c9cc', rough: 0.3, metal: 0.85}, side: {color: '#b3b6b9', metal: 0.8}})); + [-42, 42].forEach(o => g.add(kit.cylinder({cx: cx + o, cy, r: 2.6, z0: h - 1.65, z1: h + 0.05, seg: 16, side: {color: '#0d0f12', rough: 0.6}}))); + g.add(kit.cylinder({cx, cy: cy - 19, r: 11, z0: h, z1: h + 3.6, seg: 32, side: {color: '#c6c9cc', rough: 0.3, metal: 0.85}})); + g.add(kit.cylinder({cx, cy: cy - 19, r: 3, z0: h + 3.6, z1: h + 27, seg: 20, side: {color: '#e6e8ea', rough: 0.2, metal: 0.9}})); + g.add(kit.box({x: cx - 17.5, y: cy + r - 6, w: 35, d: 14, h: 40, z: 0, color: {color: '#2557c9', rough: 0.4}})); + + // 5-wire lead from the blue box into the board's socket + const sx = MX + w - 15; + const sy = MY + d - 19; + lead(kit, g, WIRES, k => [ + [cx + (k * 4.6), cy + r + 8, 22], + [cx + (k * 4.4), cy + r + 26, 2.2], + [W + 10, sy + 26 + (k * 2.8), 1.3], + [sx + 12, sy + 20 + (k * 3), 18], + [sx + 1, sy + (k * 5.6), TOP + 6 + 17] + ], 1.1); + } +}; diff --git a/module-test/components/strip.js b/module-test/components/strip.js new file mode 100644 index 00000000000..1ec1030aaf6 --- /dev/null +++ b/module-test/components/strip.js @@ -0,0 +1,79 @@ +import {TOP, glowDecal} from '../lib/parts.js'; +import {smd, text} from '../lib/breakout.js'; + +/* + * NeoPixel bar — ten WS2812B (5050) NeoPixels soldered straight onto a long purple RJ11 carrier, + * each with its 100 nF capacitor, the data line chained DIN → DOUT from the socket through all ten. + * Shown lit in a rainbow. + */ +const PITCH = 26; +const N = 10; +const X0 = 44; +const W = X0 + ((N - 1) * PITCH) + 18; +const H = 44; +const CY = 19; +const RAINBOW = ['#ff3b3b', '#ff8a2a', '#ffd23a', '#9cff3a', '#2aff7a', '#2affe0', '#2aa8ff', '#4a5bff', '#a24aff', '#ff4ad6']; + +/** Lit 5050 top in a given colour: white body, glowing window with the three dies and driver chip. */ +const pixelSvg = (c, i) => '' + + `` + + `` + + `` + + '' + + '' + + ''; + +const SILK = (() => { + let s = ''; + // 5V and GND rails along the top and bottom, the data line hopping from pixel to pixel + s += ``; + s += ``; + s += ``; + for (let i = 0; i < N; i++) { + const x = X0 + (i * PITCH); + s += ``; + s += ``; + s += ``; + if (i < N - 1) { + s += ``; + } + s += text(String(i + 1), x, CY + 12.4, {size: 2.2}); + } + s += ''; + s += text('DIN', 33, 28.6, {size: 2}) + text('5V', 36.4, 4, {size: 2}) + text('GND', 37.4, 35.6, {size: 2}); + return s; +})(); + +export default { + id: 'strip', + name: 'NeoPixel Bar (10 LEDs)', + category: 'output', + defaultPort: 'N01', + spec: { + w: W, + h: H, + jackY: CY, + label: 'NEOPIXEL x10', + labelAt: [X0 + (((N - 1) * PITCH) / 2), H - 3.6], + labelSize: 3.4, + holes: [[6, H - 5], [W - 6, 6], [W - 6, H - 6]], + silk: SILK + }, + build (kit, g) { + RAINBOW.forEach((c, i) => { + const x = X0 + (i * PITCH); + smd(kit, g, x + 7.4, CY - 9.6, 'C', true); + g.add(kit.box({ + x: x - 6, + y: CY - 6, + w: 12, + d: 12, + h: 3.8, + z: TOP, + color: {color: '#f1f1ee', rough: 0.4}, + faces: {t: kit.basic({map: kit.tex.svg(`neopixel-lit-${i}`, 12, 12, pixelSvg(c, i), {ppu: 14, base: '#f1f1ee'})})} + })); + g.add(glowDecal(kit, {cx: x, cy: CY, size: 40, z: TOP + 4, color: c, opacity: 0.75})); + }); + } +}; diff --git a/module-test/components/tsop.js b/module-test/components/tsop.js new file mode 100644 index 00000000000..63ffb50cdb3 --- /dev/null +++ b/module-test/components/tsop.js @@ -0,0 +1,70 @@ +import {TOP, axial} from '../lib/parts.js'; +import {PCB, PITCH, boardSvg, carrierPinNames, carrierTraces, holeSvg, rightAngleHeader, smd, stack, text} from '../lib/breakout.js'; + +/* + * TSOP IR receiver — the black KY-022 style board with a VS1838B (about 2.4 units per mm): right-angle + * header (S, +, −) facing the RJ11 socket, the signal LED and its resistor, and the receiver standing + * on its legs at the far edge with the lens bump looking forward. + */ +const MX = 40; +const MY = 6; +const w = 48; +const d = 36; +const PIN_V = [0, 1, 2].map(i => (d / 2) + ((i - 1) * PITCH)); +const NAMES = ['S', '+', '-']; +const W = MX + w + 6; +const H = MY + d + 13; +const JACK_Y = MY + (d / 2); +const DROP_X = MX - 5; +const RX = {u: 34, w: 9, d: 14, h: 17, legs: 5}; + +const svg = boardSvg({ + w, + d, + color: PCB.black[0], + holes: [[18, 5, 2.8]], + pins: PIN_V.map(v => ({u: 3.2, v})), + extra: NAMES.map((n, i) => text(n, 9.2, PIN_V[i], {size: 2.6, weight: 700})).join('') + + '' + + '' + + [-2.54, 0, 2.54].map(o => holeSvg(RX.u + 3.2, (d / 2) + o, 1.1)).join('') + + text('IR', 26, d - 4, {size: 3, weight: 700}) +}); + +export default { + id: 'tsop', + name: 'TSOP', + category: 'sensor', + defaultPort: 'N01', + spec: { + w: W, + h: H, + jackY: JACK_Y, + label: 'TSOP', + labelAt: [MX + (w / 2), H - 5], + labelSize: 3.6, + holes: [[6, H - 6]], + silk: carrierTraces(PIN_V.map(v => [DROP_X, MY + v]), JACK_Y) + + carrierPinNames(PIN_V.map(v => [0, MY + v]), NAMES, DROP_X - 2.2) + }, + build (kit, g) { + const m = stack(kit, g, {x: MX, y: MY, w, d, key: 'tsop-ky022-module', svg, color: PCB.black}); + rightAngleHeader(kit, g, m, {mx: MX, my: MY, vs: PIN_V, dropX: DROP_X}); + smd(kit, m, 15, 12); + m.add(kit.box({x: 15, y: 26, w: 4.8, d: 2.4, h: 1.2, z: TOP, color: {color: '#e8e5dc', rough: 0.4}, faces: {t: kit.basic({color: '#ff4a3a'})}})); + + // VS1838B: legs, black epoxy body, lens bump on the front (east) face + [-2.54, 0, 2.54].forEach(o => m.add(kit.box({ + x: RX.u + 2.8, + y: (d / 2) + o - 0.4, + w: 0.8, + d: 0.8, + h: RX.legs, + z: TOP, + color: {color: '#cfd2d5', rough: 0.3, metal: 0.8}, + shadow: false + }))); + m.add(kit.box({x: RX.u, y: (d / 2) - (RX.d / 2), w: RX.w, d: RX.d, h: RX.h, z: TOP + RX.legs, color: {color: '#141519', rough: 0.35}})); + m.add(axial(kit, {x0: RX.u + RX.w, x1: RX.u + RX.w + 2.6, cy: d / 2, cz: TOP + RX.legs + 11, r: 3.8, seg: 24, side: {color: '#141519', rough: 0.2}, top: {color: '#22232a', rough: 0.12}})); + } +}; diff --git a/module-test/components/ultra.js b/module-test/components/ultra.js new file mode 100644 index 00000000000..39a7e01dbce --- /dev/null +++ b/module-test/components/ultra.js @@ -0,0 +1,148 @@ +import {BLACK, TOP, capacitor} from '../lib/parts.js'; + +/* + * HC-SR04 ultrasonic sensor on a TinkerBit RJ11 carrier. + * The real blue HC-SR04 board (45 × 20 mm, about 2.4 units per mm) stands upright, soldered + * straight onto the purple carrier, transducers facing east, away from the RJ11 socket. + */ +const W = 92; +const H = 116; + +// HC-SR04 board: vertical plane at x = HC.x, spanning y HC.y .. HC.y + HC.w, HC.h tall. +const HC = {x: 56, y: 4, w: 108, h: 48, t: 2}; +const FRONT = HC.x + HC.t; +const SOCKET = {w: 6}; +const Z_BOT = TOP; +const Z_TOP = Z_BOT + HC.h; +const CAN = {r: 19, len: 29, v: 24, u: [23, 85]}; +const PITCH = 6.1; +const PIN_U = [0, 1, 2, 3].map(i => 54 + ((i - 1.5) * PITCH)); +const PIN_NAMES = ['Vcc', 'Trig', 'Echo', 'Gnd']; + +/** Face coordinates (u across from the left as seen from the front, v down from the top) to world y / z. */ +const yOf = u => HC.y + HC.w - u; +const zOf = v => Z_TOP - v; + +const HC_BLUE = '#1f5fa8'; +const HC_EDGE = '#123d70'; + +const FRONT_SVG = `` + + [[3.5, 3.5], [HC.w - 3.5, 3.5], [3.5, HC.h - 3.5], [HC.w - 3.5, HC.h - 3.5]].map(([x, y]) => ( + `` + )).join('') + + CAN.u.map(u => ``).join('') + + '' + + `TR` + + 'HC-SR04' + + PIN_U.map((u, i) => `${PIN_NAMES[i]}`).join('') + + ''; + +const BACK_SVG = `` + + '' + + PIN_U.map(u => ``).join(''); + +/** Woven gauze over the transducer mouth with a bright rolled rim. */ +const faceTexture = kit => kit.tex.canvas('hcsr04-face', 2 * CAN.r, 2 * CAN.r, (ctx, cw, ch) => { + const r = cw / 2; + ctx.fillStyle = '#2a2c2f'; + ctx.fillRect(0, 0, cw, ch); + const step = cw / 34; + ctx.fillStyle = '#9ca1a6'; + for (let y = step / 2; y < ch; y += step) { + for (let x = step / 2; x < cw; x += step) { + ctx.fillRect(x - (step * 0.32), y - (step * 0.32), step * 0.64, step * 0.64); + } + } + ctx.lineWidth = r * 0.16; + ctx.strokeStyle = '#dfe2e5'; + ctx.beginPath(); + ctx.arc(r, r, r * 0.92, 0, Math.PI * 2); + ctx.stroke(); +}, { + ppu: 10, + svg: (() => { + const d = 2 * CAN.r; + const step = d / 34; + return `` + + `` + + `` + + ``; + })() +}); + +/** Carrier: copper traces from the socket to the header and the silkscreen pin names. */ +const SILK = PIN_U.map(u => { + const y = yOf(u); + return `'; +}).join('') + + PIN_U.map((u, i) => `${PIN_NAMES[i].toUpperCase()}`).join(''); + +/** A transducer: aluminium can lying along +x from the board's front face. */ +const transducer = (kit, g, u) => { + const can = kit.cylinder({ + cx: 0, + cy: 0, + r: CAN.r, + z0: 0, + z1: CAN.len, + seg: 48, + side: {color: '#cfd2d5', rough: 0.3, metal: 0.85}, + top: {map: faceTexture(kit), rough: 0.55, metal: 0.4} + }); + can.rotation.y = Math.PI / 2; + can.position.set(FRONT + (CAN.len / 2), -yOf(u), zOf(CAN.v)); + g.add(can); +}; + +/** HC-SR04 ultrasonic module soldered upright onto the RJ11 carrier. */ +export default { + id: 'ultra', + name: 'HC-SR04 Ultrasonic', + category: 'sensor', + defaultPort: 'N01', + spec: { + w: W, + h: H, + jackY: H / 2, + label: 'HC-SR04\nULTRASONIC', + labelAt: [24, 100], + labelSize: 4.6, + holes: [[8, 8], [8, H - 8], [W - 6, 6], [W - 6, H - 6]], + silk: SILK + }, + build (kit, g) { + capacitor(kit, g, 36, 84, false); + + // the HC-SR04 board, soldered straight onto the carrier + const board = {x: HC.x, y: HC.y, w: HC.t, d: HC.w, z: Z_BOT, h: HC.h}; + g.add(kit.box({...board, color: {color: HC_EDGE, rough: 0.6}})); + g.add(kit.sideDecal({...board, face: 'e', material: {map: kit.tex.svg('hcsr04-front', HC.w, HC.h, FRONT_SVG, {ppu: 8, base: HC_BLUE}), rough: 0.55}})); + g.add(kit.sideDecal({...board, face: 'w', material: {map: kit.tex.svg('hcsr04-back', HC.w, HC.h, BACK_SVG, {ppu: 6, base: HC_BLUE}), rough: 0.55}})); + + // chips on the back of the HC-SR04 + [[24, 14], [72, 14], [48, 8]].forEach(([u, v]) => g.add(kit.box({ + x: HC.x - 2.2, + y: yOf(HC.w - u) - 6, + w: 2.2, + d: 12, + h: 8, + z: zOf(v + 8), + color: BLACK + }))); + + CAN.u.forEach(u => transducer(kit, g, u)); + + // HC-49S crystal between the cans + g.add(kit.box({ + x: FRONT, + y: yOf(54) - 5.5, + w: 3.5, + d: 11, + h: 4.5, + z: zOf(10), + color: {color: '#d9dbdd', rough: 0.25, metal: 0.9} + })); + } +}; diff --git a/module-test/components/water.js b/module-test/components/water.js new file mode 100644 index 00000000000..61f58d74ded --- /dev/null +++ b/module-test/components/water.js @@ -0,0 +1,70 @@ +import {TOP, sot23} from '../lib/parts.js'; +import {PCB, PITCH, boardSvg, carrierPinNames, carrierTraces, rightAngleHeader, smd, stack, text} from '../lib/breakout.js'; + +/* + * Water level sensor — the red 62 × 20 mm board (about 2.4 units per mm): right-angle header (S, +, −) + * facing the RJ11 socket, S8050 transistor, resistors and power LED by the header, and the exposed + * comb of sense traces reaching out past the small carrier. + */ +const MX = 40; +const MY = 6; +const w = 149; +const d = 48; +const PIN_V = [0, 1, 2].map(i => (d / 2) + ((i - 1) * PITCH)); +const NAMES = ['S', '+', '-']; +const W = MX + 44; +const H = MY + d + 13; +const JACK_Y = MY + (d / 2); +const DROP_X = MX - 5; + +/** Ten exposed fingers, alternately tied to the two rails along the top and bottom. */ +const COMB = (() => { + let s = ''; + for (let i = 0; i < 10; i++) { + const y = 7.2 + (i * 3.6); + const fromLeft = i % 2 === 0; + s += ``; + s += ``; + } + return s; +})(); + +const svg = boardSvg({ + w, + d, + color: PCB.red[0], + holes: [[33, 6.4, 3]], + pins: PIN_V.map(v => ({u: 3.2, v})), + extra: COMB + + NAMES.map((n, i) => text(n, 9.4, PIN_V[i], {size: 2.6, weight: 700})).join('') + + text('Water Sensor', 24, d - 4.4, {size: 2.4, weight: 700}) + + '' + + text('PWR', 23.4, 36.2, {size: 1.8}) +}); + +export default { + id: 'water', + name: 'Water Level Sensor', + category: 'sensor', + defaultPort: 'A3', + spec: { + w: W, + h: H, + jackY: JACK_Y, + label: 'WATER SENSOR', + labelAt: [MX + 2, H - 5], + labelSize: 3.4, + holes: [[6, H - 6]], + silk: carrierTraces(PIN_V.map(v => [DROP_X, MY + v]), JACK_Y) + + carrierPinNames(PIN_V.map(v => [0, MY + v]), NAMES, DROP_X - 2.2) + }, + build (kit, g) { + const m = stack(kit, g, {x: MX, y: MY, w, d, key: 'water-red-module', svg, color: PCB.red}); + rightAngleHeader(kit, g, m, {mx: MX, my: MY, vs: PIN_V, dropX: DROP_X}); + sot23(kit, m, {x: 14, y: 8}); + smd(kit, m, 14, 16); + smd(kit, m, 22, 16); + smd(kit, m, 22, 24); + m.add(kit.box({x: 21, y: 30, w: 4.8, d: 2.4, h: 1.2, z: TOP, color: {color: '#e8e5dc', rough: 0.4}, faces: {t: kit.basic({color: '#ff4a3a'})}})); + } +}; diff --git a/module-test/embed-example.html b/module-test/embed-example.html new file mode 100644 index 00000000000..7ec0add1c7b --- /dev/null +++ b/module-test/embed-example.html @@ -0,0 +1,66 @@ + + + + + +Embedding TinkerBit 3D components + + + + + +

Embedding the components

+
+
+
+
1. Ready-made viewer: createViewer(el).showComponent('pot')
+
+
+
+
2. Your own three.js scene: scene.add(createComponent('dht'))
+
+
+ + + diff --git a/module-test/index.html b/module-test/index.html new file mode 100644 index 00000000000..998d18d51c6 --- /dev/null +++ b/module-test/index.html @@ -0,0 +1,287 @@ + + + + + +TinkerBit 3D components + + + + + +
+
+ … +
+ + + +
+ + + + + + + +
+
+
+ + Embed: +
+
+ + + diff --git a/module-test/lib/board-data.js b/module-test/lib/board-data.js new file mode 100644 index 00000000000..c6fbc23ff13 --- /dev/null +++ b/module-test/lib/board-data.js @@ -0,0 +1,2172 @@ +// Exported once from the old studio source; the kit is now the source of truth, so edit by hand. + +export const SCENE = { + "x": -50, + "y": -110, + "w": 940, + "h": 700 +}; + +export const BOARD = { + "x": 150, + "y": 105, + "w": 480, + "h": 300 +}; + +export const JACK = { + "w": 30, + "h": 36 +}; + +export const CARD = { + "w": 112, + "h": 38 +}; + +export const STUB = 56; + +export const SLAB_T = 7; + +export const PCB_H = 1.6; + +export const JACK_H = 16; + +export const MOD_H = 3; + +export const CAN_H = 5; + +export const USB_H = 9; + +export const GOLD = "#c9a34c"; + +export const MOD = { + "x": 190, + "y": 82, + "w": 100, + "h": 140 +}; + +export const ANTENNA_H = 40; + +export const CAN = { + "x": 194, + "y": 124, + "w": 92, + "d": 92 +}; + +export const U1 = { + "body": { + "x": 70, + "y": 175, + "w": 28, + "h": 22 + }, + "tab": { + "x": 77, + "y": 170, + "w": 14, + "h": 6 + } +}; + +export const U4 = { + "body": { + "x": 389, + "y": 190, + "w": 22, + "h": 30 + }, + "dot": { + "x": 394, + "y": 195 + } +}; + +export const USB = { + "x": 215, + "y": 262, + "w": 50, + "h": 44 +}; + +export const LEDS = [ + { + "x": 256, + "y": 240, + "color": "#ff2828", + "mode": "power" + }, + { + "x": 270, + "y": 240, + "color": "#288cff", + "mode": "activity" + }, + { + "x": 284, + "y": 240, + "color": "#28dc6e", + "mode": "heartbeat" + } +]; + +export const BUTTONS = [ + { + "x": 100, + "y": 268 + }, + { + "x": 138, + "y": 268 + } +]; + +export const PASSIVES = [ + { + "x": 74, + "y": 100, + "kind": "C", + "horizontal": false, + "w": 6, + "h": 11 + }, + { + "x": 88, + "y": 100, + "kind": "R", + "horizontal": false, + "w": 6, + "h": 11 + }, + { + "x": 102, + "y": 100, + "kind": "R", + "horizontal": false, + "w": 6, + "h": 11 + }, + { + "x": 116, + "y": 100, + "kind": "C", + "horizontal": false, + "w": 6, + "h": 11 + }, + { + "x": 74, + "y": 122, + "kind": "R", + "horizontal": false, + "w": 6, + "h": 11 + }, + { + "x": 88, + "y": 122, + "kind": "C", + "horizontal": false, + "w": 6, + "h": 11 + }, + { + "x": 102, + "y": 122, + "kind": "R", + "horizontal": false, + "w": 6, + "h": 11 + }, + { + "x": 116, + "y": 122, + "kind": "R", + "horizontal": false, + "w": 6, + "h": 11 + }, + { + "x": 374, + "y": 82, + "kind": "C", + "horizontal": false, + "w": 6, + "h": 11 + }, + { + "x": 388, + "y": 82, + "kind": "R", + "horizontal": false, + "w": 6, + "h": 11 + }, + { + "x": 402, + "y": 82, + "kind": "R", + "horizontal": false, + "w": 6, + "h": 11 + }, + { + "x": 374, + "y": 100, + "kind": "R", + "horizontal": false, + "w": 6, + "h": 11 + }, + { + "x": 388, + "y": 100, + "kind": "C", + "horizontal": false, + "w": 6, + "h": 11 + }, + { + "x": 402, + "y": 100, + "kind": "R", + "horizontal": false, + "w": 6, + "h": 11 + }, + { + "x": 204, + "y": 240, + "kind": "R", + "horizontal": true, + "w": 11, + "h": 6 + }, + { + "x": 219, + "y": 240, + "kind": "C", + "horizontal": true, + "w": 11, + "h": 6 + }, + { + "x": 234, + "y": 240, + "kind": "R", + "horizontal": true, + "w": 11, + "h": 6 + } +]; + +export const CAST = { + "x": [ + 10, + 20, + 30, + 40, + 50, + 60, + 70, + 80, + 90 + ], + "y": [ + 50, + 60, + 70, + 80, + 90, + 100, + 110, + 120, + 130 + ] +}; + +export const PORTS = [ + { + "id": "STEPPER", + "label": "ST", + "side": "top", + "kind": "stepper", + "open": "N", + "pos": { + "x": 198, + "y": 74, + "cableX": 213, + "cableY": 74, + "cardX": 157, + "cardY": -20 + }, + "footprint": { + "x": 195, + "y": 77, + "w": 36, + "d": 30 + }, + "labelBox": { + "x": 192, + "y": 108, + "w": 42, + "d": 27 + }, + "colors": { + "dark": "#9ca3af", + "light": "#6b7280" + } + }, + { + "id": "D13", + "label": "D13", + "side": "top", + "kind": "digital", + "open": "N", + "pos": { + "x": 316, + "y": 74, + "cableX": 331, + "cableY": 74, + "cardX": 275, + "cardY": -20 + }, + "footprint": { + "x": 313, + "y": 77, + "w": 36, + "d": 30 + }, + "labelBox": { + "x": 307, + "y": 108, + "w": 48, + "d": 27 + }, + "colors": { + "dark": "#3b82f6", + "light": "#3b82f6" + } + }, + { + "id": "3D", + "label": "3D", + "side": "top", + "kind": "spi", + "open": "N", + "pos": { + "x": 434, + "y": 74, + "cableX": 449, + "cableY": 74, + "cardX": 393, + "cardY": -20 + }, + "footprint": { + "x": 431, + "y": 77, + "w": 36, + "d": 30 + }, + "labelBox": { + "x": 428, + "y": 108, + "w": 42, + "d": 27 + }, + "colors": { + "dark": "#8b5cf6", + "light": "#8b5cf6" + } + }, + { + "id": "D5", + "label": "D5", + "side": "top", + "kind": "digital", + "open": "N", + "pos": { + "x": 552, + "y": 74, + "cableX": 567, + "cableY": 74, + "cardX": 511, + "cardY": -20 + }, + "footprint": { + "x": 549, + "y": 77, + "w": 36, + "d": 30 + }, + "labelBox": { + "x": 546, + "y": 108, + "w": 42, + "d": 27 + }, + "colors": { + "dark": "#3b82f6", + "light": "#3b82f6" + } + }, + { + "id": "MD", + "label": "MD", + "side": "right", + "kind": "motor", + "open": "E", + "pos": { + "x": 625, + "y": 147, + "cableX": 655, + "cableY": 165, + "cardX": 711, + "cardY": 146 + }, + "footprint": { + "x": 625, + "y": 147, + "w": 30, + "d": 36 + }, + "labelBox": { + "x": 581, + "y": 152, + "w": 42, + "d": 27 + }, + "colors": { + "dark": "#f59e0b", + "light": "#f59e0b" + } + }, + { + "id": "I2C", + "label": "I2C", + "side": "right", + "kind": "i2c", + "open": "E", + "pos": { + "x": 625, + "y": 205, + "cableX": 655, + "cableY": 223, + "cardX": 711, + "cardY": 204 + }, + "footprint": { + "x": 625, + "y": 205, + "w": 30, + "d": 36 + }, + "labelBox": { + "x": 575, + "y": 210, + "w": 48, + "d": 27 + }, + "colors": { + "dark": "#06b6d4", + "light": "#06b6d4" + } + }, + { + "id": "A3", + "label": "A3", + "side": "right", + "kind": "analog", + "open": "E", + "pos": { + "x": 625, + "y": 263, + "cableX": 655, + "cableY": 281, + "cardX": 711, + "cardY": 262 + }, + "footprint": { + "x": 625, + "y": 263, + "w": 30, + "d": 36 + }, + "labelBox": { + "x": 581, + "y": 268, + "w": 42, + "d": 27 + }, + "colors": { + "dark": "#10b981", + "light": "#10b981" + } + }, + { + "id": "A2", + "label": "A2", + "side": "right", + "kind": "analog", + "open": "E", + "pos": { + "x": 625, + "y": 321, + "cableX": 655, + "cableY": 339, + "cardX": 711, + "cardY": 320 + }, + "footprint": { + "x": 625, + "y": 321, + "w": 30, + "d": 36 + }, + "labelBox": { + "x": 581, + "y": 326, + "w": 42, + "d": 27 + }, + "colors": { + "dark": "#10b981", + "light": "#10b981" + } + }, + { + "id": "A1", + "label": "A1", + "side": "bottom", + "kind": "analog", + "open": "S", + "pos": { + "x": 198, + "y": 400, + "cableX": 213, + "cableY": 436, + "cardX": 157, + "cardY": 492 + }, + "footprint": { + "x": 195, + "y": 403, + "w": 36, + "d": 30 + }, + "labelBox": { + "x": 192, + "y": 374, + "w": 42, + "d": 27 + }, + "colors": { + "dark": "#10b981", + "light": "#10b981" + } + }, + { + "id": "A4", + "label": "A4", + "side": "bottom", + "kind": "analog", + "open": "S", + "pos": { + "x": 552, + "y": 400, + "cableX": 567, + "cableY": 436, + "cardX": 511, + "cardY": 492 + }, + "footprint": { + "x": 549, + "y": 403, + "w": 36, + "d": 30 + }, + "labelBox": { + "x": 546, + "y": 374, + "w": 42, + "d": 27 + }, + "colors": { + "dark": "#10b981", + "light": "#10b981" + } + }, + { + "id": "ONBOARD", + "label": "ESP", + "side": "left", + "kind": "onboard", + "open": "W", + "pos": { + "x": 125, + "y": 165, + "cableX": 125, + "cableY": 183, + "cardX": -43, + "cardY": 164 + }, + "footprint": { + "x": 125, + "y": 165, + "w": 30, + "d": 36 + }, + "labelBox": { + "x": 157, + "y": 170, + "w": 48, + "d": 27 + }, + "colors": { + "dark": "#06b6d4", + "light": "#06b6d4" + } + }, + { + "id": "UART", + "label": "UART", + "side": "left", + "kind": "uart", + "open": "W", + "pos": { + "x": 125, + "y": 235, + "cableX": 125, + "cableY": 253, + "cardX": -43, + "cardY": 234 + }, + "footprint": { + "x": 125, + "y": 235, + "w": 30, + "d": 36 + }, + "labelBox": { + "x": 157, + "y": 240, + "w": 56, + "d": 27 + }, + "colors": { + "dark": "#3b82f6", + "light": "#3b82f6" + } + } +]; + +export const TRACE_POINTS = { + "STEPPER": [ + [ + 213, + 110 + ], + [ + 213, + 139 + ], + [ + 213.16666666666669, + 140.83333333333334 + ], + [ + 213.66666666666669, + 142.33333333333334 + ], + [ + 214.5, + 143.5 + ], + [ + 215.66666666666669, + 144.33333333333334 + ], + [ + 217.16666666666669, + 144.83333333333334 + ], + [ + 219, + 145 + ], + [ + 314, + 145 + ], + [ + 315.83333333333337, + 145.16666666666669 + ], + [ + 317.33333333333337, + 145.66666666666669 + ], + [ + 318.5, + 146.5 + ], + [ + 319.33333333333337, + 147.66666666666669 + ], + [ + 319.83333333333337, + 149.16666666666669 + ], + [ + 320, + 151 + ], + [ + 320, + 251 + ], + [ + 320.1666666666667, + 252.83333333333334 + ], + [ + 320.6666666666667, + 254.33333333333334 + ], + [ + 321.5, + 255.5 + ], + [ + 322.6666666666667, + 256.33333333333337 + ], + [ + 324.1666666666667, + 256.83333333333337 + ], + [ + 326, + 257 + ], + [ + 340, + 257 + ] + ], + "D13": [ + [ + 331, + 110 + ], + [ + 331, + 232.5 + ], + [ + 331.125, + 233.875 + ], + [ + 331.5, + 235 + ], + [ + 332.125, + 235.875 + ], + [ + 333, + 236.5 + ], + [ + 334.125, + 236.875 + ], + [ + 335.5, + 237 + ], + [ + 340, + 237 + ] + ], + "3D": [ + [ + 449, + 110 + ], + [ + 449, + 232.5 + ], + [ + 448.875, + 233.875 + ], + [ + 448.50000000000006, + 235 + ], + [ + 447.875, + 235.875 + ], + [ + 447, + 236.5 + ], + [ + 445.875, + 236.875 + ], + [ + 444.5, + 237 + ], + [ + 440, + 237 + ] + ], + "D5": [ + [ + 567, + 110 + ], + [ + 567, + 139 + ], + [ + 566.8333333333335, + 140.83333333333334 + ], + [ + 566.3333333333335, + 142.33333333333334 + ], + [ + 565.5, + 143.5 + ], + [ + 564.3333333333334, + 144.33333333333334 + ], + [ + 562.8333333333333, + 144.83333333333334 + ], + [ + 561, + 145 + ], + [ + 466, + 145 + ], + [ + 464.1666666666667, + 145.16666666666669 + ], + [ + 462.66666666666674, + 145.66666666666669 + ], + [ + 461.5, + 146.5 + ], + [ + 460.6666666666667, + 147.66666666666669 + ], + [ + 460.1666666666667, + 149.16666666666669 + ], + [ + 460, + 151 + ], + [ + 460, + 251 + ], + [ + 459.83333333333337, + 252.83333333333334 + ], + [ + 459.33333333333337, + 254.33333333333334 + ], + [ + 458.5, + 255.5 + ], + [ + 457.33333333333337, + 256.33333333333337 + ], + [ + 455.83333333333337, + 256.83333333333337 + ], + [ + 454, + 257 + ], + [ + 440, + 257 + ] + ], + "MD": [ + [ + 625, + 165 + ], + [ + 486, + 165 + ], + [ + 484.16666666666674, + 165.16666666666669 + ], + [ + 482.66666666666674, + 165.66666666666669 + ], + [ + 481.5, + 166.5 + ], + [ + 480.6666666666667, + 167.66666666666669 + ], + [ + 480.1666666666667, + 169.16666666666666 + ], + [ + 480, + 171 + ], + [ + 480, + 261 + ], + [ + 479.83333333333337, + 262.83333333333337 + ], + [ + 479.33333333333337, + 264.33333333333337 + ], + [ + 478.5, + 265.5 + ], + [ + 477.33333333333337, + 266.33333333333337 + ], + [ + 475.83333333333337, + 266.83333333333337 + ], + [ + 474, + 267 + ], + [ + 440, + 267 + ] + ], + "I2C": [ + [ + 625, + 223 + ], + [ + 506, + 223 + ], + [ + 504.1666666666667, + 223.16666666666669 + ], + [ + 502.66666666666674, + 223.66666666666669 + ], + [ + 501.5, + 224.5 + ], + [ + 500.6666666666667, + 225.66666666666669 + ], + [ + 500.1666666666667, + 227.16666666666669 + ], + [ + 500, + 229 + ], + [ + 500, + 271 + ], + [ + 499.83333333333337, + 272.83333333333337 + ], + [ + 499.3333333333334, + 274.33333333333337 + ], + [ + 498.5, + 275.5 + ], + [ + 497.33333333333337, + 276.3333333333333 + ], + [ + 495.8333333333333, + 276.83333333333337 + ], + [ + 494, + 277 + ], + [ + 440, + 277 + ] + ], + "A3": [ + [ + 625, + 281 + ], + [ + 523, + 281 + ], + [ + 522.0833333333334, + 281.08333333333337 + ], + [ + 521.3333333333334, + 281.33333333333337 + ], + [ + 520.75, + 281.75 + ], + [ + 520.3333333333334, + 282.33333333333337 + ], + [ + 520.0833333333333, + 283.08333333333337 + ], + [ + 520, + 284 + ], + [ + 520, + 284 + ], + [ + 519.9166666666667, + 284.9166666666667 + ], + [ + 519.6666666666667, + 285.6666666666667 + ], + [ + 519.25, + 286.25 + ], + [ + 518.6666666666667, + 286.6666666666667 + ], + [ + 517.9166666666667, + 286.9166666666667 + ], + [ + 517, + 287 + ], + [ + 440, + 287 + ] + ], + "A2": [ + [ + 625, + 339 + ], + [ + 506, + 339 + ], + [ + 504.1666666666667, + 338.83333333333337 + ], + [ + 502.66666666666674, + 338.33333333333337 + ], + [ + 501.5, + 337.5 + ], + [ + 500.6666666666667, + 336.33333333333337 + ], + [ + 500.1666666666667, + 334.8333333333333 + ], + [ + 500, + 333 + ], + [ + 500, + 303 + ], + [ + 499.83333333333337, + 301.16666666666674 + ], + [ + 499.3333333333334, + 299.66666666666674 + ], + [ + 498.5, + 298.5 + ], + [ + 497.33333333333337, + 297.6666666666667 + ], + [ + 495.8333333333333, + 297.1666666666667 + ], + [ + 494, + 297 + ], + [ + 440, + 297 + ] + ], + "A1": [ + [ + 213, + 400 + ], + [ + 213, + 356 + ], + [ + 213.16666666666669, + 354.1666666666667 + ], + [ + 213.66666666666669, + 352.6666666666667 + ], + [ + 214.5, + 351.5 + ], + [ + 215.66666666666669, + 350.6666666666667 + ], + [ + 217.16666666666669, + 350.1666666666667 + ], + [ + 219, + 350 + ], + [ + 314, + 350 + ], + [ + 315.83333333333337, + 349.83333333333337 + ], + [ + 317.33333333333337, + 349.33333333333337 + ], + [ + 318.5, + 348.5 + ], + [ + 319.33333333333337, + 347.33333333333337 + ], + [ + 319.83333333333337, + 345.83333333333337 + ], + [ + 320, + 344 + ], + [ + 320, + 323 + ], + [ + 320.1666666666667, + 321.1666666666667 + ], + [ + 320.6666666666667, + 319.6666666666667 + ], + [ + 321.5, + 318.5 + ], + [ + 322.6666666666667, + 317.6666666666667 + ], + [ + 324.1666666666667, + 317.16666666666663 + ], + [ + 326, + 317 + ], + [ + 340, + 317 + ] + ], + "A4": [ + [ + 567, + 400 + ], + [ + 567, + 356 + ], + [ + 566.8333333333335, + 354.1666666666667 + ], + [ + 566.3333333333335, + 352.6666666666667 + ], + [ + 565.5, + 351.5 + ], + [ + 564.3333333333334, + 350.6666666666667 + ], + [ + 562.8333333333333, + 350.1666666666667 + ], + [ + 561, + 350 + ], + [ + 466, + 350 + ], + [ + 464.1666666666667, + 349.83333333333337 + ], + [ + 462.66666666666674, + 349.33333333333337 + ], + [ + 461.5, + 348.5 + ], + [ + 460.6666666666667, + 347.33333333333337 + ], + [ + 460.1666666666667, + 345.83333333333337 + ], + [ + 460, + 344 + ], + [ + 460, + 323 + ], + [ + 459.83333333333337, + 321.1666666666667 + ], + [ + 459.33333333333337, + 319.6666666666667 + ], + [ + 458.5, + 318.5 + ], + [ + 457.33333333333337, + 317.6666666666667 + ], + [ + 455.83333333333337, + 317.16666666666663 + ], + [ + 454, + 317 + ], + [ + 440, + 317 + ] + ], + "ONBOARD": [ + [ + 155, + 183 + ], + [ + 294, + 183 + ], + [ + 295.83333333333337, + 183.16666666666669 + ], + [ + 297.33333333333337, + 183.66666666666669 + ], + [ + 298.5, + 184.5 + ], + [ + 299.3333333333333, + 185.66666666666669 + ], + [ + 299.83333333333337, + 187.16666666666669 + ], + [ + 300, + 189 + ], + [ + 300, + 271 + ], + [ + 300.16666666666674, + 272.83333333333337 + ], + [ + 300.66666666666674, + 274.33333333333337 + ], + [ + 301.5, + 275.5 + ], + [ + 302.6666666666667, + 276.3333333333333 + ], + [ + 304.16666666666663, + 276.83333333333337 + ], + [ + 306, + 277 + ], + [ + 340, + 277 + ] + ], + "UART": [ + [ + 155, + 253 + ], + [ + 274, + 253 + ], + [ + 275.83333333333337, + 253.16666666666669 + ], + [ + 277.33333333333337, + 253.66666666666669 + ], + [ + 278.5, + 254.5 + ], + [ + 279.3333333333333, + 255.66666666666669 + ], + [ + 279.83333333333337, + 257.1666666666667 + ], + [ + 280, + 259 + ], + [ + 280, + 291 + ], + [ + 280.1666666666667, + 292.83333333333337 + ], + [ + 280.6666666666667, + 294.33333333333337 + ], + [ + 281.5, + 295.5 + ], + [ + 282.6666666666667, + 296.33333333333337 + ], + [ + 284.1666666666667, + 296.83333333333337 + ], + [ + 286, + 297 + ], + [ + 340, + 297 + ] + ] +}; + +export const THEMES = { + "dark": { + "canvas": "#0d1117", + "panel": "#1f2937", + "text": "#f9fafb", + "analog": "#10b981", + "digital": "#3b82f6" + }, + "light": { + "canvas": "#e8eef5", + "panel": "#ffffff", + "text": "#111827", + "analog": "#10b981", + "digital": "#3b82f6" + } +}; + +export const MODULES = [ + { + "id": "btn", + "name": "Push Button", + "color": "#3b82f6", + "category": "input", + "dir": "in" + }, + { + "id": "pot", + "name": "Potentiometer", + "color": "#8b5cf6", + "category": "input", + "dir": "in" + }, + { + "id": "led", + "name": "LED", + "color": "#8b5cf6", + "category": "output", + "dir": "out" + }, + { + "id": "relay", + "name": "Relay Module", + "color": "#f59e0b", + "category": "output", + "dir": "out" + }, + { + "id": "servo", + "name": "Servo Motor", + "color": "#3b82f6", + "category": "output", + "dir": "out" + }, + { + "id": "l293d", + "name": "L293D Motor Driver", + "color": "#9ca3af", + "category": "output", + "dir": "out" + }, + { + "id": "relay4", + "name": "4-Channel Relay", + "color": "#f59e0b", + "category": "output", + "dir": "out" + }, + { + "id": "stepper", + "name": "Stepper Motor", + "color": "#9ca3af", + "category": "output", + "dir": "out" + }, + { + "id": "oled", + "name": "OLED Screen", + "color": "#06b6d4", + "category": "output", + "dir": "out" + }, + { + "id": "mq2", + "name": "MQ-2 Gas Sensor", + "color": "#6b7280", + "category": "sensor", + "dir": "in" + }, + { + "id": "mic", + "name": "Microphone", + "color": "#f59e0b", + "category": "sensor", + "dir": "in" + }, + { + "id": "pulse", + "name": "Heartbeat HW-605", + "color": "#ef4444", + "category": "sensor", + "dir": "in" + }, + { + "id": "soil", + "name": "Capacitive Soil Moisture", + "color": "#10b981", + "category": "sensor", + "dir": "in" + }, + { + "id": "dht", + "name": "DHT11 Temp & Humid", + "color": "#f59e0b", + "category": "sensor", + "dir": "in" + }, + { + "id": "ultra", + "name": "HC-SR04 Ultrasonic", + "color": "#06b6d4", + "category": "sensor", + "dir": "in" + }, + { + "id": "rfid", + "name": "RFID RC522", + "color": "#8b5cf6", + "category": "sensor", + "dir": "in" + }, + { + "id": "ble", + "name": "Bluetooth (BLE)", + "color": "#06b6d4", + "category": "output", + "dir": "out" + }, + { + "id": "hc05", + "name": "HC-05 Bluetooth", + "color": "#06b6d4", + "category": "output", + "dir": "out" + }, + { + "id": "ir", + "name": "IR Sensor", + "color": "#ef4444", + "category": "sensor", + "dir": "in" + }, + { + "id": "ldr", + "name": "LDR Sensor", + "color": "#f59e0b", + "category": "sensor", + "dir": "in" + }, + { + "id": "flame", + "name": "Flame Sensor", + "color": "#f97316", + "category": "sensor", + "dir": "in" + }, + { + "id": "water", + "name": "Water Level Sensor", + "color": "#06b6d4", + "category": "sensor", + "dir": "in" + }, + { + "id": "tsop", + "name": "TSOP", + "color": "#6b7280", + "category": "sensor", + "dir": "in" + }, + { + "id": "irline", + "name": "IR Line Sensor Array", + "color": "#374151", + "category": "sensor", + "dir": "in" + }, + { + "id": "mpu6050", + "name": "MPU6050 Motion Sensor", + "color": "#3b82f6", + "category": "sensor", + "dir": "in" + }, + { + "id": "pir", + "name": "PIR Motion Sensor", + "color": "#10b981", + "category": "sensor", + "dir": "in" + }, + { + "id": "reed", + "name": "Reed Switch", + "color": "#9ca3af", + "category": "sensor", + "dir": "in" + }, + { + "id": "lcd", + "name": "LCD 16x2 (I2C)", + "color": "#10b981", + "category": "output", + "dir": "out" + }, + { + "id": "rgb", + "name": "RGB Light (NeoPixel)", + "color": "#8b5cf6", + "category": "output", + "dir": "out" + }, + { + "id": "strip", + "name": "NeoPixel Bar (10 LEDs)", + "color": "#ec4899", + "category": "output", + "dir": "out" + }, + { + "id": "matrix", + "name": "NeoPixel Matrix 8x8", + "color": "#ef4444", + "category": "output", + "dir": "out" + }, + { + "id": "drv8833", + "name": "Motor Driver DRV8833", + "color": "#dc2626", + "category": "output", + "dir": "out" + }, + { + "id": "bomotor", + "name": "BO Motor with Wheel", + "color": "#eab308", + "category": "output", + "dir": "out" + }, + { + "id": "buzzer", + "name": "Buzzer", + "color": "#374151", + "category": "output", + "dir": "out" + }, + { + "id": "i2samp", + "name": "I2S Amp + Speaker", + "color": "#7c3aed", + "category": "output", + "dir": "out" + }, + { + "id": "pump", + "name": "Water Pump", + "color": "#0ea5e9", + "category": "output", + "dir": "out" + }, + { + "id": "solenoid", + "name": "Solenoid Lock", + "color": "#9ca3af", + "category": "output", + "dir": "out" + } +]; + +export const TEXTURES = { + "board-top": { + "file": "assets/svg/board-top.svg", + "w": 480, + "h": 300, + "ppu": 4, + "base": "#f4f4f0", + "kind": "board" + }, + "esp-top": { + "file": "assets/svg/esp-top.svg", + "w": 100, + "h": 140, + "ppu": 6, + "base": "#141414", + "kind": "board" + }, + "esp-can": { + "file": "assets/svg/esp-can.svg", + "w": 92, + "h": 92, + "ppu": 6, + "base": "#c9c4b8", + "kind": "board" + }, + "u1-top": { + "file": "assets/svg/u1-top.svg", + "w": 28, + "h": 22, + "ppu": 6, + "base": "#1a1b1d", + "kind": "board" + }, + "u4-top": { + "file": "assets/svg/u4-top.svg", + "w": 22, + "h": 30, + "ppu": 6, + "base": "#1a1b1d", + "kind": "board" + }, + "usb-top": { + "file": "assets/svg/usb-top.svg", + "w": 50, + "h": 44, + "ppu": 6, + "base": "#c9cbcd", + "kind": "board" + }, + "usb-front": { + "file": "assets/svg/usb-front.svg", + "w": 50, + "h": 9, + "ppu": 8, + "base": "#c9cbcd", + "kind": "board" + }, + "label-STEPPER-dark": { + "file": "assets/svg/label-STEPPER-dark.svg", + "w": 42, + "h": 27, + "ppu": 6, + "base": null, + "kind": "label" + }, + "label-D13-dark": { + "file": "assets/svg/label-D13-dark.svg", + "w": 48, + "h": 27, + "ppu": 6, + "base": null, + "kind": "label" + }, + "label-3D-dark": { + "file": "assets/svg/label-3D-dark.svg", + "w": 42, + "h": 27, + "ppu": 6, + "base": null, + "kind": "label" + }, + "label-D5-dark": { + "file": "assets/svg/label-D5-dark.svg", + "w": 42, + "h": 27, + "ppu": 6, + "base": null, + "kind": "label" + }, + "label-MD-dark": { + "file": "assets/svg/label-MD-dark.svg", + "w": 42, + "h": 27, + "ppu": 6, + "base": null, + "kind": "label" + }, + "label-I2C-dark": { + "file": "assets/svg/label-I2C-dark.svg", + "w": 48, + "h": 27, + "ppu": 6, + "base": null, + "kind": "label" + }, + "label-A3-dark": { + "file": "assets/svg/label-A3-dark.svg", + "w": 42, + "h": 27, + "ppu": 6, + "base": null, + "kind": "label" + }, + "label-A2-dark": { + "file": "assets/svg/label-A2-dark.svg", + "w": 42, + "h": 27, + "ppu": 6, + "base": null, + "kind": "label" + }, + "label-A1-dark": { + "file": "assets/svg/label-A1-dark.svg", + "w": 42, + "h": 27, + "ppu": 6, + "base": null, + "kind": "label" + }, + "label-A4-dark": { + "file": "assets/svg/label-A4-dark.svg", + "w": 42, + "h": 27, + "ppu": 6, + "base": null, + "kind": "label" + }, + "label-ONBOARD-dark": { + "file": "assets/svg/label-ONBOARD-dark.svg", + "w": 48, + "h": 27, + "ppu": 6, + "base": null, + "kind": "label" + }, + "label-UART-dark": { + "file": "assets/svg/label-UART-dark.svg", + "w": 56, + "h": 27, + "ppu": 6, + "base": null, + "kind": "label" + }, + "card-relay-dark": { + "file": "assets/svg/card-relay-dark.svg", + "w": 112, + "h": 38, + "ppu": 6, + "base": "#1f2937", + "kind": "card" + }, + "card-servo-dark": { + "file": "assets/svg/card-servo-dark.svg", + "w": 112, + "h": 38, + "ppu": 6, + "base": "#1f2937", + "kind": "card" + }, + "card-l293d-dark": { + "file": "assets/svg/card-l293d-dark.svg", + "w": 112, + "h": 38, + "ppu": 6, + "base": "#1f2937", + "kind": "card" + }, + "card-relay4-dark": { + "file": "assets/svg/card-relay4-dark.svg", + "w": 112, + "h": 38, + "ppu": 6, + "base": "#1f2937", + "kind": "card" + }, + "card-stepper-dark": { + "file": "assets/svg/card-stepper-dark.svg", + "w": 112, + "h": 38, + "ppu": 6, + "base": "#1f2937", + "kind": "card" + }, + "card-oled-dark": { + "file": "assets/svg/card-oled-dark.svg", + "w": 112, + "h": 38, + "ppu": 6, + "base": "#1f2937", + "kind": "card" + }, + "card-ble-dark": { + "file": "assets/svg/card-ble-dark.svg", + "w": 112, + "h": 38, + "ppu": 6, + "base": "#1f2937", + "kind": "card" + }, + "card-hc05-dark": { + "file": "assets/svg/card-hc05-dark.svg", + "w": 112, + "h": 38, + "ppu": 6, + "base": "#1f2937", + "kind": "card" + }, + "label-STEPPER-light": { + "file": "assets/svg/label-STEPPER-light.svg", + "w": 42, + "h": 27, + "ppu": 6, + "base": null, + "kind": "label" + }, + "label-D13-light": { + "file": "assets/svg/label-D13-light.svg", + "w": 48, + "h": 27, + "ppu": 6, + "base": null, + "kind": "label" + }, + "label-3D-light": { + "file": "assets/svg/label-3D-light.svg", + "w": 42, + "h": 27, + "ppu": 6, + "base": null, + "kind": "label" + }, + "label-D5-light": { + "file": "assets/svg/label-D5-light.svg", + "w": 42, + "h": 27, + "ppu": 6, + "base": null, + "kind": "label" + }, + "label-MD-light": { + "file": "assets/svg/label-MD-light.svg", + "w": 42, + "h": 27, + "ppu": 6, + "base": null, + "kind": "label" + }, + "label-I2C-light": { + "file": "assets/svg/label-I2C-light.svg", + "w": 48, + "h": 27, + "ppu": 6, + "base": null, + "kind": "label" + }, + "label-A3-light": { + "file": "assets/svg/label-A3-light.svg", + "w": 42, + "h": 27, + "ppu": 6, + "base": null, + "kind": "label" + }, + "label-A2-light": { + "file": "assets/svg/label-A2-light.svg", + "w": 42, + "h": 27, + "ppu": 6, + "base": null, + "kind": "label" + }, + "label-A1-light": { + "file": "assets/svg/label-A1-light.svg", + "w": 42, + "h": 27, + "ppu": 6, + "base": null, + "kind": "label" + }, + "label-A4-light": { + "file": "assets/svg/label-A4-light.svg", + "w": 42, + "h": 27, + "ppu": 6, + "base": null, + "kind": "label" + }, + "label-ONBOARD-light": { + "file": "assets/svg/label-ONBOARD-light.svg", + "w": 48, + "h": 27, + "ppu": 6, + "base": null, + "kind": "label" + }, + "label-UART-light": { + "file": "assets/svg/label-UART-light.svg", + "w": 56, + "h": 27, + "ppu": 6, + "base": null, + "kind": "label" + }, + "card-relay-light": { + "file": "assets/svg/card-relay-light.svg", + "w": 112, + "h": 38, + "ppu": 6, + "base": "#ffffff", + "kind": "card" + }, + "card-servo-light": { + "file": "assets/svg/card-servo-light.svg", + "w": 112, + "h": 38, + "ppu": 6, + "base": "#ffffff", + "kind": "card" + }, + "card-l293d-light": { + "file": "assets/svg/card-l293d-light.svg", + "w": 112, + "h": 38, + "ppu": 6, + "base": "#ffffff", + "kind": "card" + }, + "card-relay4-light": { + "file": "assets/svg/card-relay4-light.svg", + "w": 112, + "h": 38, + "ppu": 6, + "base": "#ffffff", + "kind": "card" + }, + "card-stepper-light": { + "file": "assets/svg/card-stepper-light.svg", + "w": 112, + "h": 38, + "ppu": 6, + "base": "#ffffff", + "kind": "card" + }, + "card-oled-light": { + "file": "assets/svg/card-oled-light.svg", + "w": 112, + "h": 38, + "ppu": 6, + "base": "#ffffff", + "kind": "card" + }, + "card-ble-light": { + "file": "assets/svg/card-ble-light.svg", + "w": 112, + "h": 38, + "ppu": 6, + "base": "#ffffff", + "kind": "card" + }, + "card-hc05-light": { + "file": "assets/svg/card-hc05-light.svg", + "w": 112, + "h": 38, + "ppu": 6, + "base": "#ffffff", + "kind": "card" + } +}; diff --git a/module-test/lib/breakout.js b/module-test/lib/breakout.js new file mode 100644 index 00000000000..28a6f4dbe61 --- /dev/null +++ b/module-test/lib/breakout.js @@ -0,0 +1,302 @@ +import {CatmullRomCurve3, Group, Mesh, TubeGeometry, Vector3} from 'three'; + +import {PCB_H} from './board-data.js'; +import {at} from './kit.js'; +import {BLACK, TOP, axial, glowDecal, passiveTexture, soic, trimmer} from './parts.js'; + +/* + * Shared pieces for modules built "the TinkerBit way": a purple RJ11 carrier with a real + * off-the-shelf breakout stacked on its header (or a part wired to it). Real parts are drawn + * at about 2.4 units per mm. Coordinates follow the kit: SVG-style x / y (y down), z up. + */ +const MM = 2.4; +const PITCH = 6.1; +const SILK = '#f2f4f6'; +const TRACE = '#6531a3'; +const PCB = { + blue: ['#1c5d8f', '#123f63'], + black: ['#17181a', '#0a0a0b'], + red: ['#b3262b', '#7d171b'], + green: ['#1f6b3a', '#134726'], + purple: ['#4a2178', '#2f1350'] +}; +const PIN_METAL = {color: '#d6b25a', rough: 0.3, metal: 0.85}; +const SOLDER = {color: '#cfd2d5', rough: 0.3, metal: 0.8}; + +/** n header pins in a column at u, centred on v (module coordinates). */ +const pinColumn = (n, u, vMid) => Array.from({length: n}, (_, i) => ({u, v: vMid + ((i - ((n - 1) / 2)) * PITCH)})); + +/** n header pins in a row at v, centred on u. */ +const pinRow = (n, uMid, v) => Array.from({length: n}, (_, i) => ({u: uMid + ((i - ((n - 1) / 2)) * PITCH), v})); + +/** Silver plated hole (mounting or pin pad) as SVG. */ +const holeSvg = (x, y, r = 3.4, ring = '#d9dbdd') => `` + + ``; + +const text = (t, x, y, {size = 2.4, anchor = 'middle', rot = 0, color = SILK, weight = 400} = {}) => ( + `${t}` +); + +/** Module top artwork: mask colour, holes, pin pads and any extra markup. */ +const boardSvg = ({w, d, color, holes = [], pins = [], extra = ''}) => `` + + holes.map(([x, y, r]) => holeSvg(x, y, r)).join('') + + pins.map(p => holeSvg(p.u, p.v, 2.1)).join('') + extra; + +/** Carrier copper: one trace per pin from the RJ11 socket (x 26) to the pin's world position. */ +const carrierTraces = (points, jackY, {spread = 2.3, width = 1.1} = {}) => points.map(([x, y], i) => { + const jy = jackY + ((i - ((points.length - 1) / 2)) * spread); + return `'; +}).join(''); + +/** Pin names printed on the carrier, just west of the module. */ +const carrierPinNames = (points, names, x) => points.map(([, y], i) => text(names[i], x, y, {size: 2.2, anchor: 'end'})).join(''); + +/** + * A breakout standing on its header over the carrier. Adds the black spacer(s) under each pin + * column or row, then returns a group in the module's own frame — (u, v) from its top-left + * corner, z = 0 at its underside — so the shared part helpers (which build at z = TOP) sit on + * its surface. rotate: quarter turns (counter-clockwise seen from above) about the module's corner. + */ +const stack = (kit, g, {x, y, w, d, key, svg, color = PCB.blue, pins = [], spacer = 6, r = 1.5, outline, ppu = 8}) => { + const columns = {}; + pins.forEach(p => { + const k = `u${p.u}`; + (columns[k] = columns[k] || []).push(p); + }); + const rows = {}; + pins.forEach(p => { + const k = `v${p.v}`; + (rows[k] = rows[k] || []).push(p); + }); + const groups = Object.keys(columns).length <= Object.keys(rows).length ? columns : rows; + Object.keys(groups).forEach(k => { + const list = groups[k]; + const u0 = Math.min(...list.map(p => p.u)) - 3; + const u1 = Math.max(...list.map(p => p.u)) + 3; + const v0 = Math.min(...list.map(p => p.v)) - 3; + const v1 = Math.max(...list.map(p => p.v)) + 3; + g.add(kit.box({x: x + u0, y: y + v0, w: u1 - u0, d: v1 - v0, h: spacer, z: TOP, color: BLACK})); + }); + + const m = new Group(); + const [mx, my] = at(x, y); + m.position.set(mx, my, TOP + spacer); + g.add(m); + m.add(kit.slab({ + x: 0, + y: 0, + w, + d, + h: PCB_H, + r, + outline, + top: {map: kit.tex.svg(key, w, d, svg, {ppu, base: color[0]}), rough: 0.55}, + side: {color: color[1], rough: 0.6} + })); + pins.forEach(p => { + m.add(kit.cylinder({cx: p.u, cy: p.v, r: 1.5, z0: TOP, z1: TOP + 0.9, side: SOLDER, seg: 14})); + m.add(kit.box({x: p.u - 0.7, y: p.v - 0.7, w: 1.4, d: 1.4, h: 2.2, z: TOP, color: PIN_METAL, shadow: false})); + }); + return m; +}; + +/** + * Right-angle header on a stacked module's west edge: black support under the edge, the plastic + * strip on top, and pins running out west then bent down into the carrier at dropX. + * mx, my: the module's corner on the carrier; vs: pin v positions (module coordinates). + */ +const rightAngleHeader = (kit, g, m, {mx, my, vs, u = 3.2, spacer = 6, dropX = mx - 5}) => { + const v0 = Math.min(...vs) - 3; + const span = Math.max(...vs) - Math.min(...vs) + 6; + const top = TOP + spacer + PCB_H; + g.add(kit.box({x: mx, y: my + v0, w: 6, d: span, h: spacer, z: TOP, color: BLACK})); + m.add(kit.box({x: u - 2.4, y: v0, w: 5, d: span, h: 2.6, z: TOP, color: {color: '#151515', rough: 0.5}})); + vs.forEach(v => { + m.add(kit.cylinder({cx: u, cy: v, r: 1.4, z0: TOP, z1: TOP + 0.6, side: SOLDER, seg: 12})); + g.add(kit.box({x: dropX - 0.7, y: my + v - 0.7, w: mx + u - dropX + 1.4, d: 1.4, h: 1.4, z: top + 0.6, color: PIN_METAL})); + g.add(kit.box({x: dropX - 0.7, y: my + v - 0.7, w: 1.4, d: 1.4, h: top + 3.2 - TOP, z: TOP - 1.2, color: PIN_METAL})); + }); + return dropX; +}; + +/** Small 0805 resistor or capacitor at (x, y), its long side along x unless vertical. */ +const smd = (kit, g, x, y, kind = 'R', vertical = false) => g.add(kit.box({ + x, + y, + w: vertical ? 2.2 : 4.4, + d: vertical ? 4.4 : 2.2, + h: kind === 'C' ? 1.4 : 1.1, + z: TOP, + color: kind === 'C' ? '#8a6641' : '#121212', + faces: {t: {map: passiveTexture(kit, kind === 'C' ? 'C' : 'R', !vertical), rough: 0.45}} +})); + +/** 0805 indicator LED; lit ones get a soft glow. */ +const ledSmd = (kit, g, x, y, color, lit = true) => { + g.add(kit.box({x, y, w: 4.4, d: 2.4, h: 1.2, z: TOP, color: {color: '#e8e5dc', rough: 0.4}, faces: {t: kit.basic({color})}})); + if (lit) { + g.add(glowDecal(kit, {cx: x + 2.2, cy: y + 1.2, size: 14, z: TOP + 1.3, color, opacity: 0.55})); + } +}; + +/** Profile of a 5 mm through-hole LED (radius, height) in units, flange at 0. */ +const LED5 = [[0, 0], [6.6, 0], [6.6, 1.4], [6, 1.4], [6, 10.5], [5.6, 11.8], [4.6, 12.9], [3, 13.6], [0, 13.9]]; + +/** + * 5 mm LED. dir 'up': standing on legs from z0 (default TOP) with its flange at z0 + legs. + * dir 'e' / 'w': lying with its dome pointing east / west, centre height cz. + */ +const led5 = (kit, g, {x, y, dir = 'up', z0 = TOP, legs = 4, cz, color = '#d8e4ee', opacity = 0.65, key = 'led5', lit = false}) => { + const material = {color, rough: 0.18, opacity, emissive: lit ? color : '#000000', emissiveIntensity: lit ? 0.5 : 0}; + const mesh = kit.lathe({key, cx: 0, cy: 0, z: 0, profile: LED5, material}); + if (dir === 'up') { + mesh.position.set(...at(x, y), z0 + legs); + g.add(mesh); + [-1.3, 1.3].forEach(o => g.add(kit.box({x: x + o - 0.4, y: y - 0.4, w: 0.8, d: 0.8, h: legs, z: z0, color: SOLDER, shadow: false}))); + } else { + const s = dir === 'e' ? 1 : -1; + mesh.rotation.y = s * (Math.PI / 2); + mesh.position.set(...at(x, y), cz); + g.add(mesh); + // legs: back along the body, then down to the board + [-1.3, 1.3].forEach(o => { + g.add(kit.box({x: s > 0 ? x - 6 : x, y: y + o - 0.4, w: 6, d: 0.8, h: 0.8, z: cz - 0.4, color: SOLDER, shadow: false})); + g.add(kit.box({x: x - (s * 6) - 0.4, y: y + o - 0.4, w: 0.8, d: 0.8, h: cz - z0, z: z0, color: SOLDER, shadow: false})); + }); + } + if (lit) { + g.add(glowDecal(kit, {cx: x, cy: y, size: 34, z: z0 + 0.3, color, opacity: 0.45})); + } + return mesh; +}; + +/** + * Green pluggable screw terminal: n poles along y at `pitch`, footprint x .. x + 18, with the + * wire openings facing `open` ('e' or 'w') and the screws on top. + */ +const screwTerminal = (kit, g, {x, y, n = 2, pitch = 12, open = 'e', z = TOP}) => { + const d = n * pitch; + const top = `` + Array.from({length: n}, (_, i) => { + const cy = (i + 0.5) * pitch; + return `` + + `` + + ``; + }).join(''); + const face = `` + Array.from({length: n}, (_, i) => ( + `` + + `` + )).join(''); + g.add(kit.box({ + x, + y, + w: 18, + d, + h: 22, + z, + color: {color: '#1d8048', rough: 0.55}, + faces: {t: {map: kit.tex.svg(`screwterm-top:${n}:${pitch}`, 18, d, top, {ppu: 8, base: '#1f8a4c'}), rough: 0.5}} + })); + g.add(kit.sideDecal({ + face: open, + x, + y, + w: 18, + d, + z, + h: 22, + material: {map: kit.tex.svg(`screwterm-face:${n}:${pitch}`, d, 22, face, {ppu: 8, base: '#1f8a4c'}), rough: 0.5} + })); +}; + +/** One insulated wire as a tube through SVG-style [x, y, z] points. */ +const wire = (kit, points, color, r = 1.3) => { + const curve = new CatmullRomCurve3(points.map(([x, y, z]) => new Vector3(x, -y, z)), false, 'centripetal'); + const mesh = new Mesh(new TubeGeometry(curve, Math.max(24, points.length * 16), r, 8, false), kit.mat({color, rough: 0.5})); + mesh.castShadow = true; + mesh.receiveShadow = true; + return mesh; +}; + +/** Several wires side by side: paths(k) gives the points for the wire at offset index k. */ +const lead = (kit, g, colors, paths, r = 1.3) => colors.forEach((c, i) => g.add(wire(kit, paths(i - ((colors.length - 1) / 2), i), c, r))); + +/** + * A generic LM393 comparator sensor board (the common 32 × 14 mm blue module): header on the + * west edge, comparator, sensitivity trimmer, PWR and signal LEDs, and a sensor area to the east + * that `sensor(kit, m, ctx)` fills. Returns a full component definition on a purple carrier. + */ +const comparatorModule = ({id, name, category = 'sensor', defaultPort = 'A1', label, pinNames, color = PCB.blue, + w = 77, d = 34, sensor, silk = '', overhang = 0, extraBuild}) => { + const MX = 36; + const MY = 5; + const pins = pinColumn(pinNames.length, 3, d / 2); + const W = MX + w - overhang + 5; + const H = MY + d + 13; + const world = pins.map(p => [MX + p.u, MY + p.v]); + const svg = boardSvg({ + w, + d, + color: color[0], + holes: [[38, d / 2, 3.4]], + pins, + extra: text('PWR', 30, 4.5, {size: 2}) + text('DO', 30, d - 4, {size: 2}) + silk + }); + return { + id, + name, + category, + defaultPort, + spec: { + w: W, + h: H, + jackY: MY + (d / 2), + label, + labelAt: [MX + ((w - overhang) / 2), H - 5], + labelSize: 3.6, + holes: [[6, H - 6]], + silk: carrierTraces(world, MY + (d / 2)) + carrierPinNames(world, pinNames, MX - 1.5) + }, + build (kit, g, ctx) { + const m = stack(kit, g, {x: MX, y: MY, w, d, key: `${id}-module`, svg, color, pins}); + soic(kit, m, {x: 9, y: 3.4, w: 10, d: 8}); + trimmer(kit, m, 9, 20); + ledSmd(kit, m, 23, 7, '#ff3030'); + ledSmd(kit, m, 23, d - 9.5, '#30ff60', false); + smd(kit, m, 23, 13); + smd(kit, m, 23, 18.5, 'C'); + sensor(kit, m, {...ctx, w, d}); + if (extraBuild) { + extraBuild(kit, g, {...ctx, MX, MY, W, H}); + } + } + }; +}; + +export { + MM, + PITCH, + SILK, + TRACE, + PCB, + PIN_METAL, + SOLDER, + pinColumn, + pinRow, + holeSvg, + text, + boardSvg, + carrierTraces, + carrierPinNames, + stack, + rightAngleHeader, + smd, + ledSmd, + led5, + screwTerminal, + wire, + lead, + axial, + comparatorModule +}; diff --git a/module-test/lib/cable.js b/module-test/lib/cable.js new file mode 100644 index 00000000000..dd3c6006a67 --- /dev/null +++ b/module-test/lib/cable.js @@ -0,0 +1,99 @@ +import {CatmullRomCurve3, Group, Mesh, TubeGeometry, Vector3} from 'three'; + +import {SLAB_T} from './board-data.js'; + +const TABLE_Z = -SLAB_T; +const RADIUS = 2.6; +const PLUG = {len: 12, w: 11, h: 8, boot: 8, inside: 4}; +const BACK = PLUG.len + PLUG.boot - PLUG.inside; + +const smooth = t => { + const k = Math.max(0, Math.min(1, t)); + return k * k * (3 - (2 * k)); +}; + +/** RJ11 plug in its own frame: tip at the origin, pointing along +x. */ +const buildPlug = (kit, color) => { + const g = new Group(); + g.add(kit.box({ + x: -PLUG.len, + y: -PLUG.w / 2, + w: PLUG.len, + d: PLUG.w, + h: PLUG.h, + z: -PLUG.h / 2, + color: {color: '#e9eef3', rough: 0.25, opacity: 0.92} + })); + g.add(kit.box({ + x: -PLUG.len + 2, + y: -3, + w: PLUG.len - 3, + d: 6, + h: 1.4, + z: PLUG.h / 2, + color: {color, rough: 0.35} + })); + g.add(kit.box({ + x: -PLUG.len - PLUG.boot, + y: -(PLUG.w - 3) / 2, + w: PLUG.boot, + d: PLUG.w - 3, + h: PLUG.h - 2, + z: -(PLUG.h - 2) / 2, + color: {color: '#9aa5b1', rough: 0.5} + })); + return g; +}; + +/** Plug seated in a socket mouth at (x, y, z), pushed in along world direction (ix, iy). */ +const placePlug = (plug, {x, y, z}, ix, iy) => { + plug.position.set(x + (ix * PLUG.inside), -(y + (iy * PLUG.inside)), z); + plug.rotation.z = Math.atan2(-iy, ix); + return plug; +}; + +/** + * Cable from a board jack to a module socket. `from`/`to` are world points (SVG-style x, y with + * height z) plus the jack's outward direction `dir`; the optional bend handle (world x, y) shapes + * the run along the table. Returns a group in board space. + */ +const buildCable = (kit, {from, to, handle, color}) => { + const group = new Group(); + const [dx, dy] = from.dir; + const start = {x: from.x + (dx * BACK), y: from.y + (dy * BACK)}; + const end = {x: to.x - (dx * BACK), y: to.y - (dy * BACK)}; + const a = {x: start.x + (dx * 10), y: start.y + (dy * 10)}; + const b = {x: end.x - (dx * 10), y: end.y - (dy * 10)}; + const hx = handle ? handle.x : (from.x + to.x) / 2; + const hy = handle ? handle.y : (from.y + to.y) / 2; + const cx = (2 * hx) - ((a.x + b.x) / 2); + const cy = (2 * hy) - ((a.y + b.y) / 2); + const floor = TABLE_Z + RADIUS; + + const pts = [new Vector3(start.x, -start.y, from.z)]; + const steps = 24; + for (let i = 0; i <= steps; i++) { + const t = i / steps; + const u = 1 - t; + const x = (u * u * a.x) + (2 * u * t * cx) + (t * t * b.x); + const y = (u * u * a.y) + (2 * u * t * cy) + (t * t * b.y); + const z = t < 0.5 ? + from.z + ((floor - from.z) * smooth(t / 0.38)) : + to.z + ((floor - to.z) * smooth((1 - t) / 0.38)); + pts.push(new Vector3(x, -y, z)); + } + pts.push(new Vector3(end.x, -end.y, to.z)); + + const curve = new CatmullRomCurve3(pts, false, 'centripetal'); + const tube = new Mesh(new TubeGeometry(curve, 96, RADIUS, 10, false), kit.mat({color, rough: 0.45})); + tube.castShadow = true; + tube.receiveShadow = true; + group.add(tube); + + group.add(placePlug(buildPlug(kit, color), from, -dx, -dy)); + group.add(placePlug(buildPlug(kit, color), to, dx, dy)); + return group; +}; + +export {TABLE_Z, buildPlug}; +export default buildCable; diff --git a/module-test/lib/index.js b/module-test/lib/index.js new file mode 100644 index 00000000000..12e8c40a046 --- /dev/null +++ b/module-test/lib/index.js @@ -0,0 +1,210 @@ +/* + * TinkerBit 3D components, standalone. + * + * import {createViewer, createComponent, COMPONENTS} from './lib/index.js'; + * const viewer = createViewer(document.getElementById('stage')); + * viewer.showComponent('pot'); // or viewer.add(createComponent('dht')) + * + * Needs an import map that resolves "three" (see index.html). All sizes are studio board units. + */ +import {Box3, Group, Mesh} from 'three'; + +import {CARD, JACK_H, MODULES, PCB_H, THEMES} from './board-data.js'; +import buildCable, {TABLE_Z} from './cable.js'; +import Kit, {at, disposeTree} from './kit.js'; +import {buildModule, placeModule} from './pcb.js'; +import TextureBank from './textures.js'; +import objectToTopSVG from './top-svg.js'; +import {Viewer, createViewer} from './viewer.js'; + +import board, {PORTS, TRACE_POINTS, buildBoardScene} from '../components/esp32-board.js'; +import {CARD_T, makeCard} from '../components/card.js'; +import MODELS from '../components/models.js'; + +TextureBank.assetRoot = new URL('../', import.meta.url).href; + +const MOUTH_Z = JACK_H * 0.46; +const OUTWARD = {top: [0, -1], bottom: [0, 1], left: [-1, 0], right: [1, 0]}; + +/** Modules without a 3D model are shown as flat cards only when this is on. */ +const SHOW_CARDS = false; + +/** Every component: the board, then the modelled modules (and the card-only ones if SHOW_CARDS). */ +const COMPONENTS = [board].concat(MODULES.filter(m => MODELS[m.id] || SHOW_CARDS).map(m => ( + MODELS[m.id] ? {...MODELS[m.id], kind: MODELS[m.id].kind || 'module', color: m.color} : makeCard(m) +))); + +const getComponent = id => { + const comp = COMPONENTS.find(c => c.id === id); + if (!comp) { + throw new Error(`Unknown component "${id}". Known: ${COMPONENTS.map(c => c.id).join(', ')}`); + } + return comp; +}; + +let sharedKit = null; +/** Kit used by createComponent when none is passed (textures shared across calls). */ +const defaultKit = () => { + if (!sharedKit) { + sharedKit = new Kit(new TextureBank()); + } + return sharedKit; +}; + +/** Subscribe to async texture loads of the default kit (re-render your scene when it fires). */ +const onTexturesChanged = fn => defaultKit().tex.onChange(fn); + +const buildRaw = (kit, comp, options) => { + if (comp.kind === 'board' || comp.kind === 'part') { + return comp.buildScene(kit, options); + } + if (comp.kind === 'card') { + const g = new Group(); + g.name = comp.id; + g.add(comp.buildCard(kit, options)); + return g; + } + return buildModule(kit, comp, options); +}; + +/** Move obj so its footprint is centred on the origin and its underside sits at z = 0. */ +const recentre = obj => { + obj.updateWorldMatrix(true, true); + const box = new Box3().setFromObject(obj); + if (!box.isEmpty()) { + const cx = (box.min.x + box.max.x) / 2; + const cy = (box.min.y + box.max.y) / 2; + obj.position.x -= cx; + obj.position.y -= cy; + obj.position.z -= box.min.z; + } + return obj; +}; + +/** + * One component in board space (x east, y north, z up), centred with its underside at z = 0. + * options: theme ('dark' | 'light'), and for modules pcb, edge, label, labelSize plus any + * component-specific options (e.g. led {on}, btn {capColor}, pot {knobColor}). + */ +const buildComponent = (kit, id, options = {}) => recentre(buildRaw(kit, getComponent(id), {theme: 'dark', ...options})); + +/** + * One component as an ordinary three.js Group (Y up), centred on the origin and resting on y = 0. + * options: everything buildComponent takes, plus kit (defaults to a shared one) and scale. + */ +const createComponent = (id, options = {}) => { + const kit = options.kit || defaultKit(); + const tilt = new Group(); + tilt.rotation.x = -Math.PI / 2; + tilt.add(buildComponent(kit, id, options)); + const outer = new Group(); + outer.name = id; + outer.scale.setScalar(options.scale || 1); + outer.add(tilt); + outer.userData.component = id; + return outer; +}; + +const cardCablePoint = (cardX, cardY, side) => { + if (side === 'top') { + return {x: cardX + (CARD.w / 2), y: cardY + CARD.h}; + } + if (side === 'bottom') { + return {x: cardX + (CARD.w / 2), y: cardY}; + } + if (side === 'left') { + return {x: cardX + CARD.w, y: cardY + (CARD.h / 2)}; + } + return {x: cardX, y: cardY + (CARD.h / 2)}; +}; + +/** + * The ESP32 board with one component plugged into a jack (its default jack unless portId is + * given), cable and lit copper trace included. Board space, studio world coordinates. + */ +const buildPluggedScene = (kit, id, {theme = 'dark', portId, ...options} = {}) => { + const scene = buildBoardScene(kit, {theme}); + const comp = getComponent(id); + if (comp.kind === 'board' || comp.kind === 'part') { + return scene; + } + const port = PORTS.find(p => p.id === (portId || comp.defaultPort)) || PORTS[0]; + const K = THEMES[theme] || THEMES.dark; + const color = port.kind === 'analog' ? K.analog : K.digital; + const dir = OUTWARD[port.side] || OUTWARD.right; + const pos = port.pos; + + (TRACE_POINTS[port.id] || []).forEach(line => { + const tint = new Mesh(Kit.ribbon(line, 1.6, 0.06), kit.basic({color, opacity: 0.6, doubleSide: true})); + tint.renderOrder = 1; + scene.add(tint); + }); + + let to; + if (comp.kind === 'card') { + scene.add(comp.buildCard(kit, {theme, x: pos.cardX, y: pos.cardY, z: TABLE_Z})); + to = {...cardCablePoint(pos.cardX, pos.cardY, port.side), z: TABLE_Z + (CARD_T / 2)}; + } else { + const group = buildModule(kit, comp, options); + const placement = placeModule(group.userData.spec, port); + const [cx, cy] = at(placement.cx, placement.cy); + group.position.set(cx, cy, TABLE_Z); + // SVG rotate() is clockwise with y down; board space has y up + group.rotation.z = -placement.rotation * (Math.PI / 180); + scene.add(group); + to = {...placement.jack, z: TABLE_Z + PCB_H + MOUTH_Z}; + } + scene.add(buildCable(kit, {from: {x: pos.cableX, y: pos.cableY, z: MOUTH_Z, dir}, to: {...to, dir}, color})); + scene.userData.port = port; + return scene; +}; + +let topKit = null; + +/** + * Vector top view of a component as an SVG string (board units, y down). + * options: plugged, portId and theme, the SVG options scale, padding, background, shade, title and + * embedAsset (see top-svg.js), plus any component options (e.g. pot {knobColor}). + */ +const toTopSVG = (id, {plugged = false, portId, scale, padding, background, shade, title, embedAsset, idPrefix, kit, ...options} = {}) => { + if (!kit) { + topKit = topKit || new Kit(new TextureBank({headless: true})); + } + const k = kit || topKit; + const root = plugged ? + buildPluggedScene(k, id, {theme: 'dark', ...options, portId}) : + buildComponent(k, id, options); + const svg = objectToTopSVG(root, {scale, padding, background, shade, title: title || getComponent(id).name, embedAsset, idPrefix}); + disposeTree(root); + return svg; +}; + +/** Viewer shortcuts: show one component on its own or plugged into the board. */ +Viewer.prototype.showComponent = function (id, options = {}) { + return this.show((kit, {theme}) => buildComponent(kit, id, {...options, theme})); +}; +Viewer.prototype.showPlugged = function (id, options = {}) { + return this.show((kit, {theme}) => buildPluggedScene(kit, id, {...options, theme})); +}; + +export { + COMPONENTS, + MODELS, + PORTS, + THEMES, + getComponent, + buildComponent, + createComponent, + buildPluggedScene, + toTopSVG, + objectToTopSVG, + onTexturesChanged, + createViewer, + Viewer, + Kit, + TextureBank, + buildCable, + buildModule, + placeModule, + disposeTree +}; diff --git a/module-test/lib/kit.js b/module-test/lib/kit.js new file mode 100644 index 00000000000..4fbe3e908fa --- /dev/null +++ b/module-test/lib/kit.js @@ -0,0 +1,297 @@ +import { + AdditiveBlending, + BoxGeometry, + BufferGeometry, + CylinderGeometry, + DoubleSide, + ExtrudeGeometry, + Float32BufferAttribute, + FrontSide, + LatheGeometry, + Mesh, + MeshBasicMaterial, + MeshStandardMaterial, + NormalBlending, + PlaneGeometry, + Shape, + ShapeGeometry, + Vector2 +} from 'three'; + +/** + * Board space: x east, y north (the inverse of SVG's y-down), z up, in board units. + * Everything is built in a root group that the scene turns so z points up. + * at(x, y) converts an SVG/world point to board space. + */ +const at = (x, y) => [x, -y]; + +const roundedRect = (w, d, r) => { + const s = new Shape(); + const rr = Math.max(0, Math.min(r, w / 2, d / 2)); + s.moveTo(rr, 0); + s.lineTo(w - rr, 0); + s.quadraticCurveTo(w, 0, w, rr); + s.lineTo(w, d - rr); + s.quadraticCurveTo(w, d, w - rr, d); + s.lineTo(rr, d); + s.quadraticCurveTo(0, d, 0, d - rr); + s.lineTo(0, rr); + s.quadraticCurveTo(0, 0, rr, 0); + return s; +}; + +/** Closed outline from SVG-style points (y down) inside a w × d box, as a Shape in slab coordinates. */ +const outlineShape = (points, d) => new Shape(points.map(([px, py]) => new Vector2(px, d - py))); + +const markShared = thing => { + thing.userData.shared = true; + return thing; +}; + +/** Frees everything under `root` that isn't cached in a Kit or TextureBank. */ +const disposeTree = root => { + root.traverse(obj => { + if (obj.geometry && !obj.geometry.userData.shared) { + obj.geometry.dispose(); + } + if (obj.material) { + (Array.isArray(obj.material) ? obj.material : [obj.material]).forEach(m => { + if (m.userData.shared) { + return; + } + if (m.map && !m.map.userData.shared) { + m.map.dispose(); + } + m.dispose(); + }); + } + }); +}; + +/** Shared materials, geometries and the part builders that use them. */ +class Kit { + constructor (textures) { + this.tex = textures; + this.mats = new Map(); + this.geos = new Map(); + } + + geo (key, make) { + if (!this.geos.has(key)) { + this.geos.set(key, markShared(make())); + } + return this.geos.get(key); + } + + /** Standard (lit) material; spec is a colour string or {color, rough, metal, map, emissive, ...}. */ + mat (spec) { + if (spec && spec.isMaterial) { + return spec; + } + const s = typeof spec === 'string' ? {color: spec} : (spec || {}); + const key = [ + 'std', s.color, s.rough, s.metal, s.map ? s.map.uuid : '', s.emissive, s.emissiveIntensity, + s.opacity, s.side, s.alpha + ].join('|'); + if (!this.mats.has(key)) { + const m = new MeshStandardMaterial({ + color: s.map && !s.color ? '#ffffff' : (s.color || '#ffffff'), + roughness: s.rough === undefined ? 0.6 : s.rough, + metalness: s.metal === undefined ? 0 : s.metal, + map: s.map || null, + emissive: s.emissive || '#000000', + emissiveIntensity: s.emissiveIntensity === undefined ? 1 : s.emissiveIntensity, + transparent: s.opacity !== undefined && s.opacity < 1 ? true : Boolean(s.map && s.alpha), + opacity: s.opacity === undefined ? 1 : s.opacity, + side: s.side === undefined ? 0 : s.side + }); + this.mats.set(key, markShared(m)); + } + return this.mats.get(key); + } + + /** Unlit material for glows, printed decals and anything that should keep its exact colour. */ + basic ({color = '#ffffff', map = null, opacity = 1, additive = false, doubleSide = false}) { + const key = ['basic', color, map ? map.uuid : '', opacity, additive, doubleSide].join('|'); + if (!this.mats.has(key)) { + const m = new MeshBasicMaterial({ + color, + map, + transparent: true, + opacity, + depthWrite: false, + blending: additive ? AdditiveBlending : NormalBlending, + side: doubleSide ? DoubleSide : FrontSide, + toneMapped: false + }); + this.mats.set(key, markShared(m)); + } + return this.mats.get(key); + } + + /** + * Cuboid with its footprint at (x, y) world units, w across, d deep, h tall, base at z. + * faces: {t, s, n, e, w, b} material specs; `color` fills any face not listed. + */ + box ({x, y, w, d, h, z = 0, color = '#888888', faces = {}, shadow = true}) { + const geom = this.geo(`box:${w}:${d}:${h}`, () => new BoxGeometry(w, d, h)); + const pick = k => this.mat(faces[k] || color); + // BoxGeometry face order: +x, -x, +y, -y, +z, -z + const mesh = new Mesh(geom, [pick('e'), pick('w'), pick('n'), pick('s'), pick('t'), pick('b')]); + const [px, py] = at(x + (w / 2), y + (d / 2)); + mesh.position.set(px, py, z + (h / 2)); + mesh.castShadow = shadow; + mesh.receiveShadow = true; + return mesh; + } + + /** + * Rounded-corner slab (or any outline: SVG-style [x, y] points inside the w × d box); + * the top texture spans the whole footprint (u: west→east, v: south→north). */ + slab ({x, y, w, d, h, z = 0, r = 2, top, side, shadow = true, outline}) { + const key = outline ? `slab:${w}:${d}:${h}:o:${outline.map(pt => pt.join(',')).join(';')}` : `slab:${w}:${d}:${h}:${r}`; + const geom = this.geo(key, () => { + const shape = outline ? outlineShape(outline, d) : roundedRect(w, d, r); + const g = new ExtrudeGeometry(shape, {depth: h, bevelEnabled: false, curveSegments: 6}); + const uv = g.attributes.uv; + for (let i = 0; i < uv.count; i++) { + uv.setXY(i, uv.getX(i) / w, uv.getY(i) / d); + } + return g; + }); + const mesh = new Mesh(geom, [this.mat(top), this.mat(side)]); + const [px, py] = at(x, y + d); + mesh.position.set(px, py, z); + mesh.castShadow = shadow; + mesh.receiveShadow = true; + return mesh; + } + + /** Upright cylinder centred at (cx, cy) from z0 to z1. */ + cylinder ({cx, cy, r, z0, z1, side, top, bottom, seg = 32, r1}) { + const h = Math.max(0.01, z1 - z0); + const rTop = r1 === undefined ? r : r1; + const geom = this.geo(`cyl:${rTop}:${r}:${h}:${seg}`, () => { + const g = new CylinderGeometry(rTop, r, h, seg, 1, false); + g.rotateX(Math.PI / 2); + return g; + }); + const sideM = this.mat(side); + const mesh = new Mesh(geom, [sideM, this.mat(top || side), this.mat(bottom || side)]); + const [px, py] = at(cx, cy); + mesh.position.set(px, py, (z0 + z1) / 2); + mesh.castShadow = true; + mesh.receiveShadow = true; + return mesh; + } + + /** Solid of revolution from [radius, height] pairs, standing at (cx, cy) on z. */ + lathe ({key, cx, cy, z = 0, profile, material, seg = 32}) { + const geom = this.geo(`lathe:${key}:${seg}`, () => { + const g = new LatheGeometry(profile.map(([r, hh]) => new Vector2(r, hh)), seg); + g.rotateX(Math.PI / 2); + return g; + }); + const mesh = new Mesh(geom, this.mat(material)); + const [px, py] = at(cx, cy); + mesh.position.set(px, py, z); + mesh.castShadow = true; + mesh.receiveShadow = true; + return mesh; + } + + /** Flat horizontal decal with its footprint at (x, y), facing up at height z. */ + decal ({x, y, w, d, z, material, receive = true}) { + const geom = this.geo(`plane:${w}:${d}`, () => new PlaneGeometry(w, d)); + const mesh = new Mesh(geom, material.isMaterial ? material : this.mat(material)); + const [px, py] = at(x + (w / 2), y + (d / 2)); + mesh.position.set(px, py, z); + mesh.receiveShadow = receive; + return mesh; + } + + /** + * Upright decal on the outside of a box face. The box footprint is (x, y, w, d), its base at z, + * h tall; `face` is 's' | 'n' | 'e' | 'w'; span is the decal width along the face (centred). + */ + sideDecal ({face, x, y, w, d, z, h, span, material}) { + const along = face === 's' || face === 'n' ? w : d; + const width = span || along; + const geom = this.geo(`side:${width}:${h}`, () => { + const g = new PlaneGeometry(width, h); + g.rotateX(Math.PI / 2); + return g; + }); + const mesh = new Mesh(geom, material.isMaterial ? material : this.mat(material)); + const eps = 0.04; + const [cx, cy] = at(x + (w / 2), y + (d / 2)); + const rot = {s: 0, n: Math.PI, e: Math.PI / 2, w: -Math.PI / 2}[face]; + const off = {s: [0, -(d / 2) - eps], n: [0, (d / 2) + eps], e: [(w / 2) + eps, 0], w: [-(w / 2) - eps, 0]}[face]; + mesh.rotation.z = rot; + mesh.position.set(cx + off[0], cy + off[1], z + (h / 2)); + return mesh; + } + + /** Rounded-rectangle outline ring around a footprint (for jack highlights). */ + ring ({w, d, r, width}) { + return this.geo(`ring:${w}:${d}:${r}:${width}`, () => { + const outer = roundedRect(w + (width * 2), d + (width * 2), r + width); + const hole = roundedRect(w, d, r); + const inner = new Shape(hole.getPoints(6).map(p => new Vector2(p.x + width, p.y + width)).reverse()); + outer.holes.push(inner); + const g = new ShapeGeometry(outer, 6); + g.translate(-(w / 2) - width, -(d / 2) - width, 0); + return g; + }); + } + + /** + * Flat ribbon along a polyline of world points, `width` wide at height z. + * Not cached: each live trace has its own. + */ + static ribbon (points, width, z) { + const pos = []; + const idx = []; + const half = width / 2; + for (let i = 0; i < points.length; i++) { + const [ax, ay] = points[Math.max(0, i - 1)]; + const [bx, by] = points[Math.min(points.length - 1, i + 1)]; + const dx = bx - ax; + const dy = by - ay; + const len = Math.hypot(dx, dy) || 1; + const nx = -dy / len; + const ny = dx / len; + const [px, py] = points[i]; + pos.push(px + (nx * half), -(py + (ny * half)), z, px - (nx * half), -(py - (ny * half)), z); + if (i > 0) { + const k = i * 2; + idx.push(k - 2, k - 1, k, k - 1, k + 1, k); + } + } + const g = new BufferGeometry(); + g.setAttribute('position', new Float32BufferAttribute(pos, 3)); + g.setIndex(idx); + g.computeVertexNormals(); + return g; + } + + /** Free cached materials matching `test` (e.g. ones whose texture was evicted). */ + dropMaterials (test) { + this.mats.forEach((m, key) => { + if (test(m)) { + m.dispose(); + this.mats.delete(key); + } + }); + } + + dispose () { + this.mats.forEach(m => m.dispose()); + this.geos.forEach(g => g.dispose()); + this.mats.clear(); + this.geos.clear(); + } +} + +export {at, roundedRect, outlineShape, disposeTree}; +export default Kit; diff --git a/module-test/lib/parts.js b/module-test/lib/parts.js new file mode 100644 index 00000000000..86709b73147 --- /dev/null +++ b/module-test/lib/parts.js @@ -0,0 +1,333 @@ +import {AdditiveBlending, Group, MeshBasicMaterial} from 'three'; + +import {JACK, JACK_H, PCB_H} from './board-data.js'; + +/** Height of a module's PCB surface; module parts stand on it. */ +const TOP = PCB_H; +const JACK_R = 3.5; +const BLACK = {color: '#151617', rough: 0.45}; +const METAL = {color: '#c9ccce', rough: 0.32, metal: 0.85}; + +// ---- Textures --------------------------------------------------------------- + +/** Soft round glow, white so a material colour can tint it. */ +const glowTexture = kit => kit.tex.canvas('glow', 16, 16, (ctx, w, h) => { + const g = ctx.createRadialGradient(w / 2, h / 2, 0, w / 2, h / 2, w / 2); + g.addColorStop(0, 'rgba(255,255,255,1)'); + g.addColorStop(0.35, 'rgba(255,255,255,0.42)'); + g.addColorStop(1, 'rgba(255,255,255,0)'); + ctx.fillStyle = g; + ctx.fillRect(0, 0, w, h); +}, { + ppu: 8, + svg: '' + + '' + + '' +}); + +/** A glow decal with its own material so its opacity can animate. */ +const glowDecal = (kit, {cx, cy, size, z, color, opacity = 0.9}) => { + const material = new MeshBasicMaterial({ + color, + map: glowTexture(kit), + transparent: true, + opacity, + depthWrite: false, + blending: AdditiveBlending, + toneMapped: false + }); + return kit.decal({x: cx - (size / 2), y: cy - (size / 2), w: size, d: size, z, material, receive: false}); +}; + +/** Two-tone SMD top: metal end caps around a body. */ +const passiveTexture = (kit, kind, horizontal) => kit.tex.canvas(`passive:${kind}:${horizontal ? 'h' : 'v'}`, 12, 12, (ctx, w, h) => { + ctx.fillStyle = kind === 'C' ? '#b08657' : '#161616'; + ctx.fillRect(0, 0, w, h); + ctx.fillStyle = '#d2d3d0'; + if (horizontal) { + ctx.fillRect(0, 0, w * 0.22, h); + ctx.fillRect(w * 0.78, 0, w * 0.22, h); + } else { + ctx.fillRect(0, 0, w, h * 0.22); + ctx.fillRect(0, h * 0.78, w, h * 0.22); + } +}, { + svg: `` + (horizontal ? + '' : + '') +}); + +/** Dotted wire mesh over a base colour, drawn to scale (pitch in board units). */ +const meshTexture = (kit, key, w, h, pitch, base, dot) => kit.tex.canvas(`mesh:${key}`, w, h, (ctx, cw, ch) => { + const s = cw / w; + ctx.fillStyle = base; + ctx.fillRect(0, 0, cw, ch); + ctx.fillStyle = dot; + const r = pitch * 0.3 * s; + for (let y = pitch / 2; y < h; y += pitch) { + for (let x = pitch / 2; x < w; x += pitch) { + ctx.beginPath(); + ctx.arc(x * s, y * s, r, 0, Math.PI * 2); + ctx.fill(); + } + } +}, { + ppu: 10, + svg: `` + + `` + + `` +}); + +/** IC package top with an optional pin-1 dot (SVG markup in a w × d box). */ +const chipTopSvg = (w, d, dot) => `` + + `` + + `` + + `${dot ? `` : ''}`; + +/** Top of an RJ11 housing, mouth at x = 0, D deep and Wd across, with a colour stripe at the back. */ +const jackTopSvg = (D, Wd, color) => { + const pins = [0, 1, 2, 3, 4, 5].map(i => { + const cy = (Wd * 0.28) + (i * ((Wd * 0.44) / 5)); + return `' + + ``; + }).join(''); + return '' + + '' + + `` + + `` + + `` + + `` + + `` + + `` + + `` + + pins; +}; + +/** The mouth the plug goes into, cropped to `span` of the Wd-wide face, H tall. */ +const jackMouthSvg = (Wd, H, span) => { + const pins = [0, 1, 2, 3, 4, 5].map(i => { + const x = (Wd * 0.29) + (i * ((Wd * 0.42) / 5)); + return `'; + }).join(''); + return `` + + `` + + `` + + `` + + `${pins}`; +}; + +// ---- Parts ------------------------------------------------------------------ + +/** Unshared copy of a cached material, freed with the mesh that owns it. */ +const ownCopy = m => { + const copy = m.clone(); + copy.userData.shared = false; + return copy; +}; + +/** + * RJ11 housing in its own frame: mouth on the west face, D deep (x) by Wd across (y), centred on + * the origin. Board jacks and module sockets are the same part. + */ +const buildJack = (kit, {color, D = JACK.w, Wd = JACK.h}) => { + const group = new Group(); + const top = kit.tex.svg(`jack-top:${color}:${D}:${Wd}`, D, Wd, jackTopSvg(D, Wd, color), {ppu: 8, base: '#161616'}); + const housing = kit.slab({ + x: -D / 2, + y: -Wd / 2, + w: D, + d: Wd, + h: JACK_H, + r: JACK_R, + top: {map: top, rough: 0.5}, + side: {color: '#141414', rough: 0.5} + }); + group.add(housing); + + const span = Wd * 0.84; + const mouth = kit.tex.svg(`jack-mouth:${Wd}`, span, JACK_H, jackMouthSvg(Wd, JACK_H, span), {ppu: 8, base: '#161616'}); + group.add(kit.sideDecal({ + face: 'w', + x: -D / 2, + y: -Wd / 2, + w: D, + d: Wd, + z: 0, + h: JACK_H, + span, + material: {map: mouth, rough: 0.5} + })); + group.userData.housing = housing; + return group; +}; + +const resistor = (kit, g, x, y) => g.add(kit.box({ + x, + y, + w: 10, + d: 5, + h: 2.2, + z: TOP, + color: '#121212', + faces: {t: {map: passiveTexture(kit, 'R', true), rough: 0.45}} +})); + +const chip = (kit, g, x, y, w, d, h = 2.4) => g.add(kit.box({ + x, + y, + w, + d, + h, + z: TOP, + color: {color: '#151617', rough: 0.45}, + faces: {t: {map: kit.tex.svg(`chip:${w}:${d}`, w, d, chipTopSvg(w, d), {ppu: 8, base: '#1a1b1d'}), rough: 0.45}} +})); + +/** Gull-wing legs along the north and/or south side of a package (x, y is the body's corner). */ +const legs = (kit, g, {x, y, w, d, north = 0, south = 0, size = [1.1, 1.8]}) => { + const [lw, ld] = size; + [[north, y - ld + 0.2], [south, y + d - 0.2]].forEach(([n, ly]) => { + for (let i = 0; i < n; i++) { + const lx = x + ((w / n) * (i + 0.5)) - (lw / 2); + g.add(kit.box({x: lx, y: ly, w: lw, d: ld, h: 0.45, z: TOP, color: METAL, shadow: false})); + } + }); +}; + +/** SOIC IC (e.g. SOIC-8 with pins: 4 per side), pin-1 dot at the north-west corner. */ +const soic = (kit, g, {x, y, w = 10, d = 8, pins = 4, h = 1.8}) => { + legs(kit, g, {x, y, w, d, north: pins, south: pins}); + g.add(kit.box({ + x, y, w, d, h, z: TOP + 0.3, + color: {color: '#151617', rough: 0.45}, + faces: {t: {map: kit.tex.svg(`soic:${w}:${d}`, w, d, chipTopSvg(w, d, {x: 1.8, y: 1.8}), {ppu: 10, base: '#1a1b1d'}), rough: 0.45}} + })); +}; + +/** SOT-23 (three legs: two south, one north), e.g. a small regulator. */ +const sot23 = (kit, g, {x, y, w = 6, d = 3.4}) => { + legs(kit, g, {x, y, w, d, south: 2, size: [1, 1.5]}); + legs(kit, g, {x: x + (w / 3), y, w: w / 3, d, north: 1, size: [1, 1.5]}); + g.add(kit.box({x, y, w, d, h: 1.3, z: TOP + 0.2, color: {color: '#151617', rough: 0.45}})); +}; + +/** Small SMD capacitor (tan body, metal ends). */ +const capacitor = (kit, g, x, y, horizontal = true) => g.add(kit.box({ + x, + y, + w: horizontal ? 6 : 3.4, + d: horizontal ? 3.4 : 6, + h: 1.8, + z: TOP, + color: '#8a6641', + faces: {t: {map: passiveTexture(kit, 'C', horizontal), rough: 0.45}} +})); + +/** + * Cylinder lying along +x from x0 to x1 (world units), centred on (cy, cz). + * `top` is the cap facing +x, `bottom` the cap facing -x. + */ +const axial = (kit, {x0, x1, cy, cz, r, side, top, bottom, seg = 40}) => { + const mesh = kit.cylinder({cx: 0, cy: 0, r, z0: 0, z1: x1 - x0, side, top, bottom, seg}); + mesh.rotation.y = Math.PI / 2; + mesh.position.set((x0 + x1) / 2, -cy, cz); + return mesh; +}; + +/** Fine lengthwise ridges for knurled knobs and threaded bushings (around × along, in units). */ +const ridgeTexture = (kit, key, around, along, pitch, base, ridge) => kit.tex.canvas(`ridge:${key}`, around, along, (ctx, cw, ch) => { + const s = cw / around; + ctx.fillStyle = base; + ctx.fillRect(0, 0, cw, ch); + ctx.fillStyle = ridge; + for (let x = 0; x < around; x += pitch) { + ctx.fillRect(x * s, 0, pitch * 0.45 * s, ch); + } +}, { + ppu: 8, + svg: `` + + `` + + `` +}); + +const TRIMMER_SVG = '' + + '' + + ''; + +const trimmer = (kit, g, x, y) => g.add(kit.box({ + x, + y, + w: 10, + d: 10, + h: 6, + z: TOP, + color: {color: '#2a62bf', rough: 0.45}, + faces: {t: {map: kit.tex.svg('trimmer', 10, 10, TRIMMER_SVG, {ppu: 12, base: '#2f6fd6'}), rough: 0.4}} +})); + +const smdLed = (kit, g, x, y, color) => g.add(kit.box({ + x, + y, + w: 4, + d: 3, + h: 1.2, + z: TOP, + color: {color: '#e8e5dc', rough: 0.4}, + faces: {t: kit.basic({color})} +})); + +const crystal = (kit, g, x, y, w, d) => g.add(kit.slab({ + x, + y, + w, + d, + h: 3, + z: TOP, + r: d / 2, + top: {color: '#d9dbdd', rough: 0.25, metal: 0.9}, + side: {color: '#a9acaf', rough: 0.3, metal: 0.9} +})); + +/** Metal can with a mesh top and a perforated wall. */ +const meshCan = (kit, g, {key, cx, cy, r, z0, z1, pitch, topBase, topDot}) => { + const h = z1 - z0; + const circ = Math.PI * 2 * r; + g.add(kit.cylinder({ + cx, + cy, + r, + z0, + z1, + seg: 40, + side: {map: meshTexture(kit, `${key}-wall`, circ, h, pitch, '#c3c6c9', '#6d7174'), rough: 0.35, metal: 0.8}, + top: {map: meshTexture(kit, `${key}-top`, r * 2, r * 2, pitch, topBase, topDot), rough: 0.5, metal: 0.4} + })); +}; + +export { + TOP, + BLACK, + METAL, + glowTexture, + glowDecal, + passiveTexture, + meshTexture, + chipTopSvg, + jackTopSvg, + jackMouthSvg, + ownCopy, + buildJack, + resistor, + chip, + soic, + sot23, + axial, + ridgeTexture, + capacitor, + trimmer, + smdLed, + crystal, + meshCan +}; diff --git a/module-test/lib/pcb.js b/module-test/lib/pcb.js new file mode 100644 index 00000000000..093a37d2248 --- /dev/null +++ b/module-test/lib/pcb.js @@ -0,0 +1,127 @@ +import {Group} from 'three'; + +import {JACK, PCB_H, STUB} from './board-data.js'; +import {at} from './kit.js'; +import {buildJack} from './parts.js'; + +const SILK_FONT = '"Arial Narrow", "Roboto Condensed", system-ui, sans-serif'; +const SOCKET_COLOR = '#8d9093'; +/** House style: every TinkerBit module uses the same purple PCB (override per call with options.pcb / options.edge). */ +const PCB_COLOR = '#552a8a'; +const PCB_EDGE = '#341656'; +const ROTATION_BY_SIDE = {top: -90, bottom: 90, right: 0, left: 180}; + +const escapeText = s => String(s).replace(/&/g, '&').replace(//g, '>'); + +/** The board's label; a "\n" in it starts a new line (lines are centred on labelAt). */ +const labelSvg = spec => { + const size = spec.labelSize || 5.5; + const lines = String(spec.label).split('\n'); + const lead = size * 1.25; + const y0 = spec.labelAt[1] - (((lines.length - 1) * lead) / 2); + return lines.map((line, i) => ( + `${escapeText(line)}` + )).join(''); +}; + +/** PCB top: optional silkscreen, two mounting holes on the far edge and the board's label. */ +const pcbTopSvg = spec => { + const holes = (spec.holes || [[spec.w - 6, 6], [spec.w - 6, spec.h - 6]]).map(([hx, hy]) => ( + `` + )).join(''); + return `` + + `${spec.silk || ''}${holes}` + + `${labelSvg(spec)}`; +}; + +/** A component's spec with any caller overrides (pcb, edge, label, labelSize) applied. */ +const resolveSpec = (spec, options = {}) => { + const out = {pcb: PCB_COLOR, edge: PCB_EDGE, ...spec}; + ['pcb', 'edge', 'label', 'labelSize'].forEach(key => { + if (options[key] !== undefined && options[key] !== null) { + out[key] = options[key]; + } + }); + return out; +}; + +/** + * A module board: PCB slab, grey RJ11 socket on the west edge at jackY, then the component's own + * parts. Returns a group with the PCB centred on the origin and its underside at z = 0 (board space). + */ +const buildModule = (kit, component, options = {}) => { + const spec = resolveSpec(component.spec, options); + const outer = new Group(); + outer.name = component.id; + + const g = new Group(); + const [ox, oy] = at(-spec.w / 2, -spec.h / 2); + g.position.set(ox, oy, 0); + outer.add(g); + + const key = ['pcb', component.id, spec.pcb, spec.label, spec.labelSize || ''].join(':'); + g.add(kit.slab({ + x: 0, + y: 0, + w: spec.w, + d: spec.h, + h: PCB_H, + r: 2, + outline: spec.outline, + top: {map: kit.tex.svg(key, spec.w, spec.h, pcbTopSvg(spec), {ppu: 6, base: spec.pcb}), rough: 0.6}, + side: {color: spec.edge, rough: 0.7} + })); + + const socket = buildJack(kit, {color: SOCKET_COLOR}); + const [sx, sy] = at(-2 + (JACK.w / 2), spec.jackY); + socket.position.set(sx, sy, PCB_H); + g.add(socket); + + component.build(kit, g, {spec, options}); + outer.userData.spec = spec; + return outer; +}; + +/** + * Places a module of w × h world units, socket on its left edge at jackY, so the socket faces + * the board jack, then applies a drag offset. Returns the centre, rotation (degrees, clockwise + * in SVG space), rotated bounding box and the world point of the socket. + */ +const placeModule = ({w, h, jackY: socketY}, port, offsetX = 0, offsetY = 0) => { + const pos = port.pos; + const rotation = ROTATION_BY_SIDE[port.side] || 0; + const reach = STUB + (w / 2); + let cx = pos.cableX; + let cy = pos.cableY; + if (port.side === 'top') { + cy -= reach; + } else if (port.side === 'bottom') { + cy += reach; + } else if (port.side === 'left') { + cx -= reach; + } else { + cx += reach; + } + cx += offsetX; + cy += offsetY; + + const localX = -w / 2; + const localY = socketY - (h / 2); + const rad = rotation * (Math.PI / 180); + const jackX = cx + (localX * Math.cos(rad)) - (localY * Math.sin(rad)); + const jackY = cy + (localX * Math.sin(rad)) + (localY * Math.cos(rad)); + const upright = rotation === 0 || rotation === 180; + return { + cx, + cy, + w, + h, + rotation, + boxW: upright ? w : h, + boxH: upright ? h : w, + jack: {x: jackX, y: jackY} + }; +}; + +export {PCB_COLOR, PCB_EDGE, SILK_FONT, pcbTopSvg, resolveSpec, buildModule, placeModule}; diff --git a/module-test/lib/textures.js b/module-test/lib/textures.js new file mode 100644 index 00000000000..e3654c4f233 --- /dev/null +++ b/module-test/lib/textures.js @@ -0,0 +1,205 @@ +import {CanvasTexture, SRGBColorSpace, Texture} from 'three'; + +import {TEXTURES} from './board-data.js'; + +const SVG_NS = 'http://www.w3.org/2000/svg'; +/** SVG drawn as an image can't use the page's web fonts, so name local ones first. */ +const FONT = '"Segoe UI", Inter, system-ui, -apple-system, Roboto, "Helvetica Neue", Arial, sans-serif'; +const MAX_EDGE = 4096; + +const makeCanvas = (w, h) => { + const canvas = document.createElement('canvas'); + canvas.width = w; + canvas.height = h; + return canvas; +}; + +const paint = (canvas, color) => { + const ctx = canvas.getContext('2d'); + ctx.clearRect(0, 0, canvas.width, canvas.height); + if (color) { + ctx.fillStyle = color; + ctx.fillRect(0, 0, canvas.width, canvas.height); + } +}; + +const escapeAttr = s => String(s).replace(/&/g, '&').replace(/"/g, '"').replace(/ this.listeners.delete(fn); + } + + changed () { + this.listeners.forEach(fn => fn()); + } + + wrap (canvas) { + const tex = new CanvasTexture(canvas); + tex.colorSpace = SRGBColorSpace; + tex.anisotropy = this.anisotropy; + tex.userData.shared = true; + return tex; + } + + size (w, h, ppu) { + const scale = Math.min(ppu, this.maxEdge / w, this.maxEdge / h); + return {cw: Math.max(2, Math.round(w * scale)), ch: Math.max(2, Math.round(h * scale))}; + } + + /** Draws an image source (data URL or file URL) into a cached canvas texture. */ + image (key, w, h, src, {ppu = 4, base = null, fallback = base, crossOrigin = false} = {}) { + if (this.cache.has(key)) { + return this.cache.get(key); + } + if (this.headless) { + const blank = new Texture(); + blank.userData.shared = true; + this.cache.set(key, blank); + return blank; + } + const {cw, ch} = this.size(w, h, ppu); + const canvas = makeCanvas(cw, ch); + paint(canvas, base); + const tex = this.wrap(canvas); + this.cache.set(key, tex); + this.pending += 1; + + const settle = drawn => { + this.pending -= 1; + if (this.disposed) { + return; + } + if (!drawn) { + const clean = makeCanvas(cw, ch); + paint(clean, fallback); + tex.image = clean; + } + tex.needsUpdate = true; + this.changed(); + }; + + const img = new Image(); + if (crossOrigin) { + img.crossOrigin = 'anonymous'; + } + img.onload = () => { + if (this.disposed) { + return; + } + try { + const ctx = canvas.getContext('2d'); + ctx.clearRect(0, 0, cw, ch); + if (base) { + ctx.fillStyle = base; + ctx.fillRect(0, 0, cw, ch); + } + ctx.drawImage(img, 0, 0, cw, ch); + // Throws if the canvas got tainted; a tainted canvas would also fail the GPU upload. + ctx.getImageData(0, 0, 1, 1); + settle(true); + } catch (e) { + settle(false); + } + }; + img.onerror = () => settle(false); + img.src = src; + return tex; + } + + /** SVG markup (the inside of an ) laid out in a w × h unit box. */ + svg (key, w, h, inner, opts = {}) { + const {cw, ch} = this.size(w, h, opts.ppu || 4); + const markup = `${inner}`; + const tex = this.image(key, w, h, `data:image/svg+xml;charset=utf-8,${encodeURIComponent(markup)}`, opts); + tex.userData.svg = {w, h, inner, font: FONT}; + return tex; + } + + /** One of the exported studio artworks in assets/svg (see board-data.js TEXTURES). */ + asset (name, opts = {}) { + const info = TEXTURES[name]; + if (!info) { + throw new Error(`Unknown texture asset: ${name}`); + } + const url = new URL(info.file, TextureBank.assetRoot || document.baseURI).href; + const tex = this.image(`asset:${name}`, info.w, info.h, url, {ppu: info.ppu, base: info.base, ...opts}); + tex.userData.asset = {name, file: info.file, url, w: info.w, h: info.h}; + return tex; + } + + /** + * Synchronous 2D-canvas texture; draw(ctx, cw, ch) paints in pixels. + * svg: the same picture as SVG markup in a w × h box, used by the vector top view. + */ + canvas (key, w, h, draw, {ppu = 8, svg = null} = {}) { + if (this.cache.has(key)) { + return this.cache.get(key); + } + let tex; + if (this.headless) { + tex = new Texture(); + tex.userData.shared = true; + } else { + const {cw, ch} = this.size(w, h, ppu); + const canvas = makeCanvas(cw, ch); + draw(canvas.getContext('2d'), cw, ch); + tex = this.wrap(canvas); + } + if (svg) { + tex.userData.svg = {w, h, inner: svg, font: FONT}; + } + this.cache.set(key, tex); + return tex; + } + + /** Drop textures whose key starts with prefix; returns them. */ + evict (prefix) { + const gone = []; + Array.from(this.cache.keys()).forEach(key => { + if (key.indexOf(prefix) === 0) { + const tex = this.cache.get(key); + tex.dispose(); + this.cache.delete(key); + gone.push(tex); + } + }); + return gone; + } + + dispose () { + this.disposed = true; + this.cache.forEach(tex => tex.dispose()); + this.cache.clear(); + this.listeners.clear(); + } +} + +/** Base URL that asset() resolves files against (lib/index.js points it at module-test/). */ +TextureBank.assetRoot = null; + +export {FONT}; +export default TextureBank; diff --git a/module-test/lib/top-svg.js b/module-test/lib/top-svg.js new file mode 100644 index 00000000000..65d6970bdca --- /dev/null +++ b/module-test/lib/top-svg.js @@ -0,0 +1,262 @@ +import {AdditiveBlending, Color, DoubleSide, Matrix4, Vector3} from 'three'; + +/* + * Vector top view of any board-space object (x east, y north, z up): every face that points up is + * flattened to an SVG path and drawn lowest first. Faces with an SVG-sourced texture reuse that + * markup, clipped to the face, so silk, labels and chip markings stay vector. + * Output is in board units with SVG's y down, the same frame as the studio's 2D board. + */ + +const SVG_NS = 'http://www.w3.org/2000/svg'; +const UP_MIN = 0.02; +const FLAT = 0.995; +const BAND = 0.75; +const LIGHT = new Vector3(-0.35, 0.45, 1).normalize(); +let svgCount = 0; + +const num = n => { + const r = Math.round(n * 100) / 100; + return Object.is(r, -0) ? '0' : String(r); +}; + +const escapeAttr = s => String(s).replace(/&/g, '&').replace(/"/g, '"').replace(/ String(s).replace(/&/g, '&').replace(/ markup + .replace(/\bid="([^"]+)"/g, (m, id) => `id="${prefix}${id}"`) + .replace(/url\(\s*#([^)\s]+)\s*\)/g, (m, id) => `url(#${prefix}${id})`) + .replace(/(\s(?:xlink:)?href)="#([^"]+)"/g, (m, attr, id) => `${attr}="#${prefix}${id}"`); + +/** A complete SVG file as a fragment that fills its parent viewport. */ +const embedFile = markup => markup + .replace(/<\?xml[^>]*>/, '') + .replace(/]*>/i, '') + .replace(/]*)>/, (m, attrs) => ``); + +const colorOf = material => { + const c = material.color ? material.color.clone() : new Color(1, 1, 1); + if (material.emissive && material.emissiveIntensity > 0) { + c.add(material.emissive.clone().multiplyScalar(material.emissiveIntensity)); + } + return c; +}; + +const shaded = (color, f) => { + if (f === 1) { + return `#${color.getHexString()}`; + } + const srgb = {}; + color.getRGB(srgb); + const ch = v => Math.max(0, Math.min(255, Math.round((f > 1 ? v + ((1 - v) * (f - 1)) : v * f) * 255))); + return `rgb(${ch(srgb.r)},${ch(srgb.g)},${ch(srgb.b)})`; +}; + +const isWhite = c => c.r > 0.999 && c.g > 0.999 && c.b > 0.999; + +/** Affine (a b c d e f) taking texture image coordinates to output coordinates, from one triangle. */ +const imageToOut = (tri, w, h) => { + const P = tri.map(p => [p.u * w, (1 - p.v) * h]); + const det = (P[0][0] * (P[1][1] - P[2][1])) - (P[0][1] * (P[1][0] - P[2][0])) + ((P[1][0] * P[2][1]) - (P[2][0] * P[1][1])); + if (Math.abs(det) < 1e-9) { + return null; + } + const solve = vals => { + const [v0, v1, v2] = vals; + const p = (v0 * (P[1][1] - P[2][1])) - (P[0][1] * (v1 - v2)) + ((v1 * P[2][1]) - (v2 * P[1][1])); + const q = (P[0][0] * (v1 - v2)) - (v0 * (P[1][0] - P[2][0])) + ((P[1][0] * v2) - (P[2][0] * v1)); + const r = (P[0][0] * ((P[1][1] * v2) - (P[2][1] * v1))) - (P[0][1] * ((P[1][0] * v2) - (P[2][0] * v1))) + + (v0 * ((P[1][0] * P[2][1]) - (P[2][0] * P[1][1]))); + return [p / det, q / det, r / det]; + }; + const [a, c, e] = solve(tri.map(p => p.X)); + const [b, d, f] = solve(tri.map(p => p.Y)); + return [a, b, c, d, e, f]; +}; + +/** Upward faces of every visible mesh under root, grouped into drawable items. */ +const collect = (root, shade) => { + root.updateWorldMatrix(true, true); + const toRoot = new Matrix4().copy(root.matrixWorld).invert(); + const m = new Matrix4(); + const va = new Vector3(); + const vb = new Vector3(); + const vc = new Vector3(); + const e1 = new Vector3(); + const e2 = new Vector3(); + const n = new Vector3(); + const items = new Map(); + let order = 0; + + root.traverseVisible(mesh => { + if (!mesh.isMesh || !mesh.geometry || mesh.userData.skipTop) { + return; + } + const geom = mesh.geometry; + const pos = geom.attributes.position; + if (!pos) { + return; + } + const uv = geom.attributes.uv; + const index = geom.index; + const materials = Array.isArray(mesh.material) ? mesh.material : [mesh.material]; + const groups = geom.groups.length ? geom.groups : [{start: 0, count: index ? index.count : pos.count, materialIndex: 0}]; + m.multiplyMatrices(toRoot, mesh.matrixWorld); + const mirrored = m.determinant() < 0; + const meshOrder = order++; + + groups.forEach((group, gi) => { + const material = materials[group.materialIndex || 0]; + if (!material || !material.visible || material.isShadowMaterial || material.opacity === 0) { + return; + } + const twoSided = material.side === DoubleSide; + const end = Math.min(group.start + group.count, index ? index.count : pos.count); + for (let i = group.start; i + 2 < end; i += 3) { + const ia = index ? index.getX(i) : i; + const ib = index ? index.getX(i + 1) : i + 1; + const ic = index ? index.getX(i + 2) : i + 2; + va.fromBufferAttribute(pos, ia).applyMatrix4(m); + vb.fromBufferAttribute(pos, ib).applyMatrix4(m); + vc.fromBufferAttribute(pos, ic).applyMatrix4(m); + n.crossVectors(e1.subVectors(vb, va), e2.subVectors(vc, va)); + const len = n.length(); + if (len < 1e-9) { + continue; + } + let nz = (mirrored ? -n.z : n.z) / len; + if (twoSided) { + nz = Math.abs(nz); + } + if (nz <= UP_MIN) { + continue; + } + n.multiplyScalar((mirrored ? -1 : 1) / len); + if (twoSided && n.z < 0) { + n.negate(); + } + const zTop = Math.max(va.z, vb.z, vc.z); + const flat = nz >= FLAT; + let f = 1; + if (shade && !flat) { + f = Math.max(0.45, Math.min(1.12, 0.45 + (0.55 * n.dot(LIGHT) / LIGHT.z))); + f = Math.round(f / 0.06) * 0.06; + } + const key = flat ? `${mesh.id}:${gi}:flat:${num(zTop)}` : `${mesh.id}:${gi}:${Math.floor(zTop / BAND)}:${f}`; + let item = items.get(key); + if (!item) { + item = {material, flat, f, z: zTop, order: meshOrder, tris: []}; + items.set(key, item); + } + item.z = Math.max(item.z, zTop); + const corner = (v, k) => ({X: v.x, Y: -v.y, u: uv ? uv.getX(k) : 0, v: uv ? uv.getY(k) : 0}); + item.tris.push([corner(va, ia), corner(vb, ib), corner(vc, ic)]); + } + }); + }); + return Array.from(items.values()).sort((p, q) => (p.z - q.z) || (p.order - q.order)); +}; + +/** + * Standalone SVG string of root seen from straight above. + * options: scale (px per board unit, default 4), padding (units, default 4), background (CSS colour), + * shade (darken sloped faces, default true), title, embedAsset(asset) => SVG file text (inline + * file-based textures instead of linking them), idPrefix (ids must be unique when several SVGs are + * inlined in one page; defaults to a fresh "tbN-"). + */ +const objectToTopSVG = (root, {scale = 4, padding = 4, background = null, shade = true, title, embedAsset, idPrefix} = {}) => { + const P = idPrefix || `tb${++svgCount}-`; + const items = collect(root, shade); + const defs = []; + const body = []; + const textures = new Map(); + let clipCount = 0; + let minX = Infinity; + let minY = Infinity; + let maxX = -Infinity; + let maxY = -Infinity; + + const textureDef = tex => { + if (textures.has(tex.uuid)) { + return textures.get(tex.uuid); + } + const id = `${P}t${textures.size}`; + let def = null; + const src = tex.userData.svg; + const asset = tex.userData.asset; + if (src) { + def = {id, w: src.w, h: src.h}; + defs.push(`${prefixIds(src.inner, `${id}-`)}`); + } else if (asset) { + def = {id, w: asset.w, h: asset.h}; + const inner = embedAsset ? prefixIds(embedFile(embedAsset(asset)), `${id}-`) : + ``; + defs.push(`${inner}`); + } + textures.set(tex.uuid, def); + return def; + }; + + items.forEach(item => { + let d = ''; + item.tris.forEach(tri => { + tri.forEach(p => { + minX = Math.min(minX, p.X); + minY = Math.min(minY, p.Y); + maxX = Math.max(maxX, p.X); + maxY = Math.max(maxY, p.Y); + }); + d += `M${num(tri[0].X)} ${num(tri[0].Y)}L${num(tri[1].X)} ${num(tri[1].Y)}L${num(tri[2].X)} ${num(tri[2].Y)}Z`; + }); + const mat = item.material; + const color = colorOf(mat); + const opacity = mat.transparent || mat.opacity < 1 ? mat.opacity : 1; + const style = []; + if (mat.blending === AdditiveBlending) { + style.push('mix-blend-mode:screen'); + } + const opAttr = opacity < 1 ? ` opacity="${num(opacity)}"` : ''; + const styleAttr = style.length ? ` style="${style.join(';')}"` : ''; + // curved surfaces are split into bands; a hairline of the same colour hides the joins + const seam = item.flat ? '' : ` stroke="${shaded(color, item.f)}" stroke-width="0.12" stroke-linejoin="round"`; + + const tex = mat.map ? textureDef(mat.map) : null; + const affine = tex && imageToOut(item.tris.find(t => imageToOut(t, tex.w, tex.h)) || item.tris[0], tex.w, tex.h); + if (!tex || !affine) { + body.push(``); + return; + } + const clip = `${P}c${clipCount++}`; + defs.push(``); + const use = ``; + if (mat.blending === AdditiveBlending && !isWhite(color)) { + defs.push(`${use}`); + body.push(``); + return; + } + const tint = isWhite(color) ? '' : ``; + const dim = item.f < 1 ? `` : ''; + body.push(`${use}${tint}${dim}`); + }); + + if (!Number.isFinite(minX)) { + minX = 0; + minY = 0; + maxX = 1; + maxY = 1; + } + const vx = minX - padding; + const vy = minY - padding; + const vw = (maxX - minX) + (padding * 2); + const vh = (maxY - minY) + (padding * 2); + const bg = background ? `` : ''; + return `` + + `${title ? `${escapeText(title)}` : ''}${defs.join('')}` + + `${bg}${body.join('')}`; +}; + +export {objectToTopSVG}; +export default objectToTopSVG; diff --git a/module-test/lib/viewer.js b/module-test/lib/viewer.js new file mode 100644 index 00000000000..93cd02a4b1b --- /dev/null +++ b/module-test/lib/viewer.js @@ -0,0 +1,417 @@ +import { + Box3, + DirectionalLight, + Group, + HemisphereLight, + Mesh, + NeutralToneMapping, + PCFShadowMap, + PerspectiveCamera, + PlaneGeometry, + PMREMGenerator, + Scene, + ShadowMaterial, + Sphere, + Vector3, + WebGLRenderer +} from 'three'; +import {OrbitControls} from '../vendor/three/OrbitControls.js'; +import {RoomEnvironment} from '../vendor/three/RoomEnvironment.js'; + +import {THEMES} from './board-data.js'; +import Kit, {disposeTree} from './kit.js'; +import TextureBank from './textures.js'; + +const MAX_DPR = 2; +const VIEW_DIR = new Vector3(0.55, 0.85, 1).normalize(); + +/** + * A self-contained three.js stage for the components: renderer, studio lighting, a soft shadow + * catcher, orbit controls and on-demand rendering. Board-space content (x east, y north, z up) + * goes in through show(); ordinary Y-up objects through add(). + */ +class Viewer { + constructor (container, {theme = 'dark', background, autoRotate = false, shadows = true, fov = 30} = {}) { + if (!container) { + throw new Error('createViewer needs a container element'); + } + this.container = container; + this.theme = theme; + this.backgroundOverride = background; + this.disposed = false; + this.dirty = true; + this.wireframe = false; + this.lastShow = null; + + const renderer = new WebGLRenderer({antialias: true, alpha: true, preserveDrawingBuffer: false}); + this.renderer = renderer; + renderer.toneMapping = NeutralToneMapping; + renderer.toneMappingExposure = 1.05; + renderer.shadowMap.enabled = shadows; + renderer.shadowMap.type = PCFShadowMap; + renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, MAX_DPR)); + const canvas = renderer.domElement; + canvas.style.display = 'block'; + canvas.style.width = '100%'; + canvas.style.height = '100%'; + canvas.style.touchAction = 'none'; + if (getComputedStyle(container).position === 'static') { + container.style.position = 'relative'; + } + container.appendChild(canvas); + + this.scene = new Scene(); + this.camera = new PerspectiveCamera(fov, 1, 1, 20000); + this.camera.position.set(400, 500, 600); + + // Board space: the studio builds with z up; turn it so z becomes three's +y. + this.root = new Group(); + this.root.rotation.x = -Math.PI / 2; + this.scene.add(this.root); + this.extra = new Group(); + this.scene.add(this.extra); + + const caps = renderer.capabilities; + this.textures = new TextureBank({ + maxSize: caps.maxTextureSize, + anisotropy: Math.min(8, caps.getMaxAnisotropy()), + onChange: () => this.invalidate() + }); + this.kit = new Kit(this.textures); + + this.buildEnvironment(); + this.scene.environmentIntensity = 0.5; + this.addLights(); + this.catcher = new Mesh(new PlaneGeometry(1, 1), new ShadowMaterial({opacity: 0.25, depthWrite: false})); + this.catcher.rotation.x = -Math.PI / 2; + this.catcher.receiveShadow = true; + this.catcher.visible = false; + this.scene.add(this.catcher); + + this.controls = new OrbitControls(this.camera, canvas); + this.controls.enableDamping = true; + this.controls.dampingFactor = 0.08; + this.controls.autoRotate = autoRotate; + this.controls.autoRotateSpeed = 1.2; + this.controls.maxPolarAngle = Math.PI * 0.495; + this.controls.addEventListener('change', () => this.invalidate()); + + this.applyBackground(); + this.bind(); + this.resize(); + this.frame = this.frame.bind(this); + this.raf = requestAnimationFrame(this.frame); + } + + buildEnvironment () { + if (this.envTex) { + this.envTex.dispose(); + } + const pmrem = new PMREMGenerator(this.renderer); + const room = new RoomEnvironment(); + this.envTex = pmrem.fromScene(room, 0.04).texture; + room.traverse(obj => { + if (obj.isMesh) { + obj.geometry.dispose(); + obj.material.dispose(); + } + }); + pmrem.dispose(); + this.scene.environment = this.envTex; + } + + addLights () { + this.scene.add(new HemisphereLight('#ffffff', '#c9c2b4', 1.1)); + const sun = new DirectionalLight('#fffaf0', 2.3); + sun.castShadow = true; + sun.shadow.mapSize.set(2048, 2048); + sun.shadow.bias = -0.0004; + sun.shadow.normalBias = 0.6; + sun.shadow.radius = 3; + this.scene.add(sun, sun.target); + this.sun = sun; + } + + bind () { + const canvas = this.renderer.domElement; + this.onLost = e => { + e.preventDefault(); + this.lost = true; + }; + this.onRestored = () => { + this.lost = false; + this.buildEnvironment(); + this.invalidate(); + }; + canvas.addEventListener('webglcontextlost', this.onLost, false); + canvas.addEventListener('webglcontextrestored', this.onRestored, false); + if (typeof ResizeObserver !== 'undefined') { + this.ro = new ResizeObserver(() => this.resize()); + this.ro.observe(this.container); + } else { + this.onWindowResize = () => this.resize(); + window.addEventListener('resize', this.onWindowResize); + } + } + + invalidate () { + this.dirty = true; + } + + resize () { + const w = Math.max(1, this.container.clientWidth); + const h = Math.max(1, this.container.clientHeight); + this.renderer.setSize(w, h, false); + this.camera.aspect = w / h; + this.camera.updateProjectionMatrix(); + this.invalidate(); + } + + applyBackground () { + const bg = this.backgroundOverride === undefined ? (THEMES[this.theme] || THEMES.dark).canvas : this.backgroundOverride; + if (bg === null || bg === 'transparent') { + this.renderer.setClearColor(0x000000, 0); + } else { + this.renderer.setClearColor(bg, 1); + } + this.catcher.material.opacity = this.theme === 'light' ? 0.24 : 0.5; + this.invalidate(); + } + + // ---- Content ------------------------------------------------------------ + + /** + * Replace the stage contents. `target` is a board-space Object3D or a builder function + * (kit, {theme}) => Object3D that is re-run when the theme changes. + */ + show (target, {frame = true} = {}) { + this.clear(); + this.lastShow = target; + const obj = typeof target === 'function' ? target(this.kit, {theme: this.theme}) : target; + if (obj) { + this.root.add(obj); + } + this.afterChange(frame); + return obj; + } + + /** Add an ordinary Y-up object (for example the result of createComponent). */ + add (obj, {frame = true} = {}) { + this.extra.add(obj); + this.afterChange(frame); + return obj; + } + + clear () { + [this.root, this.extra].forEach(group => { + disposeTree(group); + group.clear(); + }); + this.lastShow = null; + this.catcher.visible = false; + this.invalidate(); + } + + afterChange (frame) { + this.applyWireframe(); + this.fitShadows(); + if (frame) { + this.frameContent(); + } + this.renderer.shadowMap.needsUpdate = true; + this.invalidate(); + } + + bounds () { + const box = new Box3(); + box.expandByObject(this.root); + box.expandByObject(this.extra); + return box; + } + + /** Fit the shadow camera and the catcher plane to the content. */ + fitShadows () { + const box = this.bounds(); + if (box.isEmpty()) { + return; + } + const sphere = box.getBoundingSphere(new Sphere()); + const r = Math.max(10, sphere.radius); + const c = sphere.center; + this.sun.target.position.copy(c); + this.sun.position.copy(c).add(new Vector3(-0.38, 0.9, 0.52).multiplyScalar(r * 3)); + const cam = this.sun.shadow.camera; + cam.left = -r * 1.3; + cam.right = r * 1.3; + cam.top = r * 1.3; + cam.bottom = -r * 1.3; + cam.near = r * 0.5; + cam.far = r * 6; + cam.updateProjectionMatrix(); + this.catcher.position.set(c.x, box.min.y - 0.05, c.z); + this.catcher.scale.set(r * 6, r * 6, 1); + this.catcher.visible = true; + } + + /** Point the camera at the content from the default three-quarter angle. */ + frameContent (dir = VIEW_DIR) { + const box = this.bounds(); + if (box.isEmpty()) { + return; + } + const sphere = box.getBoundingSphere(new Sphere()); + const r = Math.max(10, sphere.radius); + const fov = this.camera.fov * (Math.PI / 180); + const fit = Math.min(fov, 2 * Math.atan(Math.tan(fov / 2) * this.camera.aspect)); + const unit = dir.clone().normalize(); + const center = box.getCenter(new Vector3()); + const corners = []; + [box.min.x, box.max.x].forEach(x => [box.min.y, box.max.y].forEach(y => [box.min.z, box.max.z].forEach(z => { + corners.push(new Vector3(x, y, z)); + }))); + // Start from the sphere fit, then tighten so the projected box fills ~88% of the view + let dist = r / Math.sin(fit / 2); + this.controls.target.copy(center); + for (let i = 0; i < 4; i++) { + this.camera.position.copy(center).add(unit.clone().multiplyScalar(dist)); + this.camera.near = Math.max(0.5, dist / 100); + this.camera.far = dist * 20; + this.camera.lookAt(center); + this.camera.updateMatrixWorld(true); + this.camera.updateProjectionMatrix(); + const extent = corners.reduce((m, p) => { + const q = p.clone().project(this.camera); + return Math.max(m, Math.abs(q.x), Math.abs(q.y)); + }, 0); + dist *= Math.max(0.5, Math.min(2, extent / 0.88)); + } + this.camera.position.copy(center).add(unit.multiplyScalar(dist)); + this.camera.near = Math.max(0.5, dist / 100); + this.camera.far = dist * 20; + this.camera.updateProjectionMatrix(); + this.controls.minDistance = Math.min(r * 0.4, dist * 0.5); + this.controls.maxDistance = dist * 4; + this.controls.update(); + this.invalidate(); + } + + // ---- Settings ----------------------------------------------------------- + + setTheme (theme) { + if (theme === this.theme) { + return; + } + this.theme = theme; + this.applyBackground(); + if (typeof this.lastShow === 'function') { + const target = this.lastShow; + const camPos = this.camera.position.clone(); + const camTarget = this.controls.target.clone(); + this.show(target, {frame: false}); + this.camera.position.copy(camPos); + this.controls.target.copy(camTarget); + } + } + + setBackground (color) { + this.backgroundOverride = color; + this.applyBackground(); + } + + setAutoRotate (on) { + this.controls.autoRotate = Boolean(on); + this.invalidate(); + } + + setShadows (on) { + this.renderer.shadowMap.enabled = Boolean(on); + this.catcher.visible = Boolean(on) && !this.bounds().isEmpty(); + this.scene.traverse(obj => { + if (obj.material) { + (Array.isArray(obj.material) ? obj.material : [obj.material]).forEach(m => { + m.needsUpdate = true; + }); + } + }); + this.renderer.shadowMap.needsUpdate = true; + this.invalidate(); + } + + setWireframe (on) { + this.wireframe = Boolean(on); + this.applyWireframe(); + this.invalidate(); + } + + applyWireframe () { + [this.root, this.extra].forEach(group => group.traverse(obj => { + if (obj.isMesh && obj.material) { + (Array.isArray(obj.material) ? obj.material : [obj.material]).forEach(m => { + if ('wireframe' in m) { + m.wireframe = this.wireframe; + } + }); + } + })); + } + + // ---- Output ------------------------------------------------------------- + + render () { + if (this.lost || this.disposed) { + return; + } + this.renderer.render(this.scene, this.camera); + this.dirty = false; + } + + /** PNG data URL of the current view (rendered on the spot, so it is never blank). */ + toPNG () { + this.renderer.render(this.scene, this.camera); + return this.renderer.domElement.toDataURL('image/png'); + } + + frame () { + if (this.disposed) { + return; + } + this.raf = requestAnimationFrame(this.frame); + const moved = this.controls.update(); + if (moved || this.dirty) { + this.render(); + } + } + + dispose () { + if (this.disposed) { + return; + } + this.disposed = true; + cancelAnimationFrame(this.raf); + const canvas = this.renderer.domElement; + canvas.removeEventListener('webglcontextlost', this.onLost); + canvas.removeEventListener('webglcontextrestored', this.onRestored); + if (this.ro) { + this.ro.disconnect(); + } + if (this.onWindowResize) { + window.removeEventListener('resize', this.onWindowResize); + } + this.controls.dispose(); + disposeTree(this.root); + disposeTree(this.extra); + this.catcher.geometry.dispose(); + this.catcher.material.dispose(); + this.kit.dispose(); + this.textures.dispose(); + this.envTex.dispose(); + this.sun.shadow.dispose(); + this.renderer.dispose(); + this.renderer.forceContextLoss(); + canvas.remove(); + } +} + +const createViewer = (container, options) => new Viewer(container, options); + +export {Viewer, createViewer}; diff --git a/module-test/serve.js b/module-test/serve.js new file mode 100644 index 00000000000..ae3233c5fc7 --- /dev/null +++ b/module-test/serve.js @@ -0,0 +1,51 @@ +/* Static server for the gallery: node module-test/serve.js [port]. ES modules don't load from file://. */ +const http = require('http'); +const fs = require('fs'); +const path = require('path'); + +const ROOT = __dirname; +const PORT = Number(process.argv[2] || process.env.PORT || 8710); +const TYPES = { + '.html': 'text/html; charset=utf-8', + '.js': 'text/javascript; charset=utf-8', + '.json': 'application/json; charset=utf-8', + '.svg': 'image/svg+xml', + '.png': 'image/png', + '.css': 'text/css; charset=utf-8', + '.txt': 'text/plain; charset=utf-8' +}; + +http.createServer((req, res) => { + let urlPath; + try { + urlPath = decodeURIComponent(new URL(req.url, 'http://localhost').pathname); + } catch (e) { + res.writeHead(400); + res.end('Bad request'); + return; + } + if (urlPath.endsWith('/')) { + urlPath += 'index.html'; + } + const file = path.normalize(path.join(ROOT, urlPath)); + if (file !== ROOT && !file.startsWith(ROOT + path.sep)) { + res.writeHead(403); + res.end('Forbidden'); + return; + } + fs.readFile(file, (err, data) => { + if (err) { + res.writeHead(404, {'Content-Type': 'text/plain; charset=utf-8'}); + res.end('Not found'); + return; + } + res.writeHead(200, { + 'Content-Type': TYPES[path.extname(file).toLowerCase()] || 'application/octet-stream', + 'Cache-Control': 'no-cache' + }); + res.end(data); + }); +}).listen(PORT, () => { + // eslint-disable-next-line no-console + console.log(`TinkerBit 3D components: http://localhost:${PORT}/`); +}); diff --git a/module-test/start-server.bat b/module-test/start-server.bat new file mode 100644 index 00000000000..348b6146cea --- /dev/null +++ b/module-test/start-server.bat @@ -0,0 +1,7 @@ +@echo off +REM Starts the TinkerBit 3D gallery at http://localhost:8710/ and opens it in your browser. +cd /d "%~dp0" +title TinkerBit 3D server +start "" /b powershell -NoProfile -Command "Start-Sleep 2; Start-Process http://localhost:8710/" +node serve.js +pause diff --git a/module-test/tools/export-studio-art.mjs b/module-test/tools/export-studio-art.mjs new file mode 100644 index 00000000000..b3977124587 --- /dev/null +++ b/module-test/tools/export-studio-art.mjs @@ -0,0 +1,93 @@ +/* + * Writes the artwork the studio's 2D views draw, into src/beginner-studio/assets/hub/: + * node module-test/tools/export-studio-art.mjs + * board.svg: the RJ11 Hub without its jacks (the studio draws those), silkscreen named after the + * studio's ports; .svg: every modelled module with its PCB centred on the origin; + * index.js: the files with their viewBox and module spec. Re-run after changing a component. + */ +import fs from 'fs'; +import {register} from 'module'; +import {fileURLToPath} from 'url'; + +const ROOT = new URL('../', import.meta.url); +const REPO = new URL('../', ROOT); +const OUT = new URL('src/beginner-studio/assets/hub/', REPO); +const JACKS = new URL('src/beginner-studio/domain/hubJacks.js', REPO); +const THREE = new URL('vendor/three/three.module.js', ROOT); + +// "three" comes from the vendored copy; the kit's .js files (and hubJacks.js) are ES modules +register(`data:text/javascript,${encodeURIComponent(` +const THREE = ${JSON.stringify(THREE.href)}; +const ROOT = ${JSON.stringify(ROOT.href)}; +const JACKS = ${JSON.stringify(JACKS.href)}; +export async function resolve (specifier, context, next) { + if (specifier === 'three') { + return {url: THREE, format: 'module', shortCircuit: true}; + } + const result = await next(specifier, context); + const kit = result.url.startsWith(ROOT) && result.url.endsWith('.js'); + return kit || result.url === JACKS ? {...result, format: 'module'} : result; +}`)}`); + +const {Group} = await import('three'); +const {default: Kit} = await import('../lib/kit.js'); +const {default: TextureBank} = await import('../lib/textures.js'); +const {default: objectToTopSVG} = await import('../lib/top-svg.js'); +const {MODULES} = await import('../lib/board-data.js'); +const {buildModule} = await import('../lib/pcb.js'); +const {buildBoard} = await import('../components/esp32-board.js'); +const {default: MODELS} = await import('../components/models.js'); +const {HUB_JACK} = await import(JACKS.href); + +const kit = new Kit(new TextureBank({headless: true})); +const viewBox = svg => svg.match(/viewBox="([^"]+)"/)[1].split(' ').map(Number); +const list = nums => `[${nums.join(', ')}]`; + +fs.mkdirSync(OUT, {recursive: true}); +Array.from(fs.readdirSync(OUT)).filter(f => f.endsWith('.svg')).forEach(f => fs.unlinkSync(new URL(f, OUT))); + +const labels = {}; +Object.keys(HUB_JACK).forEach(port => { + labels[HUB_JACK[port]] = port; +}); +const board = buildBoard(kit, {labels}); +// The studio animates the status LEDs itself +board.leds.forEach(led => { + led.glow.visible = false; +}); +// Projected relative to the root, so the root must sit above the hub's scale to get world units +const holder = new Group(); +holder.add(board.group); +const boardSvg = objectToTopSVG(holder, {padding: 0, idPrefix: 'hub-', title: 'ESP32 RJ11 Hub'}); +fs.writeFileSync(new URL('board.svg', OUT), boardSvg); + +// Loose parts (kind 'part', e.g. a motor) have no socket, so the studio cannot plug them in +const ids = Object.keys(MODELS).filter(id => MODELS[id].kind !== 'part').sort(); +const modules = ids.map(id => { + const group = buildModule(kit, MODELS[id], {}); + const info = MODULES.find(m => m.id === id); + const svg = objectToTopSVG(group, {padding: 1, idPrefix: `${id}-`, title: info ? info.name : id}); + fs.writeFileSync(new URL(`${id}.svg`, OUT), svg); + const {w, h, jackY} = group.userData.spec; + return {id, box: viewBox(svg), w, h, jackY, kb: Math.round(svg.length / 1024)}; +}); + +const js = `/* Generated by module-test/tools/export-studio-art.mjs; do not edit. */ +import board from './board.svg'; +${ids.map(id => `import ${id} from './${id}.svg';`).join('\n')} + +/** The hub's top view without its jacks; box is the viewBox [x, y, w, h], world units from the hub's corner. */ +const BOARD_ART = {src: board, box: ${list(viewBox(boardSvg))}}; + +/** Module top views, PCB (w × h) centred on the origin with its socket on the west edge at jackY. */ +const MODULE_ART = { +${modules.map(m => ` ${m.id}: {src: ${m.id}, box: ${list(m.box)}, w: ${m.w}, h: ${m.h}, jackY: ${m.jackY}}`).join(',\n')} +}; + +export {BOARD_ART, MODULE_ART}; +`; +fs.writeFileSync(new URL('index.js', OUT), js); + +// eslint-disable-next-line no-console +console.log(`Wrote board.svg (${Math.round(boardSvg.length / 1024)} KB) and ${modules.length} modules ` + + `(${modules.map(m => `${m.id} ${m.kb} KB`).join(', ')}) to ${fileURLToPath(OUT)}`); diff --git a/module-test/tools/export-top-svgs.mjs b/module-test/tools/export-top-svgs.mjs new file mode 100644 index 00000000000..271822559a7 --- /dev/null +++ b/module-test/tools/export-top-svgs.mjs @@ -0,0 +1,76 @@ +/* + * Writes a vector top view of every component to module-test/top-svg/: + * node module-test/tools/export-top-svgs.mjs + * .svg on its own, -plugged.svg in its default board jack, esp32-board-light.svg, + * and index.html to browse them. + */ +import fs from 'fs'; +import {register} from 'module'; +import {fileURLToPath} from 'url'; + +const ROOT = new URL('../', import.meta.url); +const OUT = new URL('top-svg/', ROOT); +const THREE = new URL('vendor/three/three.module.js', ROOT); + +// "three" comes from the vendored copy; the kit's .js files are ES modules +register(`data:text/javascript,${encodeURIComponent(` +const THREE = ${JSON.stringify(THREE.href)}; +const ROOT = ${JSON.stringify(ROOT.href)}; +export async function resolve (specifier, context, next) { + if (specifier === 'three') { + return {url: THREE, format: 'module', shortCircuit: true}; + } + const result = await next(specifier, context); + return result.url.startsWith(ROOT) && result.url.endsWith('.js') ? {...result, format: 'module'} : result; +}`)}`); + +const {COMPONENTS, toTopSVG} = await import('../lib/index.js'); + +const embedAsset = asset => fs.readFileSync(new URL(asset.file, ROOT), 'utf8'); +fs.mkdirSync(OUT, {recursive: true}); + +const written = []; +const write = (name, id, options) => { + const svg = toTopSVG(id, {embedAsset, idPrefix: `${name}-`, ...options}); + fs.writeFileSync(new URL(`${name}.svg`, OUT), svg); + written.push({name, label: `${COMPONENTS.find(c => c.id === id).name}${options.plugged ? ' (plugged in)' : ''}` + + `${options.theme === 'light' ? ' (light)' : ''}`, kb: Math.round(svg.length / 1024)}); +}; + +COMPONENTS.forEach(c => { + write(c.id, c.id, {}); + if (c.kind === 'board') { + write(`${c.id}-light`, c.id, {theme: 'light'}); + } else { + write(`${c.id}-plugged`, c.id, {plugged: true}); + } +}); + +const esc = s => s.replace(/&/g, '&').replace(/ + + + +TinkerBit components, top view + + + +

TinkerBit components, top view (vector SVG)

+
+${written.map(w => `
${esc(w.label)}` + + `
${esc(w.label)}${w.name}.svg · ${w.kb} KB
`).join('\n')} +
+ + +`); + +// eslint-disable-next-line no-console +console.log(`Wrote ${written.length} SVGs to ${fileURLToPath(OUT)}`); diff --git a/module-test/top-svg/btn-plugged.svg b/module-test/top-svg/btn-plugged.svg new file mode 100644 index 00000000000..0e4ae7fee49 --- /dev/null +++ b/module-test/top-svg/btn-plugged.svg @@ -0,0 +1 @@ +Push ButtonBUTTON5VGND3.3VA4N01STEPPER1A1D13A3A2UART1J0I2CI2C1RJ11C1R1C2R2D1C3U4U1U1ZGAPWR_LED1E1D3D4RSTBOOTLMSUSB1ESP-32CE111S3-3100PRC::DB60K1B408 \ No newline at end of file diff --git a/module-test/top-svg/btn.svg b/module-test/top-svg/btn.svg new file mode 100644 index 00000000000..83084f0aa16 --- /dev/null +++ b/module-test/top-svg/btn.svg @@ -0,0 +1 @@ +Push ButtonBUTTON \ No newline at end of file diff --git a/module-test/top-svg/dht-plugged.svg b/module-test/top-svg/dht-plugged.svg new file mode 100644 index 00000000000..d7d2ffc46ed --- /dev/null +++ b/module-test/top-svg/dht-plugged.svg @@ -0,0 +1 @@ +DHT11 Temp & HumidDHT115VGND3.3VA4N01STEPPER1A1D13A3A2UART1J0I2CI2C1RJ11C1R1C2R2D1C3U4U1U1ZGAPWR_LED1E1D3D4RSTBOOTLMSUSB1ESP-32CE111S3-3100PRC::DB60K1B408 \ No newline at end of file diff --git a/module-test/top-svg/dht.svg b/module-test/top-svg/dht.svg new file mode 100644 index 00000000000..263adbe8329 --- /dev/null +++ b/module-test/top-svg/dht.svg @@ -0,0 +1 @@ +DHT11 Temp & HumidDHT11 \ No newline at end of file diff --git a/module-test/top-svg/esp32-board-light.svg b/module-test/top-svg/esp32-board-light.svg new file mode 100644 index 00000000000..fbffb9bd6dc --- /dev/null +++ b/module-test/top-svg/esp32-board-light.svg @@ -0,0 +1 @@ +ESP32 RJ11 Hub5VGND3.3VA4N01STEPPER1A1D13A3A2UART1J0I2CI2C1RJ11C1R1C2R2D1C3U4U1U1ZGAPWR_LED1E1D3D4RSTBOOTLMSUSB1ESP-32CE111S3-3100PRC::DB60K1B408 \ No newline at end of file diff --git a/module-test/top-svg/esp32-board.svg b/module-test/top-svg/esp32-board.svg new file mode 100644 index 00000000000..e950e750bdf --- /dev/null +++ b/module-test/top-svg/esp32-board.svg @@ -0,0 +1 @@ +ESP32 RJ11 Hub5VGND3.3VA4N01STEPPER1A1D13A3A2UART1J0I2CI2C1RJ11C1R1C2R2D1C3U4U1U1ZGAPWR_LED1E1D3D4RSTBOOTLMSUSB1ESP-32CE111S3-3100PRC::DB60K1B408 \ No newline at end of file diff --git a/module-test/top-svg/index.html b/module-test/top-svg/index.html new file mode 100644 index 00000000000..73380834bfc --- /dev/null +++ b/module-test/top-svg/index.html @@ -0,0 +1,47 @@ + + + + +TinkerBit components, top view + + + +

TinkerBit components, top view (vector SVG)

+
+
ESP32 RJ11 Hub
ESP32 RJ11 Hubesp32-board.svg · 93 KB
+
ESP32 RJ11 Hub (light)
ESP32 RJ11 Hub (light)esp32-board-light.svg · 95 KB
+
Push Button
Push Buttonbtn.svg · 8 KB
+
Push Button (plugged in)
Push Button (plugged in)btn-plugged.svg · 154 KB
+
Potentiometer
Potentiometerpot.svg · 31 KB
+
Potentiometer (plugged in)
Potentiometer (plugged in)pot-plugged.svg · 184 KB
+
LED
LEDled.svg · 19 KB
+
LED (plugged in)
LED (plugged in)led-plugged.svg · 167 KB
+
SG90 Servo
SG90 Servoservo.svg · 97 KB
+
SG90 Servo (plugged in)
SG90 Servo (plugged in)servo-plugged.svg · 266 KB
+
OLED Screen
OLED Screenoled.svg · 14 KB
+
OLED Screen (plugged in)
OLED Screen (plugged in)oled-plugged.svg · 157 KB
+
MQ-2 Gas Sensor
MQ-2 Gas Sensormq2.svg · 18 KB
+
MQ-2 Gas Sensor (plugged in)
MQ-2 Gas Sensor (plugged in)mq2-plugged.svg · 157 KB
+
INMP441 Microphone
INMP441 Microphonemic.svg · 20 KB
+
INMP441 Microphone (plugged in)
INMP441 Microphone (plugged in)mic-plugged.svg · 159 KB
+
Heartbeat HW-605
Heartbeat HW-605pulse.svg · 8 KB
+
Heartbeat HW-605 (plugged in)
Heartbeat HW-605 (plugged in)pulse-plugged.svg · 151 KB
+
Capacitive Soil Moisture
Capacitive Soil Moisturesoil.svg · 16 KB
+
Capacitive Soil Moisture (plugged in)
Capacitive Soil Moisture (plugged in)soil-plugged.svg · 163 KB
+
DHT11 Temp & Humid
DHT11 Temp & Humiddht.svg · 10 KB
+
DHT11 Temp & Humid (plugged in)
DHT11 Temp & Humid (plugged in)dht-plugged.svg · 156 KB
+
HC-SR04 Ultrasonic
HC-SR04 Ultrasonicultra.svg · 15 KB
+
HC-SR04 Ultrasonic (plugged in)
HC-SR04 Ultrasonic (plugged in)ultra-plugged.svg · 160 KB
+
RFID RC522
RFID RC522rfid.svg · 32 KB
+
RFID RC522 (plugged in)
RFID RC522 (plugged in)rfid-plugged.svg · 172 KB
+
+ + diff --git a/module-test/top-svg/led-plugged.svg b/module-test/top-svg/led-plugged.svg new file mode 100644 index 00000000000..65aa842b9aa --- /dev/null +++ b/module-test/top-svg/led-plugged.svg @@ -0,0 +1 @@ +LEDLED5VGND3.3VA4N01STEPPER1A1D13A3A2UART1J0I2CI2C1RJ11C1R1C2R2D1C3U4U1U1ZGAPWR_LED1E1D3D4RSTBOOTLMSUSB1ESP-32CE111S3-3100PRC::DB60K1B408 \ No newline at end of file diff --git a/module-test/top-svg/led.svg b/module-test/top-svg/led.svg new file mode 100644 index 00000000000..4372086464f --- /dev/null +++ b/module-test/top-svg/led.svg @@ -0,0 +1 @@ +LEDLED \ No newline at end of file diff --git a/module-test/top-svg/mic-plugged.svg b/module-test/top-svg/mic-plugged.svg new file mode 100644 index 00000000000..b7107aa7879 --- /dev/null +++ b/module-test/top-svg/mic-plugged.svg @@ -0,0 +1 @@ +INMP441 MicrophoneINMP441 I2S MIC5VGND3.3VA4N01STEPPER1A1D13A3A2UART1J0I2CI2C1RJ11C1R1C2R2D1C3U4U1U1ZGAPWR_LED1E1D3D4RSTBOOTLMSUSB1441CYC738ESP-32CE111S3-3100PRC::DB60K1B408 \ No newline at end of file diff --git a/module-test/top-svg/mic.svg b/module-test/top-svg/mic.svg new file mode 100644 index 00000000000..bdb65f2e08f --- /dev/null +++ b/module-test/top-svg/mic.svg @@ -0,0 +1 @@ +INMP441 MicrophoneINMP441 I2S MIC441CYC738 \ No newline at end of file diff --git a/module-test/top-svg/mq2-plugged.svg b/module-test/top-svg/mq2-plugged.svg new file mode 100644 index 00000000000..8358e9f9e37 --- /dev/null +++ b/module-test/top-svg/mq2-plugged.svg @@ -0,0 +1 @@ +MQ-2 Gas SensorVCCGNDDOAOMQ-2 GAS SENSOR5VGND3.3VA4N01STEPPER1A1D13A3A2UART1J0I2CI2C1RJ11C1R1C2R2D1C3U4U1U1ZGAPWR_LED1E1D3D4RSTBOOTLMSUSB1PWRDOESP-32CE111S3-3100PRC::DB60K1B408 \ No newline at end of file diff --git a/module-test/top-svg/mq2.svg b/module-test/top-svg/mq2.svg new file mode 100644 index 00000000000..1cbe2072610 --- /dev/null +++ b/module-test/top-svg/mq2.svg @@ -0,0 +1 @@ +MQ-2 Gas SensorVCCGNDDOAOMQ-2 GAS SENSORPWRDO \ No newline at end of file diff --git a/module-test/top-svg/oled-plugged.svg b/module-test/top-svg/oled-plugged.svg new file mode 100644 index 00000000000..7b5be7d12be --- /dev/null +++ b/module-test/top-svg/oled-plugged.svg @@ -0,0 +1 @@ +OLED ScreenOLED I2C5VGND3.3VA4N01STEPPER1A1D13A3A2UART1J0I2CI2C1RJ11C1R1C2R2D1C3U4U1U1ZGAPWR_LED1E1D3D4RSTBOOTLMSUSB1GNDVCCSCLSDA12:45A0 72%TinkerBitOLED 128x64ESP-32CE111S3-3100PRC::DB60K1B408 \ No newline at end of file diff --git a/module-test/top-svg/oled.svg b/module-test/top-svg/oled.svg new file mode 100644 index 00000000000..9a4925f797a --- /dev/null +++ b/module-test/top-svg/oled.svg @@ -0,0 +1 @@ +OLED ScreenOLED I2CGNDVCCSCLSDA12:45A0 72%TinkerBitOLED 128x64 \ No newline at end of file diff --git a/module-test/top-svg/pot-plugged.svg b/module-test/top-svg/pot-plugged.svg new file mode 100644 index 00000000000..21e9cc4d988 --- /dev/null +++ b/module-test/top-svg/pot-plugged.svg @@ -0,0 +1 @@ +PotentiometerGNDOUTVCCPOTENTIOMETER 10K5VGND3.3VA4N01STEPPER1A1D13A3A2UART1J0I2CI2C1RJ11C1R1C2R2D1C3U4U1U1ZGAPWR_LED1E1D3D4RSTBOOTLMSUSB1ESP-32CE111S3-3100PRC::DB60K1B408 \ No newline at end of file diff --git a/module-test/top-svg/pot.svg b/module-test/top-svg/pot.svg new file mode 100644 index 00000000000..a4de2b80393 --- /dev/null +++ b/module-test/top-svg/pot.svg @@ -0,0 +1 @@ +PotentiometerGNDOUTVCCPOTENTIOMETER 10K \ No newline at end of file diff --git a/module-test/top-svg/pulse-plugged.svg b/module-test/top-svg/pulse-plugged.svg new file mode 100644 index 00000000000..d4f12e9ca2d --- /dev/null +++ b/module-test/top-svg/pulse-plugged.svg @@ -0,0 +1,3 @@ +Heartbeat HW-605HW-6055VGND3.3VA4N01STEPPER1A1D13A3A2UART1J0I2CI2C1RJ11C1R1C2R2D1C3U4U1U1ZGAPWR_LED1E1D3D4RSTBOOTLMSUSB1ESP-32CE111S3-3100PRC::DB60K1B408 \ No newline at end of file diff --git a/module-test/top-svg/pulse.svg b/module-test/top-svg/pulse.svg new file mode 100644 index 00000000000..5bc2ccddace --- /dev/null +++ b/module-test/top-svg/pulse.svg @@ -0,0 +1,3 @@ +Heartbeat HW-605HW-605 \ No newline at end of file diff --git a/module-test/top-svg/rfid-plugged.svg b/module-test/top-svg/rfid-plugged.svg new file mode 100644 index 00000000000..bb670e2339a --- /dev/null +++ b/module-test/top-svg/rfid-plugged.svg @@ -0,0 +1 @@ +RFID RC522RC5225VGND3.3VA4N01STEPPER1A1D13A3A2UART1J0I2CI2C1RJ11C1R1C2R2D1C3U4U1U1ZGAPWR_LED1E1D3D4RSTBOOTLMSUSB1RFID-RC5223.3VRSTGNDIRQMISOMOSISCKSDAL1L2D1C1C2C3C4R1C5R2R3C12R4C13C10C8C6C7C9C11ESP-32CE111S3-3100PRC::DB60K1B408 \ No newline at end of file diff --git a/module-test/top-svg/rfid.svg b/module-test/top-svg/rfid.svg new file mode 100644 index 00000000000..a39fee63e97 --- /dev/null +++ b/module-test/top-svg/rfid.svg @@ -0,0 +1 @@ +RFID RC522RC522RFID-RC5223.3VRSTGNDIRQMISOMOSISCKSDAL1L2D1C1C2C3C4R1C5R2R3C12R4C13C10C8C6C7C9C11 \ No newline at end of file diff --git a/module-test/top-svg/servo-plugged.svg b/module-test/top-svg/servo-plugged.svg new file mode 100644 index 00000000000..e8251ae3717 --- /dev/null +++ b/module-test/top-svg/servo-plugged.svg @@ -0,0 +1 @@ +SG90 ServoSG90 SERVO5VGND3.3VA4N01STEPPER1A1D13A3A2UART1J0I2CI2C1RJ11C1R1C2R2D1C3U4U1U1ZGAPWR_LED1E1D3D4RSTBOOTLMSUSB1ESP-32CE111S3-3100PRC::DB60K1B408 \ No newline at end of file diff --git a/module-test/top-svg/servo.svg b/module-test/top-svg/servo.svg new file mode 100644 index 00000000000..59899268e1e --- /dev/null +++ b/module-test/top-svg/servo.svg @@ -0,0 +1 @@ +SG90 ServoSG90 SERVO \ No newline at end of file diff --git a/module-test/top-svg/soil-plugged.svg b/module-test/top-svg/soil-plugged.svg new file mode 100644 index 00000000000..cf71656b672 --- /dev/null +++ b/module-test/top-svg/soil-plugged.svg @@ -0,0 +1 @@ +Capacitive Soil MoistureC5C6R3R4R2C1C2R1C3C4D1U2U1Capacitive SoilMoisture Sensor v1.25VGND3.3VA4N01STEPPER1A1D13A3A2UART1J0I2CI2C1RJ11C1R1C2R2D1C3U4U1U1ZGAPWR_LED1E1D3D4RSTBOOTLMSUSB1ESP-32CE111S3-3100PRC::DB60K1B408 \ No newline at end of file diff --git a/module-test/top-svg/soil.svg b/module-test/top-svg/soil.svg new file mode 100644 index 00000000000..265afad7462 --- /dev/null +++ b/module-test/top-svg/soil.svg @@ -0,0 +1 @@ +Capacitive Soil MoistureC5C6R3R4R2C1C2R1C3C4D1U2U1Capacitive SoilMoisture Sensor v1.2 \ No newline at end of file diff --git a/module-test/top-svg/ultra-plugged.svg b/module-test/top-svg/ultra-plugged.svg new file mode 100644 index 00000000000..d44da719b65 --- /dev/null +++ b/module-test/top-svg/ultra-plugged.svg @@ -0,0 +1 @@ +HC-SR04 UltrasonicVCCTRIGECHOGNDHC-SR04ULTRASONIC5VGND3.3VA4N01STEPPER1A1D13A3A2UART1J0I2CI2C1RJ11C1R1C2R2D1C3U4U1U1ZGAPWR_LED1E1D3D4RSTBOOTLMSUSB1ESP-32CE111S3-3100PRC::DB60K1B408 \ No newline at end of file diff --git a/module-test/top-svg/ultra.svg b/module-test/top-svg/ultra.svg new file mode 100644 index 00000000000..0c3d6f0832f --- /dev/null +++ b/module-test/top-svg/ultra.svg @@ -0,0 +1 @@ +HC-SR04 UltrasonicVCCTRIGECHOGNDHC-SR04ULTRASONIC \ No newline at end of file diff --git a/module-test/vendor/three/LICENSE b/module-test/vendor/three/LICENSE new file mode 100644 index 00000000000..8ada2a5f982 --- /dev/null +++ b/module-test/vendor/three/LICENSE @@ -0,0 +1,21 @@ +The MIT License + +Copyright © 2010-2026 three.js authors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/module-test/vendor/three/OrbitControls.js b/module-test/vendor/three/OrbitControls.js new file mode 100644 index 00000000000..3b49ec2db3a --- /dev/null +++ b/module-test/vendor/three/OrbitControls.js @@ -0,0 +1,1972 @@ +import { + Controls, + MOUSE, + Quaternion, + Spherical, + TOUCH, + Vector2, + Vector3, + Plane, + Ray, + MathUtils +} from 'three'; + +/** + * Fires when the camera has been transformed by the controls. + * + * @event OrbitControls#change + * @type {Object} + */ +const _changeEvent = { type: 'change' }; + +/** + * Fires when an interaction was initiated. + * + * @event OrbitControls#start + * @type {Object} + */ +const _startEvent = { type: 'start' }; + +/** + * Fires when an interaction has finished. + * + * @event OrbitControls#end + * @type {Object} + */ +const _endEvent = { type: 'end' }; + +const _ray = new Ray(); +const _plane = new Plane(); +const _TILT_LIMIT = Math.cos( 70 * MathUtils.DEG2RAD ); + +const _v = new Vector3(); +const _twoPI = 2 * Math.PI; + +const _STATE = { + NONE: - 1, + ROTATE: 0, + DOLLY: 1, + PAN: 2, + TOUCH_ROTATE: 3, + TOUCH_PAN: 4, + TOUCH_DOLLY_PAN: 5, + TOUCH_DOLLY_ROTATE: 6 +}; +const _EPS = 0.000001; + + +/** + * Orbit controls allow the camera to orbit around a target. + * + * OrbitControls performs orbiting, dollying (zooming), and panning. Unlike {@link TrackballControls}, + * it maintains the "up" direction `object.up` (+Y by default). + * + * - Orbit: Left mouse / touch: one-finger move. + * - Zoom: Middle mouse, or mousewheel / touch: two-finger spread or squish. + * - Pan: Right mouse, or left mouse + ctrl/meta/shiftKey, or arrow keys / touch: two-finger move. + * + * ```js + * const controls = new OrbitControls( camera, renderer.domElement ); + * + * // controls.update() must be called after any manual changes to the camera's transform + * camera.position.set( 0, 20, 100 ); + * controls.update(); + * + * function animate() { + * + * // required if controls.enableDamping or controls.autoRotate are set to true + * controls.update(); + * + * renderer.render( scene, camera ); + * + * } + * ``` + * + * @augments Controls + * @three_import import { OrbitControls } from 'three/addons/controls/OrbitControls.js'; + */ +class OrbitControls extends Controls { + + /** + * Constructs a new controls instance. + * + * @param {Object3D} object - The object that is managed by the controls. + * @param {?HTMLElement} domElement - The HTML element used for event listeners. + */ + constructor( object, domElement = null ) { + + super( object, domElement ); + + this.state = _STATE.NONE; + + /** + * The focus point of the controls, the `object` orbits around this. + * It can be updated manually at any point to change the focus of the controls. + * + * @type {Vector3} + */ + this.target = new Vector3(); + + /** + * The focus point of the `minTargetRadius` and `maxTargetRadius` limits. + * It can be updated manually at any point to change the center of interest + * for the `target`. + * + * @type {Vector3} + */ + this.cursor = new Vector3(); + + /** + * How far you can dolly in (perspective camera only). + * + * @type {number} + * @default 0 + */ + this.minDistance = 0; + + /** + * How far you can dolly out (perspective camera only). + * + * @type {number} + * @default Infinity + */ + this.maxDistance = Infinity; + + /** + * How far you can zoom in (orthographic camera only). + * + * @type {number} + * @default 0 + */ + this.minZoom = 0; + + /** + * How far you can zoom out (orthographic camera only). + * + * @type {number} + * @default Infinity + */ + this.maxZoom = Infinity; + + /** + * How close you can get the target to the 3D `cursor`. + * + * @type {number} + * @default 0 + */ + this.minTargetRadius = 0; + + /** + * How far you can move the target from the 3D `cursor`. + * + * @type {number} + * @default Infinity + */ + this.maxTargetRadius = Infinity; + + /** + * How far you can orbit vertically, lower limit. Range is `[0, Math.PI]` radians. + * + * @type {number} + * @default 0 + */ + this.minPolarAngle = 0; + + /** + * How far you can orbit vertically, upper limit. Range is `[0, Math.PI]` radians. + * + * @type {number} + * @default Math.PI + */ + this.maxPolarAngle = Math.PI; + + /** + * How far you can orbit horizontally, lower limit. If set, the interval `[ min, max ]` + * must be a sub-interval of `[ - 2 PI, 2 PI ]`, with `( max - min < 2 PI )`. + * + * @type {number} + * @default -Infinity + */ + this.minAzimuthAngle = - Infinity; + + /** + * How far you can orbit horizontally, upper limit. If set, the interval `[ min, max ]` + * must be a sub-interval of `[ - 2 PI, 2 PI ]`, with `( max - min < 2 PI )`. + * + * @type {number} + * @default -Infinity + */ + this.maxAzimuthAngle = Infinity; + + /** + * Set to `true` to enable damping (inertia), which can be used to give a sense of weight + * to the controls. Note that if this is enabled, you must call `update()` in your animation + * loop. + * + * @type {boolean} + * @default false + */ + this.enableDamping = false; + + /** + * The damping inertia used if `enableDamping` is set to `true`. + * + * Note that for this to work, you must call `update()` in your animation loop. + * + * @type {number} + * @default 0.05 + */ + this.dampingFactor = 0.05; + + /** + * Enable or disable zooming (dollying) of the camera. + * + * @type {boolean} + * @default true + */ + this.enableZoom = true; + + /** + * Speed of zooming / dollying. + * + * @type {number} + * @default 1 + */ + this.zoomSpeed = 1.0; + + /** + * Enable or disable horizontal and vertical rotation of the camera. + * + * Note that it is possible to disable a single axis by setting the min and max of the + * `minPolarAngle` or `minAzimuthAngle` to the same value, which will cause the vertical + * or horizontal rotation to be fixed at that value. + * + * @type {boolean} + * @default true + */ + this.enableRotate = true; + + /** + * Speed of rotation. + * + * @type {number} + * @default 1 + */ + this.rotateSpeed = 1.0; + + /** + * How fast to rotate the camera when the keyboard is used. + * + * @type {number} + * @default 1 + */ + this.keyRotateSpeed = 1.0; + + /** + * Enable or disable camera panning. + * + * @type {boolean} + * @default true + */ + this.enablePan = true; + + /** + * Speed of panning. + * + * @type {number} + * @default 1 + */ + this.panSpeed = 1.0; + + /** + * Defines how the camera's position is translated when panning. If `true`, the camera pans + * in screen space. Otherwise, the camera pans in the plane orthogonal to the camera's up + * direction. + * + * @type {boolean} + * @default true + */ + this.screenSpacePanning = true; + + /** + * How fast to pan the camera when the keyboard is used in + * pixels per keypress. + * + * @type {number} + * @default 7 + */ + this.keyPanSpeed = 7.0; + + /** + * Setting this property to `true` allows to zoom to the cursor's position. + * + * @type {boolean} + * @default false + */ + this.zoomToCursor = false; + + /** + * Set to true to automatically rotate around the target + * + * Note that if this is enabled, you must call `update()` in your animation loop. + * If you want the auto-rotate speed to be independent of the frame rate (the refresh + * rate of the display), you must pass the time `deltaTime`, in seconds, to `update()`. + * + * @type {boolean} + * @default false + */ + this.autoRotate = false; + + /** + * How fast to rotate around the target if `autoRotate` is `true`. The default equates to 30 seconds + * per orbit at 60fps. + * + * Note that if `autoRotate` is enabled, you must call `update()` in your animation loop. + * + * @type {number} + * @default 2 + */ + this.autoRotateSpeed = 2.0; + + /** + * This object contains references to the keycodes for controlling camera panning. + * + * ```js + * controls.keys = { + * LEFT: 'ArrowLeft', //left arrow + * UP: 'ArrowUp', // up arrow + * RIGHT: 'ArrowRight', // right arrow + * BOTTOM: 'ArrowDown' // down arrow + * } + * ``` + * @type {Object} + */ + this.keys = { LEFT: 'ArrowLeft', UP: 'ArrowUp', RIGHT: 'ArrowRight', BOTTOM: 'ArrowDown' }; + + /** + * This object contains references to the mouse actions used by the controls. + * + * ```js + * controls.mouseButtons = { + * LEFT: THREE.MOUSE.ROTATE, + * MIDDLE: THREE.MOUSE.DOLLY, + * RIGHT: THREE.MOUSE.PAN + * } + * ``` + * @type {Object} + */ + this.mouseButtons = { LEFT: MOUSE.ROTATE, MIDDLE: MOUSE.DOLLY, RIGHT: MOUSE.PAN }; + + /** + * This object contains references to the touch actions used by the controls. + * + * ```js + * controls.mouseButtons = { + * ONE: THREE.TOUCH.ROTATE, + * TWO: THREE.TOUCH.DOLLY_PAN + * } + * ``` + * @type {Object} + */ + this.touches = { ONE: TOUCH.ROTATE, TWO: TOUCH.DOLLY_PAN }; + + /** + * Used internally by `saveState()` and `reset()`. + * + * @type {Vector3} + */ + this.target0 = this.target.clone(); + + /** + * Used internally by `saveState()` and `reset()`. + * + * @type {Vector3} + */ + this.position0 = this.object.position.clone(); + + /** + * Used internally by `saveState()` and `reset()`. + * + * @type {number} + */ + this.zoom0 = this.object.zoom; + + this._cursorStyle = 'auto'; + + // the target DOM element for key events + this._domElementKeyEvents = null; + + // internals + + this._lastPosition = new Vector3(); + this._lastQuaternion = new Quaternion(); + this._lastTargetPosition = new Vector3(); + + // so camera.up is the orbit axis + this._quat = new Quaternion().setFromUnitVectors( object.up, new Vector3( 0, 1, 0 ) ); + this._quatInverse = this._quat.clone().invert(); + + // current position in spherical coordinates + this._spherical = new Spherical(); + this._sphericalDelta = new Spherical(); + + this._scale = 1; + this._panOffset = new Vector3(); + + this._rotateStart = new Vector2(); + this._rotateEnd = new Vector2(); + this._rotateDelta = new Vector2(); + + this._panStart = new Vector2(); + this._panEnd = new Vector2(); + this._panDelta = new Vector2(); + + this._dollyStart = new Vector2(); + this._dollyEnd = new Vector2(); + this._dollyDelta = new Vector2(); + + this._dollyDirection = new Vector3(); + this._mouse = new Vector2(); + this._performCursorZoom = false; + + this._pointers = []; + this._pointerPositions = {}; + + this._controlActive = false; + + // event listeners + + this._onPointerMove = onPointerMove.bind( this ); + this._onPointerDown = onPointerDown.bind( this ); + this._onPointerUp = onPointerUp.bind( this ); + this._onContextMenu = onContextMenu.bind( this ); + this._onMouseWheel = onMouseWheel.bind( this ); + this._onKeyDown = onKeyDown.bind( this ); + + this._onTouchStart = onTouchStart.bind( this ); + this._onTouchMove = onTouchMove.bind( this ); + + this._onMouseDown = onMouseDown.bind( this ); + this._onMouseMove = onMouseMove.bind( this ); + + this._interceptControlDown = interceptControlDown.bind( this ); + this._interceptControlUp = interceptControlUp.bind( this ); + + // + + if ( this.domElement !== null ) { + + this.connect( this.domElement ); + + } + + this.update(); + + } + + /** + * Defines the visual representation of the cursor. + * + * @type {('auto'|'grab')} + * @default 'auto' + */ + set cursorStyle( type ) { + + this._cursorStyle = type; + + if ( type === 'grab' ) { + + this.domElement.style.cursor = 'grab'; + + } else { + + this.domElement.style.cursor = 'auto'; + + } + + } + + get cursorStyle() { + + return this._cursorStyle; + + } + + connect( element ) { + + super.connect( element ); + + this.domElement.addEventListener( 'pointerdown', this._onPointerDown ); + this.domElement.addEventListener( 'pointercancel', this._onPointerUp ); + + this.domElement.addEventListener( 'contextmenu', this._onContextMenu ); + this.domElement.addEventListener( 'wheel', this._onMouseWheel, { passive: false } ); + + const document = this.domElement.getRootNode(); // offscreen canvas compatibility + document.addEventListener( 'keydown', this._interceptControlDown, { passive: true, capture: true } ); + + this.domElement.style.touchAction = 'none'; // Disable touch scroll + + } + + disconnect() { + + this.state = _STATE.NONE; + + this.domElement.removeEventListener( 'pointerdown', this._onPointerDown ); + this.domElement.ownerDocument.removeEventListener( 'pointermove', this._onPointerMove ); + this.domElement.ownerDocument.removeEventListener( 'pointerup', this._onPointerUp ); + this.domElement.removeEventListener( 'pointercancel', this._onPointerUp ); + + this.domElement.removeEventListener( 'wheel', this._onMouseWheel ); + this.domElement.removeEventListener( 'contextmenu', this._onContextMenu ); + + this.stopListenToKeyEvents(); + + const document = this.domElement.getRootNode(); // offscreen canvas compatibility + document.removeEventListener( 'keydown', this._interceptControlDown, { capture: true } ); + document.removeEventListener( 'keyup', this._interceptControlUp, { capture: true } ); + + this._controlActive = false; + + this._pointers.length = 0; + this._pointerPositions = {}; + + this.domElement.style.touchAction = ''; // Restore touch scroll + this.domElement.style.cursor = 'auto'; + + } + + dispose() { + + this.disconnect(); + + } + + /** + * Get the current vertical rotation, in radians. + * + * @return {number} The current vertical rotation, in radians. + */ + getPolarAngle() { + + return this._spherical.phi; + + } + + /** + * Get the current horizontal rotation, in radians. + * + * @return {number} The current horizontal rotation, in radians. + */ + getAzimuthalAngle() { + + return this._spherical.theta; + + } + + /** + * Returns the distance from the camera to the target. + * + * @return {number} The distance from the camera to the target. + */ + getDistance() { + + return this.object.position.distanceTo( this.target ); + + } + + /** + * Adds key event listeners to the given DOM element. + * `window` is a recommended argument for using this method. + * + * @param {HTMLElement} domElement - The DOM element + */ + listenToKeyEvents( domElement ) { + + domElement.addEventListener( 'keydown', this._onKeyDown ); + this._domElementKeyEvents = domElement; + + } + + /** + * Removes the key event listener previously defined with `listenToKeyEvents()`. + */ + stopListenToKeyEvents() { + + if ( this._domElementKeyEvents !== null ) { + + this._domElementKeyEvents.removeEventListener( 'keydown', this._onKeyDown ); + this._domElementKeyEvents = null; + + } + + } + + /** + * Save the current state of the controls. This can later be recovered with `reset()`. + */ + saveState() { + + this.target0.copy( this.target ); + this.position0.copy( this.object.position ); + this.zoom0 = this.object.zoom; + + } + + /** + * Reset the controls to their state from either the last time the `saveState()` + * was called, or the initial state. + */ + reset() { + + this.target.copy( this.target0 ); + this.object.position.copy( this.position0 ); + this.object.zoom = this.zoom0; + + this.object.updateProjectionMatrix(); + this.dispatchEvent( _changeEvent ); + + this.update(); + + this.state = _STATE.NONE; + + } + + /** + * Programmatically pan the camera. + * + * @param {number} deltaX - The horizontal pan amount in pixels. + * @param {number} deltaY - The vertical pan amount in pixels. + */ + pan( deltaX, deltaY ) { + + this._pan( deltaX, deltaY ); + this.update(); + + } + + /** + * Programmatically dolly in (zoom in for perspective camera). + * + * @param {number} dollyScale - The dolly scale factor. + */ + dollyIn( dollyScale ) { + + this._dollyIn( dollyScale ); + this.update(); + + } + + /** + * Programmatically dolly out (zoom out for perspective camera). + * + * @param {number} dollyScale - The dolly scale factor. + */ + dollyOut( dollyScale ) { + + this._dollyOut( dollyScale ); + this.update(); + + } + + /** + * Programmatically rotate the camera left (around the vertical axis). + * + * @param {number} angle - The rotation angle in radians. + */ + rotateLeft( angle ) { + + this._rotateLeft( angle ); + this.update(); + + } + + /** + * Programmatically rotate the camera up (around the horizontal axis). + * + * @param {number} angle - The rotation angle in radians. + */ + rotateUp( angle ) { + + this._rotateUp( angle ); + this.update(); + + } + + update( deltaTime = null ) { + + const position = this.object.position; + + _v.copy( position ).sub( this.target ); + + // rotate offset to "y-axis-is-up" space + _v.applyQuaternion( this._quat ); + + // angle from z-axis around y-axis + this._spherical.setFromVector3( _v ); + + if ( this.autoRotate && this.state === _STATE.NONE ) { + + this._rotateLeft( this._getAutoRotationAngle( deltaTime ) ); + + } + + if ( this.enableDamping ) { + + this._spherical.theta += this._sphericalDelta.theta * this.dampingFactor; + this._spherical.phi += this._sphericalDelta.phi * this.dampingFactor; + + } else { + + this._spherical.theta += this._sphericalDelta.theta; + this._spherical.phi += this._sphericalDelta.phi; + + } + + // restrict theta to be between desired limits + + let min = this.minAzimuthAngle; + let max = this.maxAzimuthAngle; + + if ( isFinite( min ) && isFinite( max ) ) { + + if ( min < - Math.PI ) min += _twoPI; else if ( min > Math.PI ) min -= _twoPI; + + if ( max < - Math.PI ) max += _twoPI; else if ( max > Math.PI ) max -= _twoPI; + + if ( min <= max ) { + + this._spherical.theta = Math.max( min, Math.min( max, this._spherical.theta ) ); + + } else { + + this._spherical.theta = ( this._spherical.theta > ( min + max ) / 2 ) ? + Math.max( min, this._spherical.theta ) : + Math.min( max, this._spherical.theta ); + + } + + } + + // restrict phi to be between desired limits + this._spherical.phi = Math.max( this.minPolarAngle, Math.min( this.maxPolarAngle, this._spherical.phi ) ); + + this._spherical.makeSafe(); + + + // move target to panned location + + if ( this.enableDamping === true ) { + + this.target.addScaledVector( this._panOffset, this.dampingFactor ); + + } else { + + this.target.add( this._panOffset ); + + } + + // Limit the target distance from the cursor to create a sphere around the center of interest + this.target.sub( this.cursor ); + this.target.clampLength( this.minTargetRadius, this.maxTargetRadius ); + this.target.add( this.cursor ); + + let zoomChanged = false; + // adjust the camera position based on zoom only if we're not zooming to the cursor or if it's an ortho camera + // we adjust zoom later in these cases + if ( this.zoomToCursor && this._performCursorZoom || this.object.isOrthographicCamera ) { + + this._spherical.radius = this._clampDistance( this._spherical.radius ); + + } else { + + const prevRadius = this._spherical.radius; + this._spherical.radius = this._clampDistance( this._spherical.radius * this._scale ); + zoomChanged = prevRadius != this._spherical.radius; + + } + + _v.setFromSpherical( this._spherical ); + + // rotate offset back to "camera-up-vector-is-up" space + _v.applyQuaternion( this._quatInverse ); + + position.copy( this.target ).add( _v ); + + this.object.lookAt( this.target ); + + if ( this.enableDamping === true ) { + + this._sphericalDelta.theta *= ( 1 - this.dampingFactor ); + this._sphericalDelta.phi *= ( 1 - this.dampingFactor ); + + this._panOffset.multiplyScalar( 1 - this.dampingFactor ); + + } else { + + this._sphericalDelta.set( 0, 0, 0 ); + + this._panOffset.set( 0, 0, 0 ); + + } + + // adjust camera position + if ( this.zoomToCursor && this._performCursorZoom ) { + + let newRadius = null; + if ( this.object.isPerspectiveCamera ) { + + // move the camera down the pointer ray + // this method avoids floating point error + const prevRadius = _v.length(); + newRadius = this._clampDistance( prevRadius * this._scale ); + + const radiusDelta = prevRadius - newRadius; + this.object.position.addScaledVector( this._dollyDirection, radiusDelta ); + this.object.updateMatrixWorld(); + + zoomChanged = !! radiusDelta; + + } else if ( this.object.isOrthographicCamera ) { + + // adjust the ortho camera position based on zoom changes + const mouseBefore = new Vector3( this._mouse.x, this._mouse.y, 0 ); + mouseBefore.unproject( this.object ); + + const prevZoom = this.object.zoom; + this.object.zoom = Math.max( this.minZoom, Math.min( this.maxZoom, this.object.zoom / this._scale ) ); + this.object.updateProjectionMatrix(); + + zoomChanged = prevZoom !== this.object.zoom; + + const mouseAfter = new Vector3( this._mouse.x, this._mouse.y, 0 ); + mouseAfter.unproject( this.object ); + + this.object.position.sub( mouseAfter ).add( mouseBefore ); + this.object.updateMatrixWorld(); + + newRadius = _v.length(); + + } else { + + console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled.' ); + this.zoomToCursor = false; + + } + + // handle the placement of the target + if ( newRadius !== null ) { + + if ( this.screenSpacePanning ) { + + // position the orbit target in front of the new camera position + this.target.set( 0, 0, - 1 ) + .transformDirection( this.object.matrix ) + .multiplyScalar( newRadius ) + .add( this.object.position ); + + } else { + + // get the ray and translation plane to compute target + _ray.origin.copy( this.object.position ); + _ray.direction.set( 0, 0, - 1 ).transformDirection( this.object.matrix ); + + // if the camera is 20 degrees above the horizon then don't adjust the focus target to avoid + // extremely large values + if ( Math.abs( this.object.up.dot( _ray.direction ) ) < _TILT_LIMIT ) { + + this.object.lookAt( this.target ); + + } else { + + _plane.setFromNormalAndCoplanarPoint( this.object.up, this.target ); + _ray.intersectPlane( _plane, this.target ); + + } + + } + + } + + } else if ( this.object.isOrthographicCamera ) { + + const prevZoom = this.object.zoom; + this.object.zoom = Math.max( this.minZoom, Math.min( this.maxZoom, this.object.zoom / this._scale ) ); + + if ( prevZoom !== this.object.zoom ) { + + this.object.updateProjectionMatrix(); + zoomChanged = true; + + } + + } + + this._scale = 1; + this._performCursorZoom = false; + + // update condition is: + // min(camera displacement, camera rotation in radians)^2 > EPS + // using small-angle approximation cos(x/2) = 1 - x^2 / 8 + + if ( zoomChanged || + this._lastPosition.distanceToSquared( this.object.position ) > _EPS || + 8 * ( 1 - this._lastQuaternion.dot( this.object.quaternion ) ) > _EPS || + this._lastTargetPosition.distanceToSquared( this.target ) > _EPS ) { + + this.dispatchEvent( _changeEvent ); + + this._lastPosition.copy( this.object.position ); + this._lastQuaternion.copy( this.object.quaternion ); + this._lastTargetPosition.copy( this.target ); + + return true; + + } + + return false; + + } + + _getAutoRotationAngle( deltaTime ) { + + if ( deltaTime !== null ) { + + return ( _twoPI / 60 * this.autoRotateSpeed ) * deltaTime; + + } else { + + return _twoPI / 60 / 60 * this.autoRotateSpeed; + + } + + } + + _getZoomScale( delta ) { + + const normalizedDelta = Math.abs( delta * 0.01 ); + return Math.pow( 0.95, this.zoomSpeed * normalizedDelta ); + + } + + _rotateLeft( angle ) { + + this._sphericalDelta.theta -= angle; + + } + + _rotateUp( angle ) { + + this._sphericalDelta.phi -= angle; + + } + + _panLeft( distance, objectMatrix ) { + + _v.setFromMatrixColumn( objectMatrix, 0 ); // get X column of objectMatrix + _v.multiplyScalar( - distance ); + + this._panOffset.add( _v ); + + } + + _panUp( distance, objectMatrix ) { + + if ( this.screenSpacePanning === true ) { + + _v.setFromMatrixColumn( objectMatrix, 1 ); + + } else { + + _v.setFromMatrixColumn( objectMatrix, 0 ); + _v.crossVectors( this.object.up, _v ); + + } + + _v.multiplyScalar( distance ); + + this._panOffset.add( _v ); + + } + + // deltaX and deltaY are in pixels; right and down are positive + _pan( deltaX, deltaY ) { + + const element = this.domElement; + + if ( this.object.isPerspectiveCamera ) { + + // perspective + const position = this.object.position; + _v.copy( position ).sub( this.target ); + let targetDistance = _v.length(); + + // half of the fov is center to top of screen + targetDistance *= Math.tan( ( this.object.fov / 2 ) * Math.PI / 180.0 ); + + // we use only clientHeight here so aspect ratio does not distort speed + this._panLeft( 2 * deltaX * targetDistance / element.clientHeight, this.object.matrix ); + this._panUp( 2 * deltaY * targetDistance / element.clientHeight, this.object.matrix ); + + } else if ( this.object.isOrthographicCamera ) { + + // orthographic + this._panLeft( deltaX * ( this.object.right - this.object.left ) / this.object.zoom / element.clientWidth, this.object.matrix ); + this._panUp( deltaY * ( this.object.top - this.object.bottom ) / this.object.zoom / element.clientHeight, this.object.matrix ); + + } else { + + // camera neither orthographic nor perspective + console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.' ); + this.enablePan = false; + + } + + } + + _dollyOut( dollyScale ) { + + if ( this.object.isPerspectiveCamera || this.object.isOrthographicCamera ) { + + this._scale /= dollyScale; + + } else { + + console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' ); + this.enableZoom = false; + + } + + } + + _dollyIn( dollyScale ) { + + if ( this.object.isPerspectiveCamera || this.object.isOrthographicCamera ) { + + this._scale *= dollyScale; + + } else { + + console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' ); + this.enableZoom = false; + + } + + } + + _updateZoomParameters( x, y ) { + + if ( ! this.zoomToCursor ) { + + return; + + } + + this._performCursorZoom = true; + + const rect = this.domElement.getBoundingClientRect(); + const dx = x - rect.left; + const dy = y - rect.top; + const w = rect.width; + const h = rect.height; + + this._mouse.x = ( dx / w ) * 2 - 1; + this._mouse.y = - ( dy / h ) * 2 + 1; + + this._dollyDirection.set( this._mouse.x, this._mouse.y, 1 ).unproject( this.object ).sub( this.object.position ).normalize(); + + } + + _clampDistance( dist ) { + + return Math.max( this.minDistance, Math.min( this.maxDistance, dist ) ); + + } + + // + // event callbacks - update the object state + // + + _handleMouseDownRotate( event ) { + + this._rotateStart.set( event.clientX, event.clientY ); + + } + + _handleMouseDownDolly( event ) { + + this._updateZoomParameters( event.clientX, event.clientX ); + this._dollyStart.set( event.clientX, event.clientY ); + + } + + _handleMouseDownPan( event ) { + + this._panStart.set( event.clientX, event.clientY ); + + } + + _handleMouseMoveRotate( event ) { + + this._rotateEnd.set( event.clientX, event.clientY ); + + this._rotateDelta.subVectors( this._rotateEnd, this._rotateStart ).multiplyScalar( this.rotateSpeed ); + + const element = this.domElement; + + this._rotateLeft( _twoPI * this._rotateDelta.x / element.clientHeight ); // yes, height + + this._rotateUp( _twoPI * this._rotateDelta.y / element.clientHeight ); + + this._rotateStart.copy( this._rotateEnd ); + + this.update(); + + } + + _handleMouseMoveDolly( event ) { + + this._dollyEnd.set( event.clientX, event.clientY ); + + this._dollyDelta.subVectors( this._dollyEnd, this._dollyStart ); + + if ( this._dollyDelta.y > 0 ) { + + this._dollyOut( this._getZoomScale( this._dollyDelta.y ) ); + + } else if ( this._dollyDelta.y < 0 ) { + + this._dollyIn( this._getZoomScale( this._dollyDelta.y ) ); + + } + + this._dollyStart.copy( this._dollyEnd ); + + this.update(); + + } + + _handleMouseMovePan( event ) { + + this._panEnd.set( event.clientX, event.clientY ); + + this._panDelta.subVectors( this._panEnd, this._panStart ).multiplyScalar( this.panSpeed ); + + this._pan( this._panDelta.x, this._panDelta.y ); + + this._panStart.copy( this._panEnd ); + + this.update(); + + } + + _handleMouseWheel( event ) { + + this._updateZoomParameters( event.clientX, event.clientY ); + + if ( event.deltaY < 0 ) { + + this._dollyIn( this._getZoomScale( event.deltaY ) ); + + } else if ( event.deltaY > 0 ) { + + this._dollyOut( this._getZoomScale( event.deltaY ) ); + + } + + this.update(); + + } + + _handleKeyDown( event ) { + + let needsUpdate = false; + + switch ( event.code ) { + + case this.keys.UP: + + if ( event.ctrlKey || event.metaKey || event.shiftKey ) { + + if ( this.enableRotate ) { + + this._rotateUp( _twoPI * this.keyRotateSpeed / this.domElement.clientHeight ); + + } + + } else { + + if ( this.enablePan ) { + + this._pan( 0, this.keyPanSpeed ); + + } + + } + + needsUpdate = true; + break; + + case this.keys.BOTTOM: + + if ( event.ctrlKey || event.metaKey || event.shiftKey ) { + + if ( this.enableRotate ) { + + this._rotateUp( - _twoPI * this.keyRotateSpeed / this.domElement.clientHeight ); + + } + + } else { + + if ( this.enablePan ) { + + this._pan( 0, - this.keyPanSpeed ); + + } + + } + + needsUpdate = true; + break; + + case this.keys.LEFT: + + if ( event.ctrlKey || event.metaKey || event.shiftKey ) { + + if ( this.enableRotate ) { + + this._rotateLeft( _twoPI * this.keyRotateSpeed / this.domElement.clientHeight ); + + } + + } else { + + if ( this.enablePan ) { + + this._pan( this.keyPanSpeed, 0 ); + + } + + } + + needsUpdate = true; + break; + + case this.keys.RIGHT: + + if ( event.ctrlKey || event.metaKey || event.shiftKey ) { + + if ( this.enableRotate ) { + + this._rotateLeft( - _twoPI * this.keyRotateSpeed / this.domElement.clientHeight ); + + } + + } else { + + if ( this.enablePan ) { + + this._pan( - this.keyPanSpeed, 0 ); + + } + + } + + needsUpdate = true; + break; + + } + + if ( needsUpdate ) { + + // prevent the browser from scrolling on cursor keys + event.preventDefault(); + + this.update(); + + } + + + } + + _handleTouchStartRotate( event ) { + + if ( this._pointers.length === 1 ) { + + this._rotateStart.set( event.pageX, event.pageY ); + + } else { + + const position = this._getSecondPointerPosition( event ); + + const x = 0.5 * ( event.pageX + position.x ); + const y = 0.5 * ( event.pageY + position.y ); + + this._rotateStart.set( x, y ); + + } + + } + + _handleTouchStartPan( event ) { + + if ( this._pointers.length === 1 ) { + + this._panStart.set( event.pageX, event.pageY ); + + } else { + + const position = this._getSecondPointerPosition( event ); + + const x = 0.5 * ( event.pageX + position.x ); + const y = 0.5 * ( event.pageY + position.y ); + + this._panStart.set( x, y ); + + } + + } + + _handleTouchStartDolly( event ) { + + const position = this._getSecondPointerPosition( event ); + + const dx = event.pageX - position.x; + const dy = event.pageY - position.y; + + const distance = Math.sqrt( dx * dx + dy * dy ); + + this._dollyStart.set( 0, distance ); + + } + + _handleTouchStartDollyPan( event ) { + + if ( this.enableZoom ) this._handleTouchStartDolly( event ); + + if ( this.enablePan ) this._handleTouchStartPan( event ); + + } + + _handleTouchStartDollyRotate( event ) { + + if ( this.enableZoom ) this._handleTouchStartDolly( event ); + + if ( this.enableRotate ) this._handleTouchStartRotate( event ); + + } + + _handleTouchMoveRotate( event ) { + + if ( this._pointers.length == 1 ) { + + this._rotateEnd.set( event.pageX, event.pageY ); + + } else { + + const position = this._getSecondPointerPosition( event ); + + const x = 0.5 * ( event.pageX + position.x ); + const y = 0.5 * ( event.pageY + position.y ); + + this._rotateEnd.set( x, y ); + + } + + this._rotateDelta.subVectors( this._rotateEnd, this._rotateStart ).multiplyScalar( this.rotateSpeed ); + + const element = this.domElement; + + this._rotateLeft( _twoPI * this._rotateDelta.x / element.clientHeight ); // yes, height + + this._rotateUp( _twoPI * this._rotateDelta.y / element.clientHeight ); + + this._rotateStart.copy( this._rotateEnd ); + + } + + _handleTouchMovePan( event ) { + + if ( this._pointers.length === 1 ) { + + this._panEnd.set( event.pageX, event.pageY ); + + } else { + + const position = this._getSecondPointerPosition( event ); + + const x = 0.5 * ( event.pageX + position.x ); + const y = 0.5 * ( event.pageY + position.y ); + + this._panEnd.set( x, y ); + + } + + this._panDelta.subVectors( this._panEnd, this._panStart ).multiplyScalar( this.panSpeed ); + + this._pan( this._panDelta.x, this._panDelta.y ); + + this._panStart.copy( this._panEnd ); + + } + + _handleTouchMoveDolly( event ) { + + const position = this._getSecondPointerPosition( event ); + + const dx = event.pageX - position.x; + const dy = event.pageY - position.y; + + const distance = Math.sqrt( dx * dx + dy * dy ); + + this._dollyEnd.set( 0, distance ); + + this._dollyDelta.set( 0, Math.pow( this._dollyEnd.y / this._dollyStart.y, this.zoomSpeed ) ); + + this._dollyOut( this._dollyDelta.y ); + + this._dollyStart.copy( this._dollyEnd ); + + const centerX = ( event.pageX + position.x ) * 0.5; + const centerY = ( event.pageY + position.y ) * 0.5; + + this._updateZoomParameters( centerX, centerY ); + + } + + _handleTouchMoveDollyPan( event ) { + + if ( this.enableZoom ) this._handleTouchMoveDolly( event ); + + if ( this.enablePan ) this._handleTouchMovePan( event ); + + } + + _handleTouchMoveDollyRotate( event ) { + + if ( this.enableZoom ) this._handleTouchMoveDolly( event ); + + if ( this.enableRotate ) this._handleTouchMoveRotate( event ); + + } + + // pointers + + _addPointer( event ) { + + this._pointers.push( event.pointerId ); + + } + + _removePointer( event ) { + + delete this._pointerPositions[ event.pointerId ]; + + for ( let i = 0; i < this._pointers.length; i ++ ) { + + if ( this._pointers[ i ] == event.pointerId ) { + + this._pointers.splice( i, 1 ); + return; + + } + + } + + } + + _isTrackingPointer( event ) { + + for ( let i = 0; i < this._pointers.length; i ++ ) { + + if ( this._pointers[ i ] == event.pointerId ) return true; + + } + + return false; + + } + + _trackPointer( event ) { + + let position = this._pointerPositions[ event.pointerId ]; + + if ( position === undefined ) { + + position = new Vector2(); + this._pointerPositions[ event.pointerId ] = position; + + } + + position.set( event.pageX, event.pageY ); + + } + + _getSecondPointerPosition( event ) { + + const pointerId = ( event.pointerId === this._pointers[ 0 ] ) ? this._pointers[ 1 ] : this._pointers[ 0 ]; + + return this._pointerPositions[ pointerId ]; + + } + + // + + _customWheelEvent( event ) { + + const mode = event.deltaMode; + + // minimal wheel event altered to meet delta-zoom demand + const newEvent = { + clientX: event.clientX, + clientY: event.clientY, + deltaY: event.deltaY, + }; + + switch ( mode ) { + + case 1: // LINE_MODE + newEvent.deltaY *= 16; + break; + + case 2: // PAGE_MODE + newEvent.deltaY *= 100; + break; + + } + + // detect if event was triggered by pinching + if ( event.ctrlKey && ! this._controlActive ) { + + newEvent.deltaY *= 10; + + } + + return newEvent; + + } + +} + +function onPointerDown( event ) { + + if ( this.enabled === false ) return; + + if ( this._pointers.length === 0 ) { + + this.domElement.setPointerCapture( event.pointerId ); + + this.domElement.ownerDocument.addEventListener( 'pointermove', this._onPointerMove ); + this.domElement.ownerDocument.addEventListener( 'pointerup', this._onPointerUp ); + + } + + // + + if ( this._isTrackingPointer( event ) ) return; + + // + + this._addPointer( event ); + + if ( event.pointerType === 'touch' ) { + + this._onTouchStart( event ); + + } else { + + this._onMouseDown( event ); + + } + + if ( this._cursorStyle === 'grab' ) { + + this.domElement.style.cursor = 'grabbing'; + + } + +} + +function onPointerMove( event ) { + + if ( this.enabled === false ) return; + + if ( event.pointerType === 'touch' ) { + + this._onTouchMove( event ); + + } else { + + this._onMouseMove( event ); + + } + +} + +function onPointerUp( event ) { + + this._removePointer( event ); + + switch ( this._pointers.length ) { + + case 0: + + this.domElement.releasePointerCapture( event.pointerId ); + + this.domElement.ownerDocument.removeEventListener( 'pointermove', this._onPointerMove ); + this.domElement.ownerDocument.removeEventListener( 'pointerup', this._onPointerUp ); + + this.dispatchEvent( _endEvent ); + + this.state = _STATE.NONE; + + if ( this._cursorStyle === 'grab' ) { + + this.domElement.style.cursor = 'grab'; + + } + + break; + + case 1: + + const pointerId = this._pointers[ 0 ]; + const position = this._pointerPositions[ pointerId ]; + + // minimal placeholder event - allows state correction on pointer-up + this._onTouchStart( { pointerId: pointerId, pageX: position.x, pageY: position.y } ); + + break; + + } + +} + +function onMouseDown( event ) { + + let mouseAction; + + switch ( event.button ) { + + case 0: + + mouseAction = this.mouseButtons.LEFT; + break; + + case 1: + + mouseAction = this.mouseButtons.MIDDLE; + break; + + case 2: + + mouseAction = this.mouseButtons.RIGHT; + break; + + default: + + mouseAction = - 1; + + } + + switch ( mouseAction ) { + + case MOUSE.DOLLY: + + if ( this.enableZoom === false ) return; + + this._handleMouseDownDolly( event ); + + this.state = _STATE.DOLLY; + + break; + + case MOUSE.ROTATE: + + if ( event.ctrlKey || event.metaKey || event.shiftKey ) { + + if ( this.enablePan === false ) return; + + this._handleMouseDownPan( event ); + + this.state = _STATE.PAN; + + } else { + + if ( this.enableRotate === false ) return; + + this._handleMouseDownRotate( event ); + + this.state = _STATE.ROTATE; + + } + + break; + + case MOUSE.PAN: + + if ( event.ctrlKey || event.metaKey || event.shiftKey ) { + + if ( this.enableRotate === false ) return; + + this._handleMouseDownRotate( event ); + + this.state = _STATE.ROTATE; + + } else { + + if ( this.enablePan === false ) return; + + this._handleMouseDownPan( event ); + + this.state = _STATE.PAN; + + } + + break; + + default: + + this.state = _STATE.NONE; + + } + + if ( this.state !== _STATE.NONE ) { + + this.dispatchEvent( _startEvent ); + + } + +} + +function onMouseMove( event ) { + + switch ( this.state ) { + + case _STATE.ROTATE: + + if ( this.enableRotate === false ) return; + + this._handleMouseMoveRotate( event ); + + break; + + case _STATE.DOLLY: + + if ( this.enableZoom === false ) return; + + this._handleMouseMoveDolly( event ); + + break; + + case _STATE.PAN: + + if ( this.enablePan === false ) return; + + this._handleMouseMovePan( event ); + + break; + + } + +} + +function onMouseWheel( event ) { + + if ( this.enabled === false || this.enableZoom === false || this.state !== _STATE.NONE ) return; + + event.preventDefault(); + + this.dispatchEvent( _startEvent ); + + this._handleMouseWheel( this._customWheelEvent( event ) ); + + this.dispatchEvent( _endEvent ); + +} + +function onKeyDown( event ) { + + if ( this.enabled === false ) return; + + this._handleKeyDown( event ); + +} + +function onTouchStart( event ) { + + this._trackPointer( event ); + + switch ( this._pointers.length ) { + + case 1: + + switch ( this.touches.ONE ) { + + case TOUCH.ROTATE: + + if ( this.enableRotate === false ) return; + + this._handleTouchStartRotate( event ); + + this.state = _STATE.TOUCH_ROTATE; + + break; + + case TOUCH.PAN: + + if ( this.enablePan === false ) return; + + this._handleTouchStartPan( event ); + + this.state = _STATE.TOUCH_PAN; + + break; + + default: + + this.state = _STATE.NONE; + + } + + break; + + case 2: + + switch ( this.touches.TWO ) { + + case TOUCH.DOLLY_PAN: + + if ( this.enableZoom === false && this.enablePan === false ) return; + + this._handleTouchStartDollyPan( event ); + + this.state = _STATE.TOUCH_DOLLY_PAN; + + break; + + case TOUCH.DOLLY_ROTATE: + + if ( this.enableZoom === false && this.enableRotate === false ) return; + + this._handleTouchStartDollyRotate( event ); + + this.state = _STATE.TOUCH_DOLLY_ROTATE; + + break; + + default: + + this.state = _STATE.NONE; + + } + + break; + + default: + + this.state = _STATE.NONE; + + } + + if ( this.state !== _STATE.NONE ) { + + this.dispatchEvent( _startEvent ); + + } + +} + +function onTouchMove( event ) { + + this._trackPointer( event ); + + switch ( this.state ) { + + case _STATE.TOUCH_ROTATE: + + if ( this.enableRotate === false ) return; + + this._handleTouchMoveRotate( event ); + + this.update(); + + break; + + case _STATE.TOUCH_PAN: + + if ( this.enablePan === false ) return; + + this._handleTouchMovePan( event ); + + this.update(); + + break; + + case _STATE.TOUCH_DOLLY_PAN: + + if ( this.enableZoom === false && this.enablePan === false ) return; + + this._handleTouchMoveDollyPan( event ); + + this.update(); + + break; + + case _STATE.TOUCH_DOLLY_ROTATE: + + if ( this.enableZoom === false && this.enableRotate === false ) return; + + this._handleTouchMoveDollyRotate( event ); + + this.update(); + + break; + + default: + + this.state = _STATE.NONE; + + } + +} + +function onContextMenu( event ) { + + if ( this.enabled === false ) return; + + event.preventDefault(); + +} + +function interceptControlDown( event ) { + + if ( event.key === 'Control' ) { + + this._controlActive = true; + + const document = this.domElement.getRootNode(); // offscreen canvas compatibility + + document.addEventListener( 'keyup', this._interceptControlUp, { passive: true, capture: true } ); + + } + +} + +function interceptControlUp( event ) { + + if ( event.key === 'Control' ) { + + this._controlActive = false; + + const document = this.domElement.getRootNode(); // offscreen canvas compatibility + + document.removeEventListener( 'keyup', this._interceptControlUp, { passive: true, capture: true } ); + + } + +} + +export { OrbitControls }; diff --git a/module-test/vendor/three/RoomEnvironment.js b/module-test/vendor/three/RoomEnvironment.js new file mode 100644 index 00000000000..49867cd77ea --- /dev/null +++ b/module-test/vendor/three/RoomEnvironment.js @@ -0,0 +1,185 @@ +import { + BackSide, + BoxGeometry, + InstancedMesh, + Mesh, + MeshLambertMaterial, + MeshStandardMaterial, + PointLight, + Scene, + Object3D, +} from 'three'; + +/** + * This class represents a scene with a basic room setup that can be used as + * input for {@link PMREMGenerator#fromScene}. The resulting PMREM represents the room's + * lighting and can be used for Image Based Lighting by assigning it to {@link Scene#environment} + * or directly as an environment map to PBR materials. + * + * The implementation is based on the [EnvironmentScene](https://github.com/google/model-viewer/blob/master/packages/model-viewer/src/three-components/EnvironmentScene.ts) + * component from the `model-viewer` project. + * + * ```js + * const environment = new RoomEnvironment(); + * const pmremGenerator = new THREE.PMREMGenerator( renderer ); + * + * const envMap = pmremGenerator.fromScene( environment ).texture; + * scene.environment = envMap; + * ``` + * + * @augments Scene + * @three_import import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js'; + */ +class RoomEnvironment extends Scene { + + constructor() { + + super(); + + this.name = 'RoomEnvironment'; + this.position.y = - 3.5; + + const geometry = new BoxGeometry(); + geometry.deleteAttribute( 'uv' ); + + const roomMaterial = new MeshStandardMaterial( { side: BackSide } ); + const boxMaterial = new MeshStandardMaterial(); + + const mainLight = new PointLight( 0xffffff, 900, 28, 2 ); + mainLight.position.set( 0.418, 16.199, 0.300 ); + this.add( mainLight ); + + const room = new Mesh( geometry, roomMaterial ); + room.position.set( - 0.757, 13.219, 0.717 ); + room.scale.set( 31.713, 28.305, 28.591 ); + this.add( room ); + + const boxes = new InstancedMesh( geometry, boxMaterial, 6 ); + const transform = new Object3D(); + + // box1 + transform.position.set( - 10.906, 2.009, 1.846 ); + transform.rotation.set( 0, - 0.195, 0 ); + transform.scale.set( 2.328, 7.905, 4.651 ); + transform.updateMatrix(); + boxes.setMatrixAt( 0, transform.matrix ); + + // box2 + transform.position.set( - 5.607, - 0.754, - 0.758 ); + transform.rotation.set( 0, 0.994, 0 ); + transform.scale.set( 1.970, 1.534, 3.955 ); + transform.updateMatrix(); + boxes.setMatrixAt( 1, transform.matrix ); + + // box3 + transform.position.set( 6.167, 0.857, 7.803 ); + transform.rotation.set( 0, 0.561, 0 ); + transform.scale.set( 3.927, 6.285, 3.687 ); + transform.updateMatrix(); + boxes.setMatrixAt( 2, transform.matrix ); + + // box4 + transform.position.set( - 2.017, 0.018, 6.124 ); + transform.rotation.set( 0, 0.333, 0 ); + transform.scale.set( 2.002, 4.566, 2.064 ); + transform.updateMatrix(); + boxes.setMatrixAt( 3, transform.matrix ); + + // box5 + transform.position.set( 2.291, - 0.756, - 2.621 ); + transform.rotation.set( 0, - 0.286, 0 ); + transform.scale.set( 1.546, 1.552, 1.496 ); + transform.updateMatrix(); + boxes.setMatrixAt( 4, transform.matrix ); + + // box6 + transform.position.set( - 2.193, - 0.369, - 5.547 ); + transform.rotation.set( 0, 0.516, 0 ); + transform.scale.set( 3.875, 3.487, 2.986 ); + transform.updateMatrix(); + boxes.setMatrixAt( 5, transform.matrix ); + + this.add( boxes ); + + + // -x right + const light1 = new Mesh( geometry, createAreaLightMaterial( 50 ) ); + light1.position.set( - 16.116, 14.37, 8.208 ); + light1.scale.set( 0.1, 2.428, 2.739 ); + this.add( light1 ); + + // -x left + const light2 = new Mesh( geometry, createAreaLightMaterial( 50 ) ); + light2.position.set( - 16.109, 18.021, - 8.207 ); + light2.scale.set( 0.1, 2.425, 2.751 ); + this.add( light2 ); + + // +x + const light3 = new Mesh( geometry, createAreaLightMaterial( 17 ) ); + light3.position.set( 14.904, 12.198, - 1.832 ); + light3.scale.set( 0.15, 4.265, 6.331 ); + this.add( light3 ); + + // +z + const light4 = new Mesh( geometry, createAreaLightMaterial( 43 ) ); + light4.position.set( - 0.462, 8.89, 14.520 ); + light4.scale.set( 4.38, 5.441, 0.088 ); + this.add( light4 ); + + // -z + const light5 = new Mesh( geometry, createAreaLightMaterial( 20 ) ); + light5.position.set( 3.235, 11.486, - 12.541 ); + light5.scale.set( 2.5, 2.0, 0.1 ); + this.add( light5 ); + + // +y + const light6 = new Mesh( geometry, createAreaLightMaterial( 100 ) ); + light6.position.set( 0.0, 20.0, 0.0 ); + light6.scale.set( 1.0, 0.1, 1.0 ); + this.add( light6 ); + + } + + /** + * Frees internal resources. This method should be called + * when the environment is no longer required. + */ + dispose() { + + const resources = new Set(); + + this.traverse( ( object ) => { + + if ( object.isMesh ) { + + resources.add( object.geometry ); + resources.add( object.material ); + + } + + } ); + + for ( const resource of resources ) { + + resource.dispose(); + + } + + } + +} + +function createAreaLightMaterial( intensity ) { + + // create an emissive-only material. see #31348 + const material = new MeshLambertMaterial( { + color: 0x000000, + emissive: 0xffffff, + emissiveIntensity: intensity + } ); + + return material; + +} + +export { RoomEnvironment }; diff --git a/module-test/vendor/three/three.core.js b/module-test/vendor/three/three.core.js new file mode 100644 index 00000000000..0a1d6cb9ef3 --- /dev/null +++ b/module-test/vendor/three/three.core.js @@ -0,0 +1,60586 @@ +/** + * @license + * Copyright 2010-2026 Three.js Authors + * SPDX-License-Identifier: MIT + */ +const REVISION = '186'; + +/** + * Represents mouse buttons and interaction types in context of controls. + * + * @type {ConstantsMouse} + * @constant + */ +const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 }; + +/** + * Represents touch interaction types in context of controls. + * + * @type {ConstantsTouch} + * @constant + */ +const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 }; + +/** + * Disables face culling. + * + * @type {number} + * @constant + */ +const CullFaceNone = 0; + +/** + * Culls back faces. + * + * @type {number} + * @constant + */ +const CullFaceBack = 1; + +/** + * Culls front faces. + * + * @type {number} + * @constant + */ +const CullFaceFront = 2; + +/** + * Culls both front and back faces. + * + * @type {number} + * @constant + */ +const CullFaceFrontBack = 3; + +/** + * Gives unfiltered shadow maps - fastest, but lowest quality. + * + * @type {number} + * @constant + */ +const BasicShadowMap = 0; + +/** + * Filters shadow maps using the Percentage-Closer Filtering (PCF) algorithm. + * + * @type {number} + * @constant + */ +const PCFShadowMap = 1; + +/** + * Filters shadow maps using the Percentage-Closer Filtering (PCF) algorithm with + * better soft shadows especially when using low-resolution shadow maps. + * + * @type {number} + * @constant + * @deprecated since r186. Use `PCFShadowMap` instead. + */ +const PCFSoftShadowMap = 2; + +/** + * Filters shadow maps using the Variance Shadow Map (VSM) algorithm. + * When using VSMShadowMap all shadow receivers will also cast shadows. + * + * @type {number} + * @constant + */ +const VSMShadowMap = 3; + +/** + * Only front faces are rendered. + * + * @type {number} + * @constant + */ +const FrontSide = 0; + +/** + * Only back faces are rendered. + * + * @type {number} + * @constant + */ +const BackSide = 1; + +/** + * Both front and back faces are rendered. + * + * @type {number} + * @constant + */ +const DoubleSide = 2; + +/** + * No blending is performed which effectively disables + * alpha transparency. + * + * @type {number} + * @constant + */ +const NoBlending = 0; + +/** + * The default blending. + * + * @type {number} + * @constant + */ +const NormalBlending = 1; + +/** + * Represents additive blending. + * + * @type {number} + * @constant + */ +const AdditiveBlending = 2; + +/** + * Represents subtractive blending. + * + * @type {number} + * @constant + */ +const SubtractiveBlending = 3; + +/** + * Represents multiply blending. + * + * @type {number} + * @constant + */ +const MultiplyBlending = 4; + +/** + * Represents custom blending. + * + * @type {number} + * @constant + */ +const CustomBlending = 5; + +/** + * Represents material blending. + * + * @type {number} + * @constant + */ +const MaterialBlending = 6; + +/** + * A `source + destination` blending equation. + * + * @type {number} + * @constant + */ +const AddEquation = 100; + +/** + * A `source - destination` blending equation. + * + * @type {number} + * @constant + */ +const SubtractEquation = 101; + +/** + * A `destination - source` blending equation. + * + * @type {number} + * @constant + */ +const ReverseSubtractEquation = 102; + +/** + * A blend equation that uses the minimum of source and destination. + * + * @type {number} + * @constant + */ +const MinEquation = 103; + +/** + * A blend equation that uses the maximum of source and destination. + * + * @type {number} + * @constant + */ +const MaxEquation = 104; + +/** + * Multiplies all colors by `0`. + * + * @type {number} + * @constant + */ +const ZeroFactor = 200; + +/** + * Multiplies all colors by `1`. + * + * @type {number} + * @constant + */ +const OneFactor = 201; + +/** + * Multiplies all colors by the source colors. + * + * @type {number} + * @constant + */ +const SrcColorFactor = 202; + +/** + * Multiplies all colors by `1` minus each source color. + * + * @type {number} + * @constant + */ +const OneMinusSrcColorFactor = 203; + +/** + * Multiplies all colors by the source alpha value. + * + * @type {number} + * @constant + */ +const SrcAlphaFactor = 204; + +/** + * Multiplies all colors by 1 minus the source alpha value. + * + * @type {number} + * @constant + */ +const OneMinusSrcAlphaFactor = 205; + +/** + * Multiplies all colors by the destination alpha value. + * + * @type {number} + * @constant + */ +const DstAlphaFactor = 206; + +/** + * Multiplies all colors by `1` minus the destination alpha value. + * + * @type {number} + * @constant + */ +const OneMinusDstAlphaFactor = 207; + +/** + * Multiplies all colors by the destination color. + * + * @type {number} + * @constant + */ +const DstColorFactor = 208; + +/** + * Multiplies all colors by `1` minus each destination color. + * + * @type {number} + * @constant + */ +const OneMinusDstColorFactor = 209; + +/** + * Multiplies the RGB colors by the smaller of either the source alpha + * value or the value of `1` minus the destination alpha value. The alpha + * value is multiplied by `1`. + * + * @type {number} + * @constant + */ +const SrcAlphaSaturateFactor = 210; + +/** + * Multiplies all colors by a constant color. + * + * @type {number} + * @constant + */ +const ConstantColorFactor = 211; + +/** + * Multiplies all colors by `1` minus a constant color. + * + * @type {number} + * @constant + */ +const OneMinusConstantColorFactor = 212; + +/** + * Multiplies all colors by a constant alpha value. + * + * @type {number} + * @constant + */ +const ConstantAlphaFactor = 213; + +/** + * Multiplies all colors by 1 minus a constant alpha value. + * + * @type {number} + * @constant + */ +const OneMinusConstantAlphaFactor = 214; + +/** + * Never pass. + * + * @type {number} + * @constant + */ +const NeverDepth = 0; + +/** + * Always pass. + * + * @type {number} + * @constant + */ +const AlwaysDepth = 1; + +/** + * Pass if the incoming value is less than the depth buffer value. + * + * @type {number} + * @constant + */ +const LessDepth = 2; + +/** + * Pass if the incoming value is less than or equal to the depth buffer value. + * + * @type {number} + * @constant + */ +const LessEqualDepth = 3; + +/** + * Pass if the incoming value equals the depth buffer value. + * + * @type {number} + * @constant + */ +const EqualDepth = 4; + +/** + * Pass if the incoming value is greater than or equal to the depth buffer value. + * + * @type {number} + * @constant + */ +const GreaterEqualDepth = 5; + +/** + * Pass if the incoming value is greater than the depth buffer value. + * + * @type {number} + * @constant + */ +const GreaterDepth = 6; + +/** + * Pass if the incoming value is not equal to the depth buffer value. + * + * @type {number} + * @constant + */ +const NotEqualDepth = 7; + +/** + * Multiplies the environment map color with the surface color. + * + * @type {number} + * @constant + */ +const MultiplyOperation = 0; + +/** + * Uses reflectivity to blend between the two colors. + * + * @type {number} + * @constant + */ +const MixOperation = 1; + +/** + * Adds the two colors. + * + * @type {number} + * @constant + */ +const AddOperation = 2; + +/** + * No tone mapping is applied. + * + * @type {number} + * @constant + */ +const NoToneMapping = 0; + +/** + * Linear tone mapping. + * + * @type {number} + * @constant + */ +const LinearToneMapping = 1; + +/** + * Reinhard tone mapping. + * + * @type {number} + * @constant + */ +const ReinhardToneMapping = 2; + +/** + * Cineon tone mapping. + * + * @type {number} + * @constant + */ +const CineonToneMapping = 3; + +/** + * ACES Filmic tone mapping. + * + * @type {number} + * @constant + */ +const ACESFilmicToneMapping = 4; + +/** + * Custom tone mapping. + * + * Expects a custom implementation by modifying shader code of the material's fragment shader. + * + * @type {number} + * @constant + */ +const CustomToneMapping = 5; + +/** + * AgX tone mapping. + * + * @type {number} + * @constant + */ +const AgXToneMapping = 6; + +/** + * Neutral tone mapping. + * + * Implementation based on the Khronos 3D Commerce Group standard tone mapping. + * + * @type {number} + * @constant + */ +const NeutralToneMapping = 7; + +/** + * The skinned mesh shares the same world space as the skeleton. + * + * @type {string} + * @constant + */ +const AttachedBindMode = 'attached'; + +/** + * The skinned mesh does not share the same world space as the skeleton. + * This is useful when a skeleton is shared across multiple skinned meshes. + * + * @type {string} + * @constant + */ +const DetachedBindMode = 'detached'; + +/** + * Maps textures using the geometry's UV coordinates. + * + * @type {number} + * @constant + */ +const UVMapping = 300; + +/** + * Reflection mapping for cube textures. + * + * @type {number} + * @constant + */ +const CubeReflectionMapping = 301; + +/** + * Refraction mapping for cube textures. + * + * @type {number} + * @constant + */ +const CubeRefractionMapping = 302; + +/** + * Reflection mapping for equirectangular textures. + * + * @type {number} + * @constant + */ +const EquirectangularReflectionMapping = 303; + +/** + * Refraction mapping for equirectangular textures. + * + * @type {number} + * @constant + */ +const EquirectangularRefractionMapping = 304; + +/** + * Reflection mapping for PMREM textures. + * + * @type {number} + * @constant + */ +const CubeUVReflectionMapping = 306; + +/** + * The texture will simply repeat to infinity. + * + * @type {number} + * @constant + */ +const RepeatWrapping = 1000; + +/** + * The last pixel of the texture stretches to the edge of the mesh. + * + * @type {number} + * @constant + */ +const ClampToEdgeWrapping = 1001; + +/** + * The texture will repeats to infinity, mirroring on each repeat. + * + * @type {number} + * @constant + */ +const MirroredRepeatWrapping = 1002; + +/** + * Returns the value of the texture element that is nearest (in Manhattan distance) + * to the specified texture coordinates. + * + * @type {number} + * @constant + */ +const NearestFilter = 1003; + +/** + * Chooses the mipmap that most closely matches the size of the pixel being textured + * and uses the `NearestFilter` criterion (the texel nearest to the center of the pixel) + * to produce a texture value. + * + * @type {number} + * @constant + */ +const NearestMipmapNearestFilter = 1004; +const NearestMipMapNearestFilter = 1004; // legacy + +/** + * Chooses the two mipmaps that most closely match the size of the pixel being textured and + * uses the `NearestFilter` criterion to produce a texture value from each mipmap. + * The final texture value is a weighted average of those two values. + * + * @type {number} + * @constant + */ +const NearestMipmapLinearFilter = 1005; +const NearestMipMapLinearFilter = 1005; // legacy + +/** + * Returns the weighted average of the four texture elements that are closest to the specified + * texture coordinates, and can include items wrapped or repeated from other parts of a texture, + * depending on the values of `wrapS` and `wrapT`, and on the exact mapping. + * + * @type {number} + * @constant + */ +const LinearFilter = 1006; + +/** + * Chooses the mipmap that most closely matches the size of the pixel being textured and uses + * the `LinearFilter` criterion (a weighted average of the four texels that are closest to the + * center of the pixel) to produce a texture value. + * + * @type {number} + * @constant + */ +const LinearMipmapNearestFilter = 1007; +const LinearMipMapNearestFilter = 1007; // legacy + +/** + * Chooses the two mipmaps that most closely match the size of the pixel being textured and uses + * the `LinearFilter` criterion to produce a texture value from each mipmap. The final texture value + * is a weighted average of those two values. + * + * @type {number} + * @constant + */ +const LinearMipmapLinearFilter = 1008; +const LinearMipMapLinearFilter = 1008; // legacy + +/** + * An unsigned byte data type for textures. + * + * @type {number} + * @constant + */ +const UnsignedByteType = 1009; + +/** + * A byte data type for textures. + * + * @type {number} + * @constant + */ +const ByteType = 1010; + +/** + * A short data type for textures. + * + * @type {number} + * @constant + */ +const ShortType = 1011; + +/** + * An unsigned short data type for textures. + * + * @type {number} + * @constant + */ +const UnsignedShortType = 1012; + +/** + * An int data type for textures. + * + * @type {number} + * @constant + */ +const IntType = 1013; + +/** + * An unsigned int data type for textures. + * + * @type {number} + * @constant + */ +const UnsignedIntType = 1014; + +/** + * A float data type for textures. + * + * @type {number} + * @constant + */ +const FloatType = 1015; + +/** + * A half float data type for textures. + * + * @type {number} + * @constant + */ +const HalfFloatType = 1016; + +/** + * An unsigned short 4_4_4_4 (packed) data type for textures. + * + * @type {number} + * @constant + */ +const UnsignedShort4444Type = 1017; + +/** + * An unsigned short 5_5_5_1 (packed) data type for textures. + * + * @type {number} + * @constant + */ +const UnsignedShort5551Type = 1018; + +/** + * An unsigned int 24_8 data type for textures. + * + * @type {number} + * @constant + */ +const UnsignedInt248Type = 1020; + +/** + * An unsigned int 5_9_9_9 (packed) data type for textures. + * + * @type {number} + * @constant + */ +const UnsignedInt5999Type = 35902; + +/** + * An unsigned int 10_11_11 (packed) data type for textures. + * + * @type {number} + * @constant + */ +const UnsignedInt101111Type = 35899; + +/** + * Discards the red, green and blue components and reads just the alpha component. + * + * @type {number} + * @constant + */ +const AlphaFormat = 1021; + +/** + * Discards the alpha component and reads the red, green and blue component. + * + * @type {number} + * @constant + */ +const RGBFormat = 1022; + +/** + * Reads the red, green, blue and alpha components. + * + * @type {number} + * @constant + */ +const RGBAFormat = 1023; + +/** + * Reads each element as a single depth value, converts it to floating point, and clamps to the range `[0,1]`. + * + * @type {number} + * @constant + */ +const DepthFormat = 1026; + +/** + * Reads each element is a pair of depth and stencil values. The depth component of the pair is interpreted as + * in `DepthFormat`. The stencil component is interpreted based on the depth + stencil internal format. + * + * @type {number} + * @constant + */ +const DepthStencilFormat = 1027; + +/** + * Discards the green, blue and alpha components and reads just the red component. + * + * @type {number} + * @constant + */ +const RedFormat = 1028; + +/** + * Discards the green, blue and alpha components and reads just the red component. The texels are read as integers instead of floating point. + * + * @type {number} + * @constant + */ +const RedIntegerFormat = 1029; + +/** + * Discards the alpha, and blue components and reads the red, and green components. + * + * @type {number} + * @constant + */ +const RGFormat = 1030; + +/** + * Discards the alpha, and blue components and reads the red, and green components. The texels are read as integers instead of floating point. + * + * @type {number} + * @constant + */ +const RGIntegerFormat = 1031; + +/** + * Discards the alpha component and reads the red, green and blue component. The texels are read as integers instead of floating point. + * + * @type {number} + * @constant + */ +const RGBIntegerFormat = 1032; + +/** + * Reads the red, green, blue and alpha components. The texels are read as integers instead of floating point. + * + * @type {number} + * @constant + */ +const RGBAIntegerFormat = 1033; + +/** + * A DXT1-compressed image in an RGB image format. + * + * @type {number} + * @constant + */ +const RGB_S3TC_DXT1_Format = 33776; + +/** + * A DXT1-compressed image in an RGB image format with a simple on/off alpha value. + * + * @type {number} + * @constant + */ +const RGBA_S3TC_DXT1_Format = 33777; + +/** + * A DXT3-compressed image in an RGBA image format. Compared to a 32-bit RGBA texture, it offers 4:1 compression. + * + * @type {number} + * @constant + */ +const RGBA_S3TC_DXT3_Format = 33778; + +/** + * A DXT5-compressed image in an RGBA image format. It also provides a 4:1 compression, but differs to the DXT3 + * compression in how the alpha compression is done. + * + * @type {number} + * @constant + */ +const RGBA_S3TC_DXT5_Format = 33779; + +/** + * PVRTC RGB compression in 4-bit mode. One block for each 4×4 pixels. + * + * @type {number} + * @constant + */ +const RGB_PVRTC_4BPPV1_Format = 35840; + +/** + * PVRTC RGB compression in 2-bit mode. One block for each 8×4 pixels. + * + * @type {number} + * @constant + */ +const RGB_PVRTC_2BPPV1_Format = 35841; + +/** + * PVRTC RGBA compression in 4-bit mode. One block for each 4×4 pixels. + * + * @type {number} + * @constant + */ +const RGBA_PVRTC_4BPPV1_Format = 35842; + +/** + * PVRTC RGBA compression in 2-bit mode. One block for each 8×4 pixels. + * + * @type {number} + * @constant + */ +const RGBA_PVRTC_2BPPV1_Format = 35843; + +/** + * ETC1 RGB format. + * + * @type {number} + * @constant + */ +const RGB_ETC1_Format = 36196; + +/** + * ETC2 RGB format. + * + * @type {number} + * @constant + */ +const RGB_ETC2_Format = 37492; + +/** + * ETC2 RGBA format. + * + * @type {number} + * @constant + */ +const RGBA_ETC2_EAC_Format = 37496; + +/** + * EAC R11 UNORM format. + * + * @type {number} + * @constant + */ +const R11_EAC_Format = 37488; // 0x9270 + +/** + * EAC R11 SNORM format. + * + * @type {number} + * @constant + */ +const SIGNED_R11_EAC_Format = 37489; // 0x9271 + +/** + * EAC RG11 UNORM format. + * + * @type {number} + * @constant + */ +const RG11_EAC_Format = 37490; // 0x9272 + +/** + * EAC RG11 SNORM format. + * + * @type {number} + * @constant + */ +const SIGNED_RG11_EAC_Format = 37491; // 0x9273 + +/** + * ASTC RGBA 4x4 format. + * + * @type {number} + * @constant + */ +const RGBA_ASTC_4x4_Format = 37808; + +/** + * ASTC RGBA 5x4 format. + * + * @type {number} + * @constant + */ +const RGBA_ASTC_5x4_Format = 37809; + +/** + * ASTC RGBA 5x5 format. + * + * @type {number} + * @constant + */ +const RGBA_ASTC_5x5_Format = 37810; + +/** + * ASTC RGBA 6x5 format. + * + * @type {number} + * @constant + */ +const RGBA_ASTC_6x5_Format = 37811; + +/** + * ASTC RGBA 6x6 format. + * + * @type {number} + * @constant + */ +const RGBA_ASTC_6x6_Format = 37812; + +/** + * ASTC RGBA 8x5 format. + * + * @type {number} + * @constant + */ +const RGBA_ASTC_8x5_Format = 37813; + +/** + * ASTC RGBA 8x6 format. + * + * @type {number} + * @constant + */ +const RGBA_ASTC_8x6_Format = 37814; + +/** + * ASTC RGBA 8x8 format. + * + * @type {number} + * @constant + */ +const RGBA_ASTC_8x8_Format = 37815; + +/** + * ASTC RGBA 10x5 format. + * + * @type {number} + * @constant + */ +const RGBA_ASTC_10x5_Format = 37816; + +/** + * ASTC RGBA 10x6 format. + * + * @type {number} + * @constant + */ +const RGBA_ASTC_10x6_Format = 37817; + +/** + * ASTC RGBA 10x8 format. + * + * @type {number} + * @constant + */ +const RGBA_ASTC_10x8_Format = 37818; + +/** + * ASTC RGBA 10x10 format. + * + * @type {number} + * @constant + */ +const RGBA_ASTC_10x10_Format = 37819; + +/** + * ASTC RGBA 12x10 format. + * + * @type {number} + * @constant + */ +const RGBA_ASTC_12x10_Format = 37820; + +/** + * ASTC RGBA 12x12 format. + * + * @type {number} + * @constant + */ +const RGBA_ASTC_12x12_Format = 37821; + +/** + * BPTC RGBA format. + * + * @type {number} + * @constant + */ +const RGBA_BPTC_Format = 36492; + +/** + * BPTC Signed RGB format. + * + * @type {number} + * @constant + */ +const RGB_BPTC_SIGNED_Format = 36494; + +/** + * BPTC Unsigned RGB format. + * + * @type {number} + * @constant + */ +const RGB_BPTC_UNSIGNED_Format = 36495; + +/** + * RGTC1 Red format. + * + * @type {number} + * @constant + */ +const RED_RGTC1_Format = 36283; + +/** + * RGTC1 Signed Red format. + * + * @type {number} + * @constant + */ +const SIGNED_RED_RGTC1_Format = 36284; + +/** + * RGTC2 Red Green format. + * + * @type {number} + * @constant + */ +const RED_GREEN_RGTC2_Format = 36285; + +/** + * RGTC2 Signed Red Green format. + * + * @type {number} + * @constant + */ +const SIGNED_RED_GREEN_RGTC2_Format = 36286; + +/** + * Animations are played once. + * + * @type {number} + * @constant + */ +const LoopOnce = 2200; + +/** + * Animations are played with a chosen number of repetitions, each time jumping from + * the end of the clip directly to its beginning. + * + * @type {number} + * @constant + */ +const LoopRepeat = 2201; + +/** + * Animations are played with a chosen number of repetitions, alternately playing forward + * and backward. + * + * @type {number} + * @constant + */ +const LoopPingPong = 2202; + +/** + * Discrete interpolation mode for keyframe tracks. + * + * @type {number} + * @constant + */ +const InterpolateDiscrete = 2300; + +/** + * Linear interpolation mode for keyframe tracks. + * + * @type {number} + * @constant + */ +const InterpolateLinear = 2301; + +/** + * Smooth interpolation mode for keyframe tracks. + * + * @type {number} + * @constant + */ +const InterpolateSmooth = 2302; + +/** + * Bezier interpolation mode for keyframe tracks. + * + * Uses cubic Bezier curves with explicit 2D control points. + * Requires tangent data to be set on the track. + * + * @type {number} + * @constant + */ +const InterpolateBezier = 2303; + +/** + * Zero curvature ending for animations. + * + * @type {number} + * @constant + */ +const ZeroCurvatureEnding = 2400; + +/** + * Zero slope ending for animations. + * + * @type {number} + * @constant + */ +const ZeroSlopeEnding = 2401; + +/** + * Wrap around ending for animations. + * + * @type {number} + * @constant + */ +const WrapAroundEnding = 2402; + +/** + * Default animation blend mode. + * + * @type {number} + * @constant + */ +const NormalAnimationBlendMode = 2500; + +/** + * Additive animation blend mode. Can be used to layer motions on top of + * each other to build complex performances from smaller re-usable assets. + * + * @type {number} + * @constant + */ +const AdditiveAnimationBlendMode = 2501; + +/** + * For every three vertices draw a single triangle. + * + * @type {number} + * @constant + */ +const TrianglesDrawMode = 0; + +/** + * For each vertex draw a triangle from the last three vertices. + * + * @type {number} + * @constant + */ +const TriangleStripDrawMode = 1; + +/** + * For each vertex draw a triangle from the first vertex and the last two vertices. + * + * @type {number} + * @constant + */ +const TriangleFanDrawMode = 2; + +/** + * The depth value is inverted (1.0 - z) for visualization purposes. + * + * @type {number} + * @constant + */ +const BasicDepthPacking = 3200; + +/** + * The depth value is packed into 32 bit RGBA. + * + * @type {number} + * @constant + */ +const RGBADepthPacking = 3201; + +/** + * The depth value is packed into 24 bit RGB. + * + * @type {number} + * @constant + */ +const RGBDepthPacking = 3202; + +/** + * The depth value is packed into 16 bit RG. + * + * @type {number} + * @constant + */ +const RGDepthPacking = 3203; + +/** + * Normal information is relative to the underlying surface. + * + * @type {number} + * @constant + */ +const TangentSpaceNormalMap = 0; + +/** + * Normal information is relative to the object orientation. + * + * @type {number} + * @constant + */ +const ObjectSpaceNormalMap = 1; + +// Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available. + +/** + * No color space. + * + * @type {string} + * @constant + */ +const NoColorSpace = ''; + +/** + * sRGB color space. + * + * @type {string} + * @constant + */ +const SRGBColorSpace = 'srgb'; + +/** + * sRGB-linear color space. + * + * @type {string} + * @constant + */ +const LinearSRGBColorSpace = 'srgb-linear'; + +/** + * Linear transfer function. + * + * @type {string} + * @constant + */ +const LinearTransfer = 'linear'; + +/** + * sRGB transfer function. + * + * @type {string} + * @constant + */ +const SRGBTransfer = 'srgb'; + +/** + * No normal map packing. + * + * @type {string} + * @constant + */ +const NoNormalPacking = ''; + +/** + * Normal RG packing. + * + * @type {string} + * @constant + */ +const NormalRGPacking = 'rg'; + +/** + * Normal GA packing. + * + * @type {string} + * @constant + */ +const NormalGAPacking = 'ga'; + +/** + * Sets the stencil buffer value to `0`. + * + * @type {number} + * @constant + */ +const ZeroStencilOp = 0; + +/** + * Keeps the current value. + * + * @type {number} + * @constant + */ +const KeepStencilOp = 7680; + +/** + * Sets the stencil buffer value to the specified reference value. + * + * @type {number} + * @constant + */ +const ReplaceStencilOp = 7681; + +/** + * Increments the current stencil buffer value. Clamps to the maximum representable unsigned value. + * + * @type {number} + * @constant + */ +const IncrementStencilOp = 7682; + +/** + * Decrements the current stencil buffer value. Clamps to `0`. + * + * @type {number} + * @constant + */ +const DecrementStencilOp = 7683; + +/** + * Increments the current stencil buffer value. Wraps stencil buffer value to zero when incrementing + * the maximum representable unsigned value. + * + * @type {number} + * @constant + */ +const IncrementWrapStencilOp = 34055; + +/** + * Decrements the current stencil buffer value. Wraps stencil buffer value to the maximum representable + * unsigned value when decrementing a stencil buffer value of `0`. + * + * @type {number} + * @constant + */ +const DecrementWrapStencilOp = 34056; + +/** + * Inverts the current stencil buffer value bitwise. + * + * @type {number} + * @constant + */ +const InvertStencilOp = 5386; + +/** + * Will never return true. + * + * @type {number} + * @constant + */ +const NeverStencilFunc = 512; + +/** + * Will return true if the stencil reference value is less than the current stencil value. + * + * @type {number} + * @constant + */ +const LessStencilFunc = 513; + +/** + * Will return true if the stencil reference value is equal to the current stencil value. + * + * @type {number} + * @constant + */ +const EqualStencilFunc = 514; + +/** + * Will return true if the stencil reference value is less than or equal to the current stencil value. + * + * @type {number} + * @constant + */ +const LessEqualStencilFunc = 515; + +/** + * Will return true if the stencil reference value is greater than the current stencil value. + * + * @type {number} + * @constant + */ +const GreaterStencilFunc = 516; + +/** + * Will return true if the stencil reference value is not equal to the current stencil value. + * + * @type {number} + * @constant + */ +const NotEqualStencilFunc = 517; + +/** + * Will return true if the stencil reference value is greater than or equal to the current stencil value. + * + * @type {number} + * @constant + */ +const GreaterEqualStencilFunc = 518; + +/** + * Will always return true. + * + * @type {number} + * @constant + */ +const AlwaysStencilFunc = 519; + +/** + * Never pass. + * + * @type {number} + * @constant + */ +const NeverCompare = 512; + +/** + * Pass if the incoming value is less than the texture value. + * + * @type {number} + * @constant + */ +const LessCompare = 513; + +/** + * Pass if the incoming value equals the texture value. + * + * @type {number} + * @constant + */ +const EqualCompare = 514; + +/** + * Pass if the incoming value is less than or equal to the texture value. + * + * @type {number} + * @constant + */ +const LessEqualCompare = 515; + +/** + * Pass if the incoming value is greater than the texture value. + * + * @type {number} + * @constant + */ +const GreaterCompare = 516; + +/** + * Pass if the incoming value is not equal to the texture value. + * + * @type {number} + * @constant + */ +const NotEqualCompare = 517; + +/** + * Pass if the incoming value is greater than or equal to the texture value. + * + * @type {number} + * @constant + */ +const GreaterEqualCompare = 518; + +/** + * Always pass. + * + * @type {number} + * @constant + */ +const AlwaysCompare = 519; + +/** + * The contents are intended to be specified once by the application, and used many + * times as the source for drawing and image specification commands. + * + * @type {number} + * @constant + */ +const StaticDrawUsage = 35044; + +/** + * The contents are intended to be respecified repeatedly by the application, and + * used many times as the source for drawing and image specification commands. + * + * @type {number} + * @constant + */ +const DynamicDrawUsage = 35048; + +/** + * The contents are intended to be specified once by the application, and used at most + * a few times as the source for drawing and image specification commands. + * + * @type {number} + * @constant + */ +const StreamDrawUsage = 35040; + +/** + * The contents are intended to be specified once by reading data from the 3D API, and queried + * many times by the application. + * + * @type {number} + * @constant + */ +const StaticReadUsage = 35045; + +/** + * The contents are intended to be respecified repeatedly by reading data from the 3D API, and queried + * many times by the application. + * + * @type {number} + * @constant + */ +const DynamicReadUsage = 35049; + +/** + * The contents are intended to be specified once by reading data from the 3D API, and queried at most + * a few times by the application + * + * @type {number} + * @constant + */ +const StreamReadUsage = 35041; + +/** + * The contents are intended to be specified once by reading data from the 3D API, and used many times as + * the source for WebGL drawing and image specification commands. + * + * @type {number} + * @constant + */ +const StaticCopyUsage = 35046; + +/** + * The contents are intended to be respecified repeatedly by reading data from the 3D API, and used many times + * as the source for WebGL drawing and image specification commands. + * + * @type {number} + * @constant + */ +const DynamicCopyUsage = 35050; + +/** + * The contents are intended to be specified once by reading data from the 3D API, and used at most a few times + * as the source for WebGL drawing and image specification commands. + * + * @type {number} + * @constant + */ +const StreamCopyUsage = 35042; + +/** + * GLSL 1 shader code. + * + * @type {string} + * @constant + */ +const GLSL1 = '100'; + +/** + * GLSL 3 shader code. + * + * @type {string} + * @constant + */ +const GLSL3 = '300 es'; + +/** + * WebGL coordinate system. + * + * @type {number} + * @constant + */ +const WebGLCoordinateSystem = 2000; + +/** + * WebGPU coordinate system. + * + * @type {number} + * @constant + */ +const WebGPUCoordinateSystem = 2001; + +/** + * Represents the different timestamp query types. + * + * @type {ConstantsTimestampQuery} + * @constant + */ +const TimestampQuery = { + COMPUTE: 'compute', + RENDER: 'render' +}; + +/** + * Represents mouse buttons and interaction types in context of controls. + * + * @type {ConstantsInterpolationSamplingType} + * @constant + */ +const InterpolationSamplingType = { + PERSPECTIVE: 'perspective', + LINEAR: 'linear', + FLAT: 'flat' +}; + +/** + * Represents the different interpolation sampling modes. + * + * @type {ConstantsInterpolationSamplingMode} + * @constant + */ +const InterpolationSamplingMode = { + NORMAL: 'normal', + CENTROID: 'centroid', + SAMPLE: 'sample', + FIRST: 'first', + EITHER: 'either' +}; + +/** + * Compatibility flags for features that may not be supported across all platforms. + * + * @type {Object} + * @constant + */ +const Compatibility = { + TEXTURE_COMPARE: 'depthTextureCompare' +}; + +/** + * Represents the refresh types of render objects. + * + * @type {ConstantsRenderObjectRefreshType} + * @constant + */ +const RenderObjectRefreshType = { + NONE: 0, + SHARED: 1, + FULL: 2 +}; + +/** + * This type represents mouse buttons and interaction types in context of controls. + * + * @typedef {Object} ConstantsMouse + * @property {number} MIDDLE - The left mouse button. + * @property {number} LEFT - The middle mouse button. + * @property {number} RIGHT - The right mouse button. + * @property {number} ROTATE - A rotate interaction. + * @property {number} DOLLY - A dolly interaction. + * @property {number} PAN - A pan interaction. + **/ + +/** + * This type represents touch interaction types in context of controls. + * + * @typedef {Object} ConstantsTouch + * @property {number} ROTATE - A rotate interaction. + * @property {number} PAN - A pan interaction. + * @property {number} DOLLY_PAN - The dolly-pan interaction. + * @property {number} DOLLY_ROTATE - A dolly-rotate interaction. + **/ + +/** + * This type represents the different timestamp query types. + * + * @typedef {Object} ConstantsTimestampQuery + * @property {string} COMPUTE - A `compute` timestamp query. + * @property {string} RENDER - A `render` timestamp query. + **/ + +/** + * Represents the different interpolation sampling types. + * + * @typedef {Object} ConstantsInterpolationSamplingType + * @property {string} PERSPECTIVE - Perspective-correct interpolation. + * @property {string} LINEAR - Linear interpolation. + * @property {string} FLAT - Flat interpolation. + */ + +/** + * Represents the different interpolation sampling modes. + * + * @typedef {Object} ConstantsInterpolationSamplingMode + * @property {string} NORMAL - Normal sampling mode. + * @property {string} CENTROID - Centroid sampling mode. + * @property {string} SAMPLE - Sample-specific sampling mode. + * @property {string} FIRST - Flat interpolation using the first vertex. + * @property {string} EITHER - Flat interpolation using either vertex. + */ + +/** + * Represents the refresh types of render objects. + * + * @typedef {Object} ConstantsRenderObjectRefreshType + * @property {number} NONE - No refresh required. + * @property {number} SHARED - Only shared uniform buffers require an update. + * @property {number} FULL - The render object requires a full refresh. + */ + +/** + * Checks if an array contains values that require Uint32 representation. + * + * This function determines whether the array contains any values >= 65535, + * which would require a Uint32Array rather than a Uint16Array for proper storage. + * The function iterates from the end of the array, assuming larger values are + * typically located at the end. + * + * @private + * @param {Array} array - The array to check. + * @return {boolean} True if the array contains values >= 65535, false otherwise. + */ +function arrayNeedsUint32( array ) { + + // assumes larger values usually on last + + for ( let i = array.length - 1; i >= 0; -- i ) { + + if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565 + + } + + return false; + +} + +/** + * Map of typed array constructor names to their constructors. + * This mapping enables dynamic creation of typed arrays based on string type names. + * + * @private + * @constant + * @type {Object} + */ +const TYPED_ARRAYS = { + Int8Array: Int8Array, + Uint8Array: Uint8Array, + Uint8ClampedArray: Uint8ClampedArray, + Int16Array: Int16Array, + Uint16Array: Uint16Array, + Int32Array: Int32Array, + Uint32Array: Uint32Array, + Float32Array: Float32Array, + Float64Array: Float64Array +}; + +/** + * Creates a typed array of the specified type from the given buffer. + * + * @private + * @param {string} type - The name of the typed array type (e.g., 'Float32Array', 'Uint16Array'). + * @param {ArrayBuffer} buffer - The buffer to create the typed array from. + * @return {TypedArray} A new typed array of the specified type. + */ +function getTypedArray( type, buffer ) { + + return new TYPED_ARRAYS[ type ]( buffer ); + +} + +/** + * Returns `true` if the given object is a typed array. + * + * @param {any} array - The object to check. + * @return {boolean} Whether the given object is a typed array. + */ +function isTypedArray( array ) { + + return ArrayBuffer.isView( array ) && ! ( array instanceof DataView ); + +} + +/** + * Creates an XHTML element with the specified tag name. + * + * This function uses the XHTML namespace to create DOM elements, + * ensuring proper element creation in XML-based contexts. + * + * @private + * @param {string} name - The tag name of the element to create (e.g., 'canvas', 'div'). + * @return {HTMLElement} The created XHTML element. + */ +function createElementNS( name ) { + + return document.createElementNS( 'http://www.w3.org/1999/xhtml', name ); + +} + +/** + * Creates a canvas element configured for block display. + * + * This is a convenience function that creates a canvas element with + * display style set to 'block', which is commonly used in three.js + * rendering contexts to avoid inline element spacing issues. + * + * @return {HTMLCanvasElement} A canvas element with display set to 'block'. + */ +function createCanvasElement() { + + const canvas = createElementNS( 'canvas' ); + canvas.style.display = 'block'; + return canvas; + +} + +/** + * Internal cache for tracking warning messages to prevent duplicate warnings. + * + * @private + * @type {Object} + */ +const _cache = {}; + +/** + * Custom console function handler for intercepting log, warn, and error calls. + * + * @private + * @type {Function|null} + */ +let _setConsoleFunction = null; + +/** + * Sets a custom function to handle console output. + * + * This allows external code to intercept and handle console.log, console.warn, + * and console.error calls made by three.js, which is useful for custom logging, + * testing, or debugging workflows. + * + * @param {Function} fn - The function to handle console output. Should accept + * (type, message, ...params) where type is 'log', 'warn', or 'error'. + */ +function setConsoleFunction( fn ) { + + _setConsoleFunction = fn; + +} + +/** + * Gets the currently set custom console function. + * + * @return {Function|null} The custom console function, or null if not set. + */ +function getConsoleFunction() { + + return _setConsoleFunction; + +} + +/** + * Logs an informational message with the 'THREE.' prefix. + * + * If a custom console function is set via setConsoleFunction(), it will be used + * instead of the native console.log. The first parameter is treated as the + * method name and is automatically prefixed with 'THREE.'. + * + * @param {...any} params - The message components. The first param is used as + * the method name and prefixed with 'THREE.'. + */ +function log( ...params ) { + + const message = 'THREE.' + params.shift(); + + if ( _setConsoleFunction ) { + + _setConsoleFunction( 'log', message, ...params ); + + } else { + + console.log( message, ...params ); + + } + +} + +/** + * Enhances log/warn/error messages related to TSL. + * + * @param {Array} params - The original message parameters. + * @returns {Array} The filtered and enhanced message parameters. + */ +function enhanceLogMessage( params ) { + + const message = params[ 0 ]; + + if ( typeof message === 'string' && message.startsWith( 'TSL:' ) ) { + + const stackTrace = params[ 1 ]; + + if ( stackTrace && stackTrace.isStackTrace ) { + + params[ 0 ] += ' ' + stackTrace.getLocation(); + + } else { + + params[ 1 ] = 'Stack trace not available. Enable "THREE.Node.captureStackTrace" to capture stack traces.'; + + } + + } + + return params; + +} + +/** + * Logs a warning message with the 'THREE.' prefix. + * + * If a custom console function is set via setConsoleFunction(), it will be used + * instead of the native console.warn. The first parameter is treated as the + * method name and is automatically prefixed with 'THREE.'. + * + * @param {...any} params - The message components. The first param is used as + * the method name and prefixed with 'THREE.'. + */ +function warn( ...params ) { + + params = enhanceLogMessage( params ); + + const message = 'THREE.' + params.shift(); + + if ( _setConsoleFunction ) { + + _setConsoleFunction( 'warn', message, ...params ); + + } else { + + const stackTrace = params[ 0 ]; + + if ( stackTrace && stackTrace.isStackTrace ) { + + console.warn( stackTrace.getError( message ) ); + + } else { + + console.warn( message, ...params ); + + } + + } + +} + +/** + * Logs an error message with the 'THREE.' prefix. + * + * If a custom console function is set via setConsoleFunction(), it will be used + * instead of the native console.error. The first parameter is treated as the + * method name and is automatically prefixed with 'THREE.'. + * + * @param {...any} params - The message components. The first param is used as + * the method name and prefixed with 'THREE.'. + */ +function error( ...params ) { + + params = enhanceLogMessage( params ); + + const message = 'THREE.' + params.shift(); + + if ( _setConsoleFunction ) { + + _setConsoleFunction( 'error', message, ...params ); + + } else { + + const stackTrace = params[ 0 ]; + + if ( stackTrace && stackTrace.isStackTrace ) { + + console.error( stackTrace.getError( message ) ); + + } else { + + console.error( message, ...params ); + + } + + } + +} + +/** + * Logs a warning message only once, preventing duplicate warnings. + * + * This function maintains an internal cache of warning messages and will only + * output each unique warning message once. Useful for warnings that may be + * triggered repeatedly but should only be shown to the user once. + * + * @param {...any} params - The warning message components. + */ +function warnOnce( ...params ) { + + const message = params.join( ' ' ); + + if ( message in _cache ) return; + + _cache[ message ] = true; + + warn( ...params ); + +} + +/** + * Yields execution to the main thread to allow rendering and other tasks. + * Uses scheduler.yield() when available (Chrome 115+), falls back to requestAnimationFrame. + * + * @return {Promise} + */ +function yieldToMain() { + + if ( typeof self !== 'undefined' && typeof self.scheduler !== 'undefined' && typeof self.scheduler.yield !== 'undefined' ) { + + return self.scheduler.yield(); + + } + + return new Promise( resolve => { + + requestAnimationFrame( resolve ); + + } ); + +} + +/** + * Asynchronously probes for WebGL sync object completion. + * + * This function creates a promise that resolves when the WebGL sync object + * signals completion or rejects if the sync operation fails. It uses polling + * at the specified interval to check the sync status without blocking the + * main thread. This is useful for GPU-CPU synchronization in WebGL contexts. + * + * @private + * @param {WebGL2RenderingContext} gl - The WebGL rendering context. + * @param {WebGLSync} sync - The WebGL sync object to wait for. + * @param {number} interval - The polling interval in milliseconds. + * @return {Promise} A promise that resolves when the sync completes or rejects if it fails. + */ +function probeAsync( gl, sync, interval ) { + + return new Promise( function ( resolve, reject ) { + + function probe() { + + switch ( gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 ) ) { + + case gl.WAIT_FAILED: + reject(); + break; + + case gl.TIMEOUT_EXPIRED: + setTimeout( probe, interval ); + break; + + default: + resolve(); + + } + + } + + setTimeout( probe, interval ); + + } ); + +} + +/** + * Used to select the correct depth functions + * when reversed depth buffer is used. + * + * @private + * @type {Object} + */ +const ReversedDepthFuncs = { + [ NeverDepth ]: AlwaysDepth, + [ LessDepth ]: GreaterDepth, + [ EqualDepth ]: NotEqualDepth, + [ LessEqualDepth ]: GreaterEqualDepth, + + [ AlwaysDepth ]: NeverDepth, + [ GreaterDepth ]: LessDepth, + [ NotEqualDepth ]: EqualDepth, + [ GreaterEqualDepth ]: LessEqualDepth, +}; + +/** + * This modules allows to dispatch event objects on custom JavaScript objects. + * + * Main repository: [eventdispatcher.js](https://github.com/mrdoob/eventdispatcher.js/) + * + * Code Example: + * ```js + * class Car extends EventDispatcher { + * start() { + * this.dispatchEvent( { type: 'start', message: 'vroom vroom!' } ); + * } + *}; + * + * // Using events with the custom object + * const car = new Car(); + * car.addEventListener( 'start', function ( event ) { + * alert( event.message ); + * } ); + * + * car.start(); + * ``` + */ +class EventDispatcher { + + /** + * Adds the given event listener to the given event type. + * + * @param {string} type - The type of event to listen to. + * @param {Function} listener - The function that gets called when the event is fired. + */ + addEventListener( type, listener ) { + + if ( this._listeners === undefined ) this._listeners = {}; + + const listeners = this._listeners; + + if ( listeners[ type ] === undefined ) { + + listeners[ type ] = []; + + } + + if ( listeners[ type ].indexOf( listener ) === -1 ) { + + listeners[ type ].push( listener ); + + } + + } + + /** + * Returns `true` if the given event listener has been added to the given event type. + * + * @param {string} type - The type of event. + * @param {Function} listener - The listener to check. + * @return {boolean} Whether the given event listener has been added to the given event type. + */ + hasEventListener( type, listener ) { + + const listeners = this._listeners; + + if ( listeners === undefined ) return false; + + return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== -1; + + } + + /** + * Removes the given event listener from the given event type. + * + * @param {string} type - The type of event. + * @param {Function} listener - The listener to remove. + */ + removeEventListener( type, listener ) { + + const listeners = this._listeners; + + if ( listeners === undefined ) return; + + const listenerArray = listeners[ type ]; + + if ( listenerArray !== undefined ) { + + const index = listenerArray.indexOf( listener ); + + if ( index !== -1 ) { + + listenerArray.splice( index, 1 ); + + } + + } + + } + + /** + * Dispatches an event object. + * + * @param {Object} event - The event that gets fired. + */ + dispatchEvent( event ) { + + const listeners = this._listeners; + + if ( listeners === undefined ) return; + + const listenerArray = listeners[ event.type ]; + + if ( listenerArray !== undefined ) { + + event.target = this; + + // Make a copy, in case listeners are removed while iterating. + const array = listenerArray.slice( 0 ); + + for ( let i = 0, l = array.length; i < l; i ++ ) { + + array[ i ].call( this, event ); + + } + + event.target = null; + + } + + } + +} + +const _lut = [ '00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '0a', '0b', '0c', '0d', '0e', '0f', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '1a', '1b', '1c', '1d', '1e', '1f', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '2a', '2b', '2c', '2d', '2e', '2f', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '3a', '3b', '3c', '3d', '3e', '3f', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '4a', '4b', '4c', '4d', '4e', '4f', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '5a', '5b', '5c', '5d', '5e', '5f', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '6a', '6b', '6c', '6d', '6e', '6f', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '7a', '7b', '7c', '7d', '7e', '7f', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '8a', '8b', '8c', '8d', '8e', '8f', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99', '9a', '9b', '9c', '9d', '9e', '9f', 'a0', 'a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9', 'aa', 'ab', 'ac', 'ad', 'ae', 'af', 'b0', 'b1', 'b2', 'b3', 'b4', 'b5', 'b6', 'b7', 'b8', 'b9', 'ba', 'bb', 'bc', 'bd', 'be', 'bf', 'c0', 'c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7', 'c8', 'c9', 'ca', 'cb', 'cc', 'cd', 'ce', 'cf', 'd0', 'd1', 'd2', 'd3', 'd4', 'd5', 'd6', 'd7', 'd8', 'd9', 'da', 'db', 'dc', 'dd', 'de', 'df', 'e0', 'e1', 'e2', 'e3', 'e4', 'e5', 'e6', 'e7', 'e8', 'e9', 'ea', 'eb', 'ec', 'ed', 'ee', 'ef', 'f0', 'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'fa', 'fb', 'fc', 'fd', 'fe', 'ff' ]; + +let _seed = 1234567; + + +const DEG2RAD = Math.PI / 180; +const RAD2DEG = 180 / Math.PI; + +/** + * Generate a [UUID](https://en.wikipedia.org/wiki/Universally_unique_identifier) + * (universally unique identifier). + * + * @return {string} The UUID. + */ +function generateUUID() { + + // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136 + + const d0 = Math.random() * 0xffffffff | 0; + const d1 = Math.random() * 0xffffffff | 0; + const d2 = Math.random() * 0xffffffff | 0; + const d3 = Math.random() * 0xffffffff | 0; + const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' + + _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' + + _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] + + _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ]; + + // .toLowerCase() here flattens concatenated strings to save heap memory space. + return uuid.toLowerCase(); + +} + +/** + * Clamps the given value between min and max. + * + * @param {number} value - The value to clamp. + * @param {number} min - The min value. + * @param {number} max - The max value. + * @return {number} The clamped value. + */ +function clamp( value, min, max ) { + + return Math.max( min, Math.min( max, value ) ); + +} + +/** + * Computes the Euclidean modulo of the given parameters that + * is `( ( n % m ) + m ) % m`. + * + * @param {number} n - The first parameter. + * @param {number} m - The second parameter. + * @return {number} The Euclidean modulo. + */ +function euclideanModulo( n, m ) { + + // https://en.wikipedia.org/wiki/Modulo_operation + + return ( ( n % m ) + m ) % m; + +} + +/** + * Performs a linear mapping from range `` to range `` + * for the given value. `a2` must be greater than `a1`. + * + * @param {number} x - The value to be mapped. + * @param {number} a1 - Minimum value for range A. + * @param {number} a2 - Maximum value for range A. + * @param {number} b1 - Minimum value for range B. + * @param {number} b2 - Maximum value for range B. + * @return {number} The mapped value. + */ +function mapLinear( x, a1, a2, b1, b2 ) { + + return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 ); + +} + +/** + * Returns the percentage in the closed interval `[0, 1]` of the given value + * between the start and end point. + * + * @param {number} x - The start point + * @param {number} y - The end point. + * @param {number} value - A value between start and end. + * @return {number} The interpolation factor. + */ +function inverseLerp( x, y, value ) { + + // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/ + + if ( x !== y ) { + + return ( value - x ) / ( y - x ); + + } else { + + return 0; + + } + +} + +/** + * Returns a value linearly interpolated from two known points based on the given interval - + * `t = 0` will return `x` and `t = 1` will return `y`. + * + * @param {number} x - The start point + * @param {number} y - The end point. + * @param {number} t - The interpolation factor in the closed interval `[0, 1]`. + * @return {number} The interpolated value. + */ +function lerp( x, y, t ) { + + return ( 1 - t ) * x + t * y; + +} + +/** + * Smoothly interpolate a number from `x` to `y` in a spring-like manner using a delta + * time to maintain frame rate independent movement. For details, see + * [Frame rate independent damping using lerp](http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/). + * + * @param {number} x - The current point. + * @param {number} y - The target point. + * @param {number} lambda - A higher lambda value will make the movement more sudden, + * and a lower value will make the movement more gradual. + * @param {number} dt - Delta time in seconds. + * @return {number} The interpolated value. + */ +function damp( x, y, lambda, dt ) { + + return lerp( x, y, 1 - Math.exp( - lambda * dt ) ); + +} + +/** + * Returns a value that alternates between `0` and the given `length` parameter. + * + * @param {number} x - The value to pingpong. + * @param {number} [length=1] - The positive value the function will pingpong to. + * @return {number} The alternated value. + */ +function pingpong( x, length = 1 ) { + + // https://www.desmos.com/calculator/vcsjnyz7x4 + + return length - Math.abs( euclideanModulo( x, length * 2 ) - length ); + +} + +/** + * Returns a value in the range `[0,1]` that represents the percentage that `x` has + * moved between `min` and `max`, but smoothed or slowed down the closer `x` is to + * the `min` and `max`. + * + * See [Smoothstep](http://en.wikipedia.org/wiki/Smoothstep) for more details. + * + * @param {number} x - The value to evaluate based on its position between `min` and `max`. + * @param {number} min - The min value. Any `x` value below `min` will be `0`. `min` must be lower than `max`. + * @param {number} max - The max value. Any `x` value above `max` will be `1`. `max` must be greater than `min`. + * @return {number} The alternated value. + */ +function smoothstep( x, min, max ) { + + if ( x <= min ) return 0; + if ( x >= max ) return 1; + + x = ( x - min ) / ( max - min ); + + return x * x * ( 3 - 2 * x ); + +} + +/** + * A [variation on smoothstep](https://en.wikipedia.org/wiki/Smoothstep#Variations) + * that has zero 1st and 2nd order derivatives at `x=0` and `x=1`. + * + * @param {number} x - The value to evaluate based on its position between `min` and `max`. + * @param {number} min - The min value. Any `x` value below `min` will be `0`. `min` must be lower than `max`. + * @param {number} max - The max value. Any `x` value above `max` will be `1`. `max` must be greater than `min`. + * @return {number} The alternated value. + */ +function smootherstep( x, min, max ) { + + if ( x <= min ) return 0; + if ( x >= max ) return 1; + + x = ( x - min ) / ( max - min ); + + return x * x * x * ( x * ( x * 6 - 15 ) + 10 ); + +} + +/** + * Returns a random integer from `` interval. + * + * @param {number} low - The lower value boundary. + * @param {number} high - The upper value boundary + * @return {number} A random integer. + */ +function randInt( low, high ) { + + return low + Math.floor( Math.random() * ( high - low + 1 ) ); + +} + +/** + * Returns a random float from `` interval. + * + * @param {number} low - The lower value boundary. + * @param {number} high - The upper value boundary + * @return {number} A random float. + */ +function randFloat( low, high ) { + + return low + Math.random() * ( high - low ); + +} + +/** + * Returns a random integer from `<-range/2, range/2>` interval. + * + * @param {number} range - Defines the value range. + * @return {number} A random float. + */ +function randFloatSpread( range ) { + + return range * ( 0.5 - Math.random() ); + +} + +/** + * Returns a deterministic pseudo-random float in the interval `[0, 1]`. + * + * @param {number} [s] - The integer seed. + * @return {number} A random float. + */ +function seededRandom( s ) { + + if ( s !== undefined ) _seed = s; + + // Mulberry32 generator + + let t = _seed += 0x6D2B79F5; + + t = Math.imul( t ^ t >>> 15, t | 1 ); + + t ^= t + Math.imul( t ^ t >>> 7, t | 61 ); + + return ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296; + +} + +/** + * Converts degrees to radians. + * + * @param {number} degrees - A value in degrees. + * @return {number} The converted value in radians. + */ +function degToRad( degrees ) { + + return degrees * DEG2RAD; + +} + +/** + * Converts radians to degrees. + * + * @param {number} radians - A value in radians. + * @return {number} The converted value in degrees. + */ +function radToDeg( radians ) { + + return radians * RAD2DEG; + +} + +/** + * Returns `true` if the given integer is a power of two. + * + * @param {number} value - The value to check. + * @return {boolean} Whether the given integer is a power of two or not. + */ +function isPowerOfTwo( value ) { + + return value > 0 && Number.isInteger( value ) && 2 ** Math.round( Math.log2( value ) ) === value; + +} + +/** + * Returns the smallest power of two that is greater than or equal to the given number. + * + * @param {number} value - The value to find a POT for. Must be greater than `0`. + * @return {number} The smallest power of two that is greater than or equal to the given number. + */ +function ceilPowerOfTwo( value ) { + + return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) ); + +} + +/** + * Returns the largest power of two that is less than or equal to the given number. + * + * @param {number} value - The value to find a POT for. Must be greater than `0`. + * @return {number} The largest power of two that is less than or equal to the given number. + */ +function floorPowerOfTwo( value ) { + + return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) ); + +} + +/** + * Sets the given quaternion from the [Intrinsic Proper Euler Angles](https://en.wikipedia.org/wiki/Euler_angles) + * defined by the given angles and order. + * + * Rotations are applied to the axes in the order specified by order: + * rotation by angle `a` is applied first, then by angle `b`, then by angle `c`. + * + * @param {Quaternion} q - The quaternion to set. + * @param {number} a - The rotation applied to the first axis, in radians. + * @param {number} b - The rotation applied to the second axis, in radians. + * @param {number} c - The rotation applied to the third axis, in radians. + * @param {('XYX'|'XZX'|'YXY'|'YZY'|'ZXZ'|'ZYZ')} order - A string specifying the axes order. + */ +function setQuaternionFromProperEuler( q, a, b, c, order ) { + + const cos = Math.cos; + const sin = Math.sin; + + const c2 = cos( b / 2 ); + const s2 = sin( b / 2 ); + + const c13 = cos( ( a + c ) / 2 ); + const s13 = sin( ( a + c ) / 2 ); + + const c1_3 = cos( ( a - c ) / 2 ); + const s1_3 = sin( ( a - c ) / 2 ); + + const c3_1 = cos( ( c - a ) / 2 ); + const s3_1 = sin( ( c - a ) / 2 ); + + switch ( order ) { + + case 'XYX': + q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 ); + break; + + case 'YZY': + q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 ); + break; + + case 'ZXZ': + q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 ); + break; + + case 'XZX': + q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 ); + break; + + case 'YXY': + q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 ); + break; + + case 'ZYZ': + q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 ); + break; + + default: + warn( 'MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order ); + + } + +} + +/** + * Denormalizes the given value according to the given typed array. + * + * @param {number} value - The value to denormalize. + * @param {TypedArray} array - The typed array that defines the data type of the value. + * @return {number} The denormalize (float) value in the range `[0,1]`. + */ +function denormalize( value, array ) { + + switch ( array.constructor ) { + + case Float32Array: + + return value; + + case Uint32Array: + + return value / 4294967295.0; + + case Uint16Array: + + return value / 65535.0; + + case Uint8Array: + case Uint8ClampedArray: + + return value / 255.0; + + case Int32Array: + + return Math.max( value / 2147483647.0, -1 ); + + case Int16Array: + + return Math.max( value / 32767.0, -1 ); + + case Int8Array: + + return Math.max( value / 127.0, -1 ); + + default: + + throw new Error( 'THREE.MathUtils: Invalid component type.' ); + + } + +} + +/** + * Normalizes the given value according to the given typed array. + * + * @param {number} value - The float value in the range `[0,1]` to normalize. + * @param {TypedArray} array - The typed array that defines the data type of the value. + * @return {number} The normalize value. + */ +function normalize( value, array ) { + + switch ( array.constructor ) { + + case Float32Array: + + return value; + + case Uint32Array: + + return Math.round( value * 4294967295.0 ); + + case Uint16Array: + + return Math.round( value * 65535.0 ); + + case Uint8Array: + case Uint8ClampedArray: + + return Math.round( value * 255.0 ); + + case Int32Array: + + return Math.round( value * 2147483647.0 ); + + case Int16Array: + + return Math.round( value * 32767.0 ); + + case Int8Array: + + return Math.round( value * 127.0 ); + + default: + + throw new Error( 'THREE.MathUtils: Invalid component type.' ); + + } + +} + +/** + * @class + * @classdesc A collection of math utility functions. + * @hideconstructor + */ +const MathUtils = { + DEG2RAD: DEG2RAD, + RAD2DEG: RAD2DEG, + /** + * Generate a [UUID](https://en.wikipedia.org/wiki/Universally_unique_identifier) + * (universally unique identifier). + * + * @static + * @method + * @return {string} The UUID. + */ + generateUUID: generateUUID, + /** + * Clamps the given value between min and max. + * + * @static + * @method + * @param {number} value - The value to clamp. + * @param {number} min - The min value. + * @param {number} max - The max value. + * @return {number} The clamped value. + */ + clamp: clamp, + /** + * Computes the Euclidean modulo of the given parameters that + * is `( ( n % m ) + m ) % m`. + * + * @static + * @method + * @param {number} n - The first parameter. + * @param {number} m - The second parameter. + * @return {number} The Euclidean modulo. + */ + euclideanModulo: euclideanModulo, + /** + * Performs a linear mapping from range `` to range `` + * for the given value. + * + * @static + * @method + * @param {number} x - The value to be mapped. + * @param {number} a1 - Minimum value for range A. + * @param {number} a2 - Maximum value for range A. + * @param {number} b1 - Minimum value for range B. + * @param {number} b2 - Maximum value for range B. + * @return {number} The mapped value. + */ + mapLinear: mapLinear, + /** + * Returns the percentage in the closed interval `[0, 1]` of the given value + * between the start and end point. + * + * @static + * @method + * @param {number} x - The start point + * @param {number} y - The end point. + * @param {number} value - A value between start and end. + * @return {number} The interpolation factor. + */ + inverseLerp: inverseLerp, + /** + * Returns a value linearly interpolated from two known points based on the given interval - + * `t = 0` will return `x` and `t = 1` will return `y`. + * + * @static + * @method + * @param {number} x - The start point + * @param {number} y - The end point. + * @param {number} t - The interpolation factor in the closed interval `[0, 1]`. + * @return {number} The interpolated value. + */ + lerp: lerp, + /** + * Smoothly interpolate a number from `x` to `y` in a spring-like manner using a delta + * time to maintain frame rate independent movement. For details, see + * [Frame rate independent damping using lerp](http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/). + * + * @static + * @method + * @param {number} x - The current point. + * @param {number} y - The target point. + * @param {number} lambda - A higher lambda value will make the movement more sudden, + * and a lower value will make the movement more gradual. + * @param {number} dt - Delta time in seconds. + * @return {number} The interpolated value. + */ + damp: damp, + /** + * Returns a value that alternates between `0` and the given `length` parameter. + * + * @static + * @method + * @param {number} x - The value to pingpong. + * @param {number} [length=1] - The positive value the function will pingpong to. + * @return {number} The alternated value. + */ + pingpong: pingpong, + /** + * Returns a value in the range `[0,1]` that represents the percentage that `x` has + * moved between `min` and `max`, but smoothed or slowed down the closer `x` is to + * the `min` and `max`. + * + * See [Smoothstep](http://en.wikipedia.org/wiki/Smoothstep) for more details. + * + * @static + * @method + * @param {number} x - The value to evaluate based on its position between min and max. + * @param {number} min - The min value. Any x value below min will be `0`. + * @param {number} max - The max value. Any x value above max will be `1`. + * @return {number} The alternated value. + */ + smoothstep: smoothstep, + /** + * A [variation on smoothstep](https://en.wikipedia.org/wiki/Smoothstep#Variations) + * that has zero 1st and 2nd order derivatives at x=0 and x=1. + * + * @static + * @method + * @param {number} x - The value to evaluate based on its position between min and max. + * @param {number} min - The min value. Any x value below min will be `0`. + * @param {number} max - The max value. Any x value above max will be `1`. + * @return {number} The alternated value. + */ + smootherstep: smootherstep, + /** + * Returns a random integer from `` interval. + * + * @static + * @method + * @param {number} low - The lower value boundary. + * @param {number} high - The upper value boundary + * @return {number} A random integer. + */ + randInt: randInt, + /** + * Returns a random float from `` interval. + * + * @static + * @method + * @param {number} low - The lower value boundary. + * @param {number} high - The upper value boundary + * @return {number} A random float. + */ + randFloat: randFloat, + /** + * Returns a random integer from `<-range/2, range/2>` interval. + * + * @static + * @method + * @param {number} range - Defines the value range. + * @return {number} A random float. + */ + randFloatSpread: randFloatSpread, + /** + * Returns a deterministic pseudo-random float in the interval `[0, 1]`. + * + * @static + * @method + * @param {number} [s] - The integer seed. + * @return {number} A random float. + */ + seededRandom: seededRandom, + /** + * Converts degrees to radians. + * + * @static + * @method + * @param {number} degrees - A value in degrees. + * @return {number} The converted value in radians. + */ + degToRad: degToRad, + /** + * Converts radians to degrees. + * + * @static + * @method + * @param {number} radians - A value in radians. + * @return {number} The converted value in degrees. + */ + radToDeg: radToDeg, + /** + * Returns `true` if the given number is a power of two. + * + * @static + * @method + * @param {number} value - The value to check. + * @return {boolean} Whether the given number is a power of two or not. + */ + isPowerOfTwo: isPowerOfTwo, + /** + * Returns the smallest power of two that is greater than or equal to the given number. + * + * @static + * @method + * @param {number} value - The value to find a POT for. + * @return {number} The smallest power of two that is greater than or equal to the given number. + */ + ceilPowerOfTwo: ceilPowerOfTwo, + /** + * Returns the largest power of two that is less than or equal to the given number. + * + * @static + * @method + * @param {number} value - The value to find a POT for. + * @return {number} The largest power of two that is less than or equal to the given number. + */ + floorPowerOfTwo: floorPowerOfTwo, + /** + * Sets the given quaternion from the [Intrinsic Proper Euler Angles](https://en.wikipedia.org/wiki/Euler_angles) + * defined by the given angles and order. + * + * Rotations are applied to the axes in the order specified by order: + * rotation by angle `a` is applied first, then by angle `b`, then by angle `c`. + * + * @static + * @method + * @param {Quaternion} q - The quaternion to set. + * @param {number} a - The rotation applied to the first axis, in radians. + * @param {number} b - The rotation applied to the second axis, in radians. + * @param {number} c - The rotation applied to the third axis, in radians. + * @param {('XYX'|'XZX'|'YXY'|'YZY'|'ZXZ'|'ZYZ')} order - A string specifying the axes order. + */ + setQuaternionFromProperEuler: setQuaternionFromProperEuler, + /** + * Normalizes the given value according to the given typed array. + * + * @static + * @method + * @param {number} value - The float value in the range `[0,1]` to normalize. + * @param {TypedArray} array - The typed array that defines the data type of the value. + * @return {number} The normalize value. + */ + normalize: normalize, + /** + * Denormalizes the given value according to the given typed array. + * + * @static + * @method + * @param {number} value - The value to denormalize. + * @param {TypedArray} array - The typed array that defines the data type of the value. + * @return {number} The denormalize (float) value in the range `[0,1]`. + */ + denormalize: denormalize +}; + +/** + * Class representing a 2D vector. A 2D vector is an ordered pair of numbers + * (labeled x and y), which can be used to represent a number of things, such as: + * + * - A point in 2D space (i.e. a position on a plane). + * - A direction and length across a plane. In three.js the length will + * always be the Euclidean distance(straight-line distance) from `(0, 0)` to `(x, y)` + * and the direction is also measured from `(0, 0)` towards `(x, y)`. + * - Any arbitrary ordered pair of numbers. + * + * There are other things a 2D vector can be used to represent, such as + * momentum vectors, complex numbers and so on, however these are the most + * common uses in three.js. + * + * Iterating through a vector instance will yield its components `(x, y)` in + * the corresponding order. + * ```js + * const a = new THREE.Vector2( 0, 1 ); + * + * //no arguments; will be initialised to (0, 0) + * const b = new THREE.Vector2( ); + * + * const d = a.distanceTo( b ); + * ``` + */ +class Vector2 { + + static { + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + Vector2.prototype.isVector2 = true; + + } + + /** + * Constructs a new 2D vector. + * + * @param {number} [x=0] - The x value of this vector. + * @param {number} [y=0] - The y value of this vector. + */ + constructor( x = 0, y = 0 ) { + + /** + * The x value of this vector. + * + * @type {number} + */ + this.x = x; + + /** + * The y value of this vector. + * + * @type {number} + */ + this.y = y; + + } + + /** + * Alias for {@link Vector2#x}. + * + * @type {number} + */ + get width() { + + return this.x; + + } + + set width( value ) { + + this.x = value; + + } + + /** + * Alias for {@link Vector2#y}. + * + * @type {number} + */ + get height() { + + return this.y; + + } + + set height( value ) { + + this.y = value; + + } + + /** + * Sets the vector components. + * + * @param {number} x - The value of the x component. + * @param {number} y - The value of the y component. + * @return {Vector2} A reference to this vector. + */ + set( x, y ) { + + this.x = x; + this.y = y; + + return this; + + } + + /** + * Sets the vector components to the same value. + * + * @param {number} scalar - The value to set for all vector components. + * @return {Vector2} A reference to this vector. + */ + setScalar( scalar ) { + + this.x = scalar; + this.y = scalar; + + return this; + + } + + /** + * Sets the vector's x component to the given value + * + * @param {number} x - The value to set. + * @return {Vector2} A reference to this vector. + */ + setX( x ) { + + this.x = x; + + return this; + + } + + /** + * Sets the vector's y component to the given value + * + * @param {number} y - The value to set. + * @return {Vector2} A reference to this vector. + */ + setY( y ) { + + this.y = y; + + return this; + + } + + /** + * Allows to set a vector component with an index. + * + * @param {number} index - The component index. `0` equals to x, `1` equals to y. + * @param {number} value - The value to set. + * @return {Vector2} A reference to this vector. + */ + setComponent( index, value ) { + + switch ( index ) { + + case 0: this.x = value; break; + case 1: this.y = value; break; + default: throw new Error( 'THREE.Vector2: index is out of range: ' + index ); + + } + + return this; + + } + + /** + * Returns the value of the vector component which matches the given index. + * + * @param {number} index - The component index. `0` equals to x, `1` equals to y. + * @return {number} A vector component value. + */ + getComponent( index ) { + + switch ( index ) { + + case 0: return this.x; + case 1: return this.y; + default: throw new Error( 'THREE.Vector2: index is out of range: ' + index ); + + } + + } + + /** + * Returns a new vector with copied values from this instance. + * + * @return {Vector2} A clone of this instance. + */ + clone() { + + return new this.constructor( this.x, this.y ); + + } + + /** + * Copies the values of the given vector to this instance. + * + * @param {Vector2} v - The vector to copy. + * @return {Vector2} A reference to this vector. + */ + copy( v ) { + + this.x = v.x; + this.y = v.y; + + return this; + + } + + /** + * Adds the given vector to this instance. + * + * @param {Vector2} v - The vector to add. + * @return {Vector2} A reference to this vector. + */ + add( v ) { + + this.x += v.x; + this.y += v.y; + + return this; + + } + + /** + * Adds the given scalar value to all components of this instance. + * + * @param {number} s - The scalar to add. + * @return {Vector2} A reference to this vector. + */ + addScalar( s ) { + + this.x += s; + this.y += s; + + return this; + + } + + /** + * Adds the given vectors and stores the result in this instance. + * + * @param {Vector2} a - The first vector. + * @param {Vector2} b - The second vector. + * @return {Vector2} A reference to this vector. + */ + addVectors( a, b ) { + + this.x = a.x + b.x; + this.y = a.y + b.y; + + return this; + + } + + /** + * Adds the given vector scaled by the given factor to this instance. + * + * @param {Vector2} v - The vector. + * @param {number} s - The factor that scales `v`. + * @return {Vector2} A reference to this vector. + */ + addScaledVector( v, s ) { + + this.x += v.x * s; + this.y += v.y * s; + + return this; + + } + + /** + * Subtracts the given vector from this instance. + * + * @param {Vector2} v - The vector to subtract. + * @return {Vector2} A reference to this vector. + */ + sub( v ) { + + this.x -= v.x; + this.y -= v.y; + + return this; + + } + + /** + * Subtracts the given scalar value from all components of this instance. + * + * @param {number} s - The scalar to subtract. + * @return {Vector2} A reference to this vector. + */ + subScalar( s ) { + + this.x -= s; + this.y -= s; + + return this; + + } + + /** + * Subtracts the given vectors and stores the result in this instance. + * + * @param {Vector2} a - The first vector. + * @param {Vector2} b - The second vector. + * @return {Vector2} A reference to this vector. + */ + subVectors( a, b ) { + + this.x = a.x - b.x; + this.y = a.y - b.y; + + return this; + + } + + /** + * Multiplies the given vector with this instance. + * + * @param {Vector2} v - The vector to multiply. + * @return {Vector2} A reference to this vector. + */ + multiply( v ) { + + this.x *= v.x; + this.y *= v.y; + + return this; + + } + + /** + * Multiplies the given scalar value with all components of this instance. + * + * @param {number} scalar - The scalar to multiply. + * @return {Vector2} A reference to this vector. + */ + multiplyScalar( scalar ) { + + this.x *= scalar; + this.y *= scalar; + + return this; + + } + + /** + * Divides this instance by the given vector. + * + * @param {Vector2} v - The vector to divide. + * @return {Vector2} A reference to this vector. + */ + divide( v ) { + + this.x /= v.x; + this.y /= v.y; + + return this; + + } + + /** + * Divides this vector by the given scalar. + * + * @param {number} scalar - The scalar to divide. + * @return {Vector2} A reference to this vector. + */ + divideScalar( scalar ) { + + return this.multiplyScalar( 1 / scalar ); + + } + + /** + * Multiplies this vector (with an implicit 1 as the 3rd component) by + * the given 3x3 matrix. + * + * @param {Matrix3} m - The matrix to apply. + * @return {Vector2} A reference to this vector. + */ + applyMatrix3( m ) { + + const x = this.x, y = this.y; + const e = m.elements; + + this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ]; + this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ]; + + return this; + + } + + /** + * If this vector's x or y value is greater than the given vector's x or y + * value, replace that value with the corresponding min value. + * + * @param {Vector2} v - The vector. + * @return {Vector2} A reference to this vector. + */ + min( v ) { + + this.x = Math.min( this.x, v.x ); + this.y = Math.min( this.y, v.y ); + + return this; + + } + + /** + * If this vector's x or y value is less than the given vector's x or y + * value, replace that value with the corresponding max value. + * + * @param {Vector2} v - The vector. + * @return {Vector2} A reference to this vector. + */ + max( v ) { + + this.x = Math.max( this.x, v.x ); + this.y = Math.max( this.y, v.y ); + + return this; + + } + + /** + * If this vector's x or y value is greater than the max vector's x or y + * value, it is replaced by the corresponding value. + * If this vector's x or y value is less than the min vector's x or y value, + * it is replaced by the corresponding value. + * + * @param {Vector2} min - The minimum x and y values. + * @param {Vector2} max - The maximum x and y values in the desired range. + * @return {Vector2} A reference to this vector. + */ + clamp( min, max ) { + + // assumes min < max, componentwise + + this.x = clamp( this.x, min.x, max.x ); + this.y = clamp( this.y, min.y, max.y ); + + return this; + + } + + /** + * If this vector's x or y values are greater than the max value, they are + * replaced by the max value. + * If this vector's x or y values are less than the min value, they are + * replaced by the min value. + * + * @param {number} minVal - The minimum value the components will be clamped to. + * @param {number} maxVal - The maximum value the components will be clamped to. + * @return {Vector2} A reference to this vector. + */ + clampScalar( minVal, maxVal ) { + + this.x = clamp( this.x, minVal, maxVal ); + this.y = clamp( this.y, minVal, maxVal ); + + return this; + + } + + /** + * If this vector's length is greater than the max value, it is replaced by + * the max value. + * If this vector's length is less than the min value, it is replaced by the + * min value. + * + * @param {number} min - The minimum value the vector length will be clamped to. + * @param {number} max - The maximum value the vector length will be clamped to. + * @return {Vector2} A reference to this vector. + */ + clampLength( min, max ) { + + const length = this.length(); + + return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) ); + + } + + /** + * The components of this vector are rounded down to the nearest integer value. + * + * @return {Vector2} A reference to this vector. + */ + floor() { + + this.x = Math.floor( this.x ); + this.y = Math.floor( this.y ); + + return this; + + } + + /** + * The components of this vector are rounded up to the nearest integer value. + * + * @return {Vector2} A reference to this vector. + */ + ceil() { + + this.x = Math.ceil( this.x ); + this.y = Math.ceil( this.y ); + + return this; + + } + + /** + * The components of this vector are rounded to the nearest integer value + * + * @return {Vector2} A reference to this vector. + */ + round() { + + this.x = Math.round( this.x ); + this.y = Math.round( this.y ); + + return this; + + } + + /** + * The components of this vector are rounded towards zero (up if negative, + * down if positive) to an integer value. + * + * @return {Vector2} A reference to this vector. + */ + roundToZero() { + + this.x = Math.trunc( this.x ); + this.y = Math.trunc( this.y ); + + return this; + + } + + /** + * Inverts this vector - i.e. sets x = -x and y = -y. + * + * @return {Vector2} A reference to this vector. + */ + negate() { + + this.x = - this.x; + this.y = - this.y; + + return this; + + } + + /** + * Calculates the dot product of the given vector with this instance. + * + * @param {Vector2} v - The vector to compute the dot product with. + * @return {number} The result of the dot product. + */ + dot( v ) { + + return this.x * v.x + this.y * v.y; + + } + + /** + * Calculates the cross product of the given vector with this instance. + * + * @param {Vector2} v - The vector to compute the cross product with. + * @return {number} The result of the cross product. + */ + cross( v ) { + + return this.x * v.y - this.y * v.x; + + } + + /** + * Computes the square of the Euclidean length (straight-line length) from + * (0, 0) to (x, y). If you are comparing the lengths of vectors, you should + * compare the length squared instead as it is slightly more efficient to calculate. + * + * @return {number} The square length of this vector. + */ + lengthSq() { + + return this.x * this.x + this.y * this.y; + + } + + /** + * Computes the Euclidean length (straight-line length) from (0, 0) to (x, y). + * + * @return {number} The length of this vector. + */ + length() { + + return Math.sqrt( this.x * this.x + this.y * this.y ); + + } + + /** + * Computes the Manhattan length of this vector. + * + * @return {number} The length of this vector. + */ + manhattanLength() { + + return Math.abs( this.x ) + Math.abs( this.y ); + + } + + /** + * Converts this vector to a unit vector - that is, sets it equal to a vector + * with the same direction as this one, but with a vector length of `1`. + * + * @return {Vector2} A reference to this vector. + */ + normalize() { + + return this.divideScalar( this.length() || 1 ); + + } + + /** + * Computes the angle in radians of this vector with respect to the positive x-axis. + * + * @return {number} The angle in radians. + */ + angle() { + + const angle = Math.atan2( - this.y, - this.x ) + Math.PI; + + return angle; + + } + + /** + * Returns the angle between the given vector and this instance in radians. + * + * @param {Vector2} v - The vector to compute the angle with. + * @return {number} The angle in radians. + */ + angleTo( v ) { + + const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() ); + + if ( denominator === 0 ) return Math.PI / 2; + + const theta = this.dot( v ) / denominator; + + // clamp, to handle numerical problems + + return Math.acos( clamp( theta, -1, 1 ) ); + + } + + /** + * Computes the distance from the given vector to this instance. + * + * @param {Vector2} v - The vector to compute the distance to. + * @return {number} The distance. + */ + distanceTo( v ) { + + return Math.sqrt( this.distanceToSquared( v ) ); + + } + + /** + * Computes the squared distance from the given vector to this instance. + * If you are just comparing the distance with another distance, you should compare + * the distance squared instead as it is slightly more efficient to calculate. + * + * @param {Vector2} v - The vector to compute the squared distance to. + * @return {number} The squared distance. + */ + distanceToSquared( v ) { + + const dx = this.x - v.x, dy = this.y - v.y; + return dx * dx + dy * dy; + + } + + /** + * Computes the Manhattan distance from the given vector to this instance. + * + * @param {Vector2} v - The vector to compute the Manhattan distance to. + * @return {number} The Manhattan distance. + */ + manhattanDistanceTo( v ) { + + return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ); + + } + + /** + * Sets this vector to a vector with the same direction as this one, but + * with the specified length. + * + * @param {number} length - The new length of this vector. + * @return {Vector2} A reference to this vector. + */ + setLength( length ) { + + return this.normalize().multiplyScalar( length ); + + } + + /** + * Linearly interpolates between the given vector and this instance, where + * alpha is the percent distance along the line - alpha = 0 will be this + * vector, and alpha = 1 will be the given one. + * + * @param {Vector2} v - The vector to interpolate towards. + * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`. + * @return {Vector2} A reference to this vector. + */ + lerp( v, alpha ) { + + this.x += ( v.x - this.x ) * alpha; + this.y += ( v.y - this.y ) * alpha; + + return this; + + } + + /** + * Linearly interpolates between the given vectors, where alpha is the percent + * distance along the line - alpha = 0 will be first vector, and alpha = 1 will + * be the second one. The result is stored in this instance. + * + * @param {Vector2} v1 - The first vector. + * @param {Vector2} v2 - The second vector. + * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`. + * @return {Vector2} A reference to this vector. + */ + lerpVectors( v1, v2, alpha ) { + + this.x = v1.x + ( v2.x - v1.x ) * alpha; + this.y = v1.y + ( v2.y - v1.y ) * alpha; + + return this; + + } + + /** + * Returns `true` if this vector is equal with the given one. + * + * @param {Vector2} v - The vector to test for equality. + * @return {boolean} Whether this vector is equal with the given one. + */ + equals( v ) { + + return ( ( v.x === this.x ) && ( v.y === this.y ) ); + + } + + /** + * Sets this vector's x value to be `array[ offset ]` and y + * value to be `array[ offset + 1 ]`. + * + * @param {Array} array - An array holding the vector component values. + * @param {number} [offset=0] - The offset into the array. + * @return {Vector2} A reference to this vector. + */ + fromArray( array, offset = 0 ) { + + this.x = array[ offset ]; + this.y = array[ offset + 1 ]; + + return this; + + } + + /** + * Writes the components of this vector to the given array. If no array is provided, + * the method returns a new instance. + * + * @param {Array} [array=[]] - The target array holding the vector components. + * @param {number} [offset=0] - Index of the first element in the array. + * @return {Array} The vector components. + */ + toArray( array = [], offset = 0 ) { + + array[ offset ] = this.x; + array[ offset + 1 ] = this.y; + + return array; + + } + + /** + * Sets the components of this vector from the given buffer attribute. + * + * @param {BufferAttribute} attribute - The buffer attribute holding vector data. + * @param {number} index - The index into the attribute. + * @return {Vector2} A reference to this vector. + */ + fromBufferAttribute( attribute, index ) { + + this.x = attribute.getX( index ); + this.y = attribute.getY( index ); + + return this; + + } + + /** + * Rotates this vector around the given center by the given angle. + * + * @param {Vector2} center - The point around which to rotate. + * @param {number} angle - The angle to rotate, in radians. + * @return {Vector2} A reference to this vector. + */ + rotateAround( center, angle ) { + + const c = Math.cos( angle ), s = Math.sin( angle ); + + const x = this.x - center.x; + const y = this.y - center.y; + + this.x = x * c - y * s + center.x; + this.y = x * s + y * c + center.y; + + return this; + + } + + /** + * Sets each component of this vector to a pseudo-random value between `0` and + * `1`, excluding `1`. + * + * @return {Vector2} A reference to this vector. + */ + random() { + + this.x = Math.random(); + this.y = Math.random(); + + return this; + + } + + *[ Symbol.iterator ]() { + + yield this.x; + yield this.y; + + } + +} + +/** + * Class for representing a Quaternion. Quaternions are used in three.js to represent rotations. + * + * Iterating through a vector instance will yield its components `(x, y, z, w)` in + * the corresponding order. + * + * Note that three.js expects Quaternions to be normalized. + * ```js + * const quaternion = new THREE.Quaternion(); + * quaternion.setFromAxisAngle( new THREE.Vector3( 0, 1, 0 ), Math.PI / 2 ); + * + * const vector = new THREE.Vector3( 1, 0, 0 ); + * vector.applyQuaternion( quaternion ); + * ``` + */ +class Quaternion { + + /** + * Constructs a new quaternion. + * + * @param {number} [x=0] - The x value of this quaternion. + * @param {number} [y=0] - The y value of this quaternion. + * @param {number} [z=0] - The z value of this quaternion. + * @param {number} [w=1] - The w value of this quaternion. + */ + constructor( x = 0, y = 0, z = 0, w = 1 ) { + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isQuaternion = true; + + this._x = x; + this._y = y; + this._z = z; + this._w = w; + + } + + /** + * Interpolates between two quaternions via SLERP. This implementation assumes the + * quaternion data are managed in flat arrays. + * + * @param {Array} dst - The destination array. + * @param {number} dstOffset - An offset into the destination array. + * @param {Array} src0 - The source array of the first quaternion. + * @param {number} srcOffset0 - An offset into the first source array. + * @param {Array} src1 - The source array of the second quaternion. + * @param {number} srcOffset1 - An offset into the second source array. + * @param {number} t - The interpolation factor. A value in the range `[0,1]` will interpolate. A value outside the range `[0,1]` will extrapolate. + * @see {@link Quaternion#slerp} + */ + static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) { + + let x0 = src0[ srcOffset0 + 0 ], + y0 = src0[ srcOffset0 + 1 ], + z0 = src0[ srcOffset0 + 2 ], + w0 = src0[ srcOffset0 + 3 ]; + + let x1 = src1[ srcOffset1 + 0 ], + y1 = src1[ srcOffset1 + 1 ], + z1 = src1[ srcOffset1 + 2 ], + w1 = src1[ srcOffset1 + 3 ]; + + if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) { + + let dot = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1; + + if ( dot < 0 ) { + + x1 = - x1; + y1 = - y1; + z1 = - z1; + w1 = - w1; + + dot = - dot; + + } + + let s = 1 - t; + + if ( dot < 0.9995 ) { + + // slerp + + const theta = Math.acos( dot ); + const sin = Math.sin( theta ); + + s = Math.sin( s * theta ) / sin; + t = Math.sin( t * theta ) / sin; + + x0 = x0 * s + x1 * t; + y0 = y0 * s + y1 * t; + z0 = z0 * s + z1 * t; + w0 = w0 * s + w1 * t; + + } else { + + // for small angles, lerp then normalize + + x0 = x0 * s + x1 * t; + y0 = y0 * s + y1 * t; + z0 = z0 * s + z1 * t; + w0 = w0 * s + w1 * t; + + const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 ); + + x0 *= f; + y0 *= f; + z0 *= f; + w0 *= f; + + } + + } + + dst[ dstOffset ] = x0; + dst[ dstOffset + 1 ] = y0; + dst[ dstOffset + 2 ] = z0; + dst[ dstOffset + 3 ] = w0; + + } + + /** + * Multiplies two quaternions. This implementation assumes the quaternion data are managed + * in flat arrays. + * + * @param {Array} dst - The destination array. + * @param {number} dstOffset - An offset into the destination array. + * @param {Array} src0 - The source array of the first quaternion. + * @param {number} srcOffset0 - An offset into the first source array. + * @param {Array} src1 - The source array of the second quaternion. + * @param {number} srcOffset1 - An offset into the second source array. + * @return {Array} The destination array. + * @see {@link Quaternion#multiplyQuaternions}. + */ + static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) { + + const x0 = src0[ srcOffset0 ]; + const y0 = src0[ srcOffset0 + 1 ]; + const z0 = src0[ srcOffset0 + 2 ]; + const w0 = src0[ srcOffset0 + 3 ]; + + const x1 = src1[ srcOffset1 ]; + const y1 = src1[ srcOffset1 + 1 ]; + const z1 = src1[ srcOffset1 + 2 ]; + const w1 = src1[ srcOffset1 + 3 ]; + + dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1; + dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1; + dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1; + dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1; + + return dst; + + } + + /** + * The x value of this quaternion. + * + * @type {number} + * @default 0 + */ + get x() { + + return this._x; + + } + + set x( value ) { + + this._x = value; + this._onChangeCallback(); + + } + + /** + * The y value of this quaternion. + * + * @type {number} + * @default 0 + */ + get y() { + + return this._y; + + } + + set y( value ) { + + this._y = value; + this._onChangeCallback(); + + } + + /** + * The z value of this quaternion. + * + * @type {number} + * @default 0 + */ + get z() { + + return this._z; + + } + + set z( value ) { + + this._z = value; + this._onChangeCallback(); + + } + + /** + * The w value of this quaternion. + * + * @type {number} + * @default 1 + */ + get w() { + + return this._w; + + } + + set w( value ) { + + this._w = value; + this._onChangeCallback(); + + } + + /** + * Sets the quaternion components. + * + * @param {number} x - The x value of this quaternion. + * @param {number} y - The y value of this quaternion. + * @param {number} z - The z value of this quaternion. + * @param {number} w - The w value of this quaternion. + * @return {Quaternion} A reference to this quaternion. + */ + set( x, y, z, w ) { + + this._x = x; + this._y = y; + this._z = z; + this._w = w; + + this._onChangeCallback(); + + return this; + + } + + /** + * Returns a new quaternion with copied values from this instance. + * + * @return {Quaternion} A clone of this instance. + */ + clone() { + + return new this.constructor( this._x, this._y, this._z, this._w ); + + } + + /** + * Copies the values of the given quaternion to this instance. + * + * @param {Quaternion} quaternion - The quaternion to copy. + * @return {Quaternion} A reference to this quaternion. + */ + copy( quaternion ) { + + this._x = quaternion.x; + this._y = quaternion.y; + this._z = quaternion.z; + this._w = quaternion.w; + + this._onChangeCallback(); + + return this; + + } + + /** + * Sets this quaternion from the rotation specified by the given + * Euler angles. + * + * @param {Euler} euler - The Euler angles. + * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not. + * @return {Quaternion} A reference to this quaternion. + */ + setFromEuler( euler, update = true ) { + + const x = euler._x, y = euler._y, z = euler._z, order = euler._order; + + const cos = Math.cos; + const sin = Math.sin; + + const c1 = cos( x / 2 ); + const c2 = cos( y / 2 ); + const c3 = cos( z / 2 ); + + const s1 = sin( x / 2 ); + const s2 = sin( y / 2 ); + const s3 = sin( z / 2 ); + + switch ( order ) { + + case 'XYZ': + this._x = s1 * c2 * c3 + c1 * s2 * s3; + this._y = c1 * s2 * c3 - s1 * c2 * s3; + this._z = c1 * c2 * s3 + s1 * s2 * c3; + this._w = c1 * c2 * c3 - s1 * s2 * s3; + break; + + case 'YXZ': + this._x = s1 * c2 * c3 + c1 * s2 * s3; + this._y = c1 * s2 * c3 - s1 * c2 * s3; + this._z = c1 * c2 * s3 - s1 * s2 * c3; + this._w = c1 * c2 * c3 + s1 * s2 * s3; + break; + + case 'ZXY': + this._x = s1 * c2 * c3 - c1 * s2 * s3; + this._y = c1 * s2 * c3 + s1 * c2 * s3; + this._z = c1 * c2 * s3 + s1 * s2 * c3; + this._w = c1 * c2 * c3 - s1 * s2 * s3; + break; + + case 'ZYX': + this._x = s1 * c2 * c3 - c1 * s2 * s3; + this._y = c1 * s2 * c3 + s1 * c2 * s3; + this._z = c1 * c2 * s3 - s1 * s2 * c3; + this._w = c1 * c2 * c3 + s1 * s2 * s3; + break; + + case 'YZX': + this._x = s1 * c2 * c3 + c1 * s2 * s3; + this._y = c1 * s2 * c3 + s1 * c2 * s3; + this._z = c1 * c2 * s3 - s1 * s2 * c3; + this._w = c1 * c2 * c3 - s1 * s2 * s3; + break; + + case 'XZY': + this._x = s1 * c2 * c3 - c1 * s2 * s3; + this._y = c1 * s2 * c3 - s1 * c2 * s3; + this._z = c1 * c2 * s3 + s1 * s2 * c3; + this._w = c1 * c2 * c3 + s1 * s2 * s3; + break; + + default: + warn( 'Quaternion: .setFromEuler() encountered an unknown order: ' + order ); + + } + + if ( update === true ) this._onChangeCallback(); + + return this; + + } + + /** + * Sets this quaternion from the given axis and angle. + * + * @param {Vector3} axis - The normalized axis. + * @param {number} angle - The angle in radians. + * @return {Quaternion} A reference to this quaternion. + */ + setFromAxisAngle( axis, angle ) { + + const halfAngle = angle / 2, s = Math.sin( halfAngle ); + + this._x = axis.x * s; + this._y = axis.y * s; + this._z = axis.z * s; + this._w = Math.cos( halfAngle ); + + this._onChangeCallback(); + + return this; + + } + + /** + * Sets this quaternion from the given rotation matrix. + * + * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled). + * @return {Quaternion} A reference to this quaternion. + */ + setFromRotationMatrix( m ) { + + // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) + + const te = m.elements, + + m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ], + m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ], + m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ], + + trace = m11 + m22 + m33; + + if ( trace > 0 ) { + + const s = 0.5 / Math.sqrt( trace + 1.0 ); + + this._w = 0.25 / s; + this._x = ( m32 - m23 ) * s; + this._y = ( m13 - m31 ) * s; + this._z = ( m21 - m12 ) * s; + + } else if ( m11 > m22 && m11 > m33 ) { + + const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 ); + + this._w = ( m32 - m23 ) / s; + this._x = 0.25 * s; + this._y = ( m12 + m21 ) / s; + this._z = ( m13 + m31 ) / s; + + } else if ( m22 > m33 ) { + + const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 ); + + this._w = ( m13 - m31 ) / s; + this._x = ( m12 + m21 ) / s; + this._y = 0.25 * s; + this._z = ( m23 + m32 ) / s; + + } else { + + const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 ); + + this._w = ( m21 - m12 ) / s; + this._x = ( m13 + m31 ) / s; + this._y = ( m23 + m32 ) / s; + this._z = 0.25 * s; + + } + + this._onChangeCallback(); + + return this; + + } + + /** + * Sets this quaternion to the rotation required to rotate the direction vector + * `vFrom` to the direction vector `vTo`. + * + * @param {Vector3} vFrom - The first (normalized) direction vector. + * @param {Vector3} vTo - The second (normalized) direction vector. + * @return {Quaternion} A reference to this quaternion. + */ + setFromUnitVectors( vFrom, vTo ) { + + // assumes direction vectors vFrom and vTo are normalized + + let r = vFrom.dot( vTo ) + 1; + + if ( r < 1e-8 ) { // the epsilon value has been discussed in #31286 + + // vFrom and vTo point in opposite directions + + r = 0; + + if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) { + + this._x = - vFrom.y; + this._y = vFrom.x; + this._z = 0; + this._w = r; + + } else { + + this._x = 0; + this._y = - vFrom.z; + this._z = vFrom.y; + this._w = r; + + } + + } else { + + // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3 + + this._x = vFrom.y * vTo.z - vFrom.z * vTo.y; + this._y = vFrom.z * vTo.x - vFrom.x * vTo.z; + this._z = vFrom.x * vTo.y - vFrom.y * vTo.x; + this._w = r; + + } + + return this.normalize(); + + } + + /** + * Returns the angle between this quaternion and the given one in radians. + * + * @param {Quaternion} q - The quaternion to compute the angle with. + * @return {number} The angle in radians. + */ + angleTo( q ) { + + return 2 * Math.acos( Math.abs( clamp( this.dot( q ), -1, 1 ) ) ); + + } + + /** + * Rotates this quaternion by a given angular step to the given quaternion. + * The method ensures that the final quaternion will not overshoot `q`. + * + * @param {Quaternion} q - The target quaternion. + * @param {number} step - The angular step in radians. + * @return {Quaternion} A reference to this quaternion. + */ + rotateTowards( q, step ) { + + const angle = this.angleTo( q ); + + if ( angle === 0 ) return this; + + const t = Math.min( 1, step / angle ); + + this.slerp( q, t ); + + return this; + + } + + /** + * Sets this quaternion to the identity quaternion; that is, to the + * quaternion that represents "no rotation". + * + * @return {Quaternion} A reference to this quaternion. + */ + identity() { + + return this.set( 0, 0, 0, 1 ); + + } + + /** + * Inverts this quaternion via {@link Quaternion#conjugate}. The + * quaternion is assumed to have unit length. + * + * @return {Quaternion} A reference to this quaternion. + */ + invert() { + + return this.conjugate(); + + } + + /** + * Returns the rotational conjugate of this quaternion. The conjugate of a + * quaternion represents the same rotation in the opposite direction about + * the rotational axis. + * + * @return {Quaternion} A reference to this quaternion. + */ + conjugate() { + + this._x *= -1; + this._y *= -1; + this._z *= -1; + + this._onChangeCallback(); + + return this; + + } + + /** + * Calculates the dot product of this quaternion and the given one. + * + * @param {Quaternion} v - The quaternion to compute the dot product with. + * @return {number} The result of the dot product. + */ + dot( v ) { + + return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w; + + } + + /** + * Computes the squared Euclidean length (straight-line length) of this quaternion, + * considered as a 4 dimensional vector. This can be useful if you are comparing the + * lengths of two quaternions, as this is a slightly more efficient calculation than + * {@link Quaternion#length}. + * + * @return {number} The squared Euclidean length. + */ + lengthSq() { + + return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w; + + } + + /** + * Computes the Euclidean length (straight-line length) of this quaternion, + * considered as a 4 dimensional vector. + * + * @return {number} The Euclidean length. + */ + length() { + + return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w ); + + } + + /** + * Normalizes this quaternion - that is, calculated the quaternion that performs + * the same rotation as this one, but has a length equal to `1`. + * + * @return {Quaternion} A reference to this quaternion. + */ + normalize() { + + let l = this.length(); + + if ( l === 0 ) { + + this._x = 0; + this._y = 0; + this._z = 0; + this._w = 1; + + } else { + + l = 1 / l; + + this._x = this._x * l; + this._y = this._y * l; + this._z = this._z * l; + this._w = this._w * l; + + } + + this._onChangeCallback(); + + return this; + + } + + /** + * Multiplies this quaternion by the given one. + * + * @param {Quaternion} q - The quaternion. + * @return {Quaternion} A reference to this quaternion. + */ + multiply( q ) { + + return this.multiplyQuaternions( this, q ); + + } + + /** + * Pre-multiplies this quaternion by the given one. + * + * @param {Quaternion} q - The quaternion. + * @return {Quaternion} A reference to this quaternion. + */ + premultiply( q ) { + + return this.multiplyQuaternions( q, this ); + + } + + /** + * Multiplies the given quaternions and stores the result in this instance. + * + * @param {Quaternion} a - The first quaternion. + * @param {Quaternion} b - The second quaternion. + * @return {Quaternion} A reference to this quaternion. + */ + multiplyQuaternions( a, b ) { + + const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w; + const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w; + + this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby; + this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz; + this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx; + this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz; + + this._onChangeCallback(); + + return this; + + } + + /** + * Performs a spherical linear interpolation between this quaternion and the target quaternion. + * + * @param {Quaternion} qb - The target quaternion. + * @param {number} t - The interpolation factor. A value in the range `[0,1]` will interpolate. A value outside the range `[0,1]` will extrapolate. + * @return {Quaternion} A reference to this quaternion. + */ + slerp( qb, t ) { + + let x = qb._x, y = qb._y, z = qb._z, w = qb._w; + + let dot = this.dot( qb ); + + if ( dot < 0 ) { + + x = - x; + y = - y; + z = - z; + w = - w; + + dot = - dot; + + } + + let s = 1 - t; + + if ( dot < 0.9995 ) { + + // slerp + + const theta = Math.acos( dot ); + const sin = Math.sin( theta ); + + s = Math.sin( s * theta ) / sin; + t = Math.sin( t * theta ) / sin; + + this._x = this._x * s + x * t; + this._y = this._y * s + y * t; + this._z = this._z * s + z * t; + this._w = this._w * s + w * t; + + this._onChangeCallback(); + + } else { + + // for small angles, lerp then normalize + + this._x = this._x * s + x * t; + this._y = this._y * s + y * t; + this._z = this._z * s + z * t; + this._w = this._w * s + w * t; + + this.normalize(); // normalize calls _onChangeCallback() + + } + + return this; + + } + + /** + * Performs a spherical linear interpolation between the given quaternions + * and stores the result in this quaternion. + * + * @param {Quaternion} qa - The source quaternion. + * @param {Quaternion} qb - The target quaternion. + * @param {number} t - The interpolation factor in the closed interval `[0, 1]`. + * @return {Quaternion} A reference to this quaternion. + */ + slerpQuaternions( qa, qb, t ) { + + return this.copy( qa ).slerp( qb, t ); + + } + + /** + * Sets this quaternion to a uniformly random, normalized quaternion. + * + * @return {Quaternion} A reference to this quaternion. + */ + random() { + + // Ken Shoemake + // Uniform random rotations + // D. Kirk, editor, Graphics Gems III, pages 124-132. Academic Press, New York, 1992. + + const theta1 = 2 * Math.PI * Math.random(); + const theta2 = 2 * Math.PI * Math.random(); + + const x0 = Math.random(); + const r1 = Math.sqrt( 1 - x0 ); + const r2 = Math.sqrt( x0 ); + + return this.set( + r1 * Math.sin( theta1 ), + r1 * Math.cos( theta1 ), + r2 * Math.sin( theta2 ), + r2 * Math.cos( theta2 ), + ); + + } + + /** + * Returns `true` if this quaternion is equal with the given one. + * + * @param {Quaternion} quaternion - The quaternion to test for equality. + * @return {boolean} Whether this quaternion is equal with the given one. + */ + equals( quaternion ) { + + return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w ); + + } + + /** + * Sets this quaternion's components from the given array. + * + * @param {Array} array - An array holding the quaternion component values. + * @param {number} [offset=0] - The offset into the array. + * @return {Quaternion} A reference to this quaternion. + */ + fromArray( array, offset = 0 ) { + + this._x = array[ offset ]; + this._y = array[ offset + 1 ]; + this._z = array[ offset + 2 ]; + this._w = array[ offset + 3 ]; + + this._onChangeCallback(); + + return this; + + } + + /** + * Writes the components of this quaternion to the given array. If no array is provided, + * the method returns a new instance. + * + * @param {Array} [array=[]] - The target array holding the quaternion components. + * @param {number} [offset=0] - Index of the first element in the array. + * @return {Array} The quaternion components. + */ + toArray( array = [], offset = 0 ) { + + array[ offset ] = this._x; + array[ offset + 1 ] = this._y; + array[ offset + 2 ] = this._z; + array[ offset + 3 ] = this._w; + + return array; + + } + + /** + * Sets the components of this quaternion from the given buffer attribute. + * + * @param {BufferAttribute} attribute - The buffer attribute holding quaternion data. + * @param {number} index - The index into the attribute. + * @return {Quaternion} A reference to this quaternion. + */ + fromBufferAttribute( attribute, index ) { + + this._x = attribute.getX( index ); + this._y = attribute.getY( index ); + this._z = attribute.getZ( index ); + this._w = attribute.getW( index ); + + this._onChangeCallback(); + + return this; + + } + + /** + * This methods defines the serialization result of this class. Returns the + * numerical elements of this quaternion in an array of format `[x, y, z, w]`. + * + * @return {Array} The serialized quaternion. + */ + toJSON() { + + return this.toArray(); + + } + + _onChange( callback ) { + + this._onChangeCallback = callback; + + return this; + + } + + _onChangeCallback() {} + + *[ Symbol.iterator ]() { + + yield this._x; + yield this._y; + yield this._z; + yield this._w; + + } + +} + +/** + * Class representing a 3D vector. A 3D vector is an ordered triplet of numbers + * (labeled x, y and z), which can be used to represent a number of things, such as: + * + * - A point in 3D space. + * - A direction and length in 3D space. In three.js the length will + * always be the Euclidean distance(straight-line distance) from `(0, 0, 0)` to `(x, y, z)` + * and the direction is also measured from `(0, 0, 0)` towards `(x, y, z)`. + * - Any arbitrary ordered triplet of numbers. + * + * There are other things a 3D vector can be used to represent, such as + * momentum vectors and so on, however these are the most + * common uses in three.js. + * + * Iterating through a vector instance will yield its components `(x, y, z)` in + * the corresponding order. + * ```js + * const a = new THREE.Vector3( 0, 1, 0 ); + * + * //no arguments; will be initialised to (0, 0, 0) + * const b = new THREE.Vector3( ); + * + * const d = a.distanceTo( b ); + * ``` + */ +class Vector3 { + + static { + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + Vector3.prototype.isVector3 = true; + + } + + /** + * Constructs a new 3D vector. + * + * @param {number} [x=0] - The x value of this vector. + * @param {number} [y=0] - The y value of this vector. + * @param {number} [z=0] - The z value of this vector. + */ + constructor( x = 0, y = 0, z = 0 ) { + + /** + * The x value of this vector. + * + * @type {number} + */ + this.x = x; + + /** + * The y value of this vector. + * + * @type {number} + */ + this.y = y; + + /** + * The z value of this vector. + * + * @type {number} + */ + this.z = z; + + } + + /** + * Sets the vector components. + * + * @param {number} x - The value of the x component. + * @param {number} y - The value of the y component. + * @param {number} z - The value of the z component. + * @return {Vector3} A reference to this vector. + */ + set( x, y, z ) { + + if ( z === undefined ) z = this.z; // sprite.scale.set(x,y) + + this.x = x; + this.y = y; + this.z = z; + + return this; + + } + + /** + * Sets the vector components to the same value. + * + * @param {number} scalar - The value to set for all vector components. + * @return {Vector3} A reference to this vector. + */ + setScalar( scalar ) { + + this.x = scalar; + this.y = scalar; + this.z = scalar; + + return this; + + } + + /** + * Sets the vector's x component to the given value. + * + * @param {number} x - The value to set. + * @return {Vector3} A reference to this vector. + */ + setX( x ) { + + this.x = x; + + return this; + + } + + /** + * Sets the vector's y component to the given value. + * + * @param {number} y - The value to set. + * @return {Vector3} A reference to this vector. + */ + setY( y ) { + + this.y = y; + + return this; + + } + + /** + * Sets the vector's z component to the given value. + * + * @param {number} z - The value to set. + * @return {Vector3} A reference to this vector. + */ + setZ( z ) { + + this.z = z; + + return this; + + } + + /** + * Allows to set a vector component with an index. + * + * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z. + * @param {number} value - The value to set. + * @return {Vector3} A reference to this vector. + */ + setComponent( index, value ) { + + switch ( index ) { + + case 0: this.x = value; break; + case 1: this.y = value; break; + case 2: this.z = value; break; + default: throw new Error( 'THREE.Vector3: index is out of range: ' + index ); + + } + + return this; + + } + + /** + * Returns the value of the vector component which matches the given index. + * + * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z. + * @return {number} A vector component value. + */ + getComponent( index ) { + + switch ( index ) { + + case 0: return this.x; + case 1: return this.y; + case 2: return this.z; + default: throw new Error( 'THREE.Vector3: index is out of range: ' + index ); + + } + + } + + /** + * Returns a new vector with copied values from this instance. + * + * @return {Vector3} A clone of this instance. + */ + clone() { + + return new this.constructor( this.x, this.y, this.z ); + + } + + /** + * Copies the values of the given vector to this instance. + * + * @param {Vector3} v - The vector to copy. + * @return {Vector3} A reference to this vector. + */ + copy( v ) { + + this.x = v.x; + this.y = v.y; + this.z = v.z; + + return this; + + } + + /** + * Adds the given vector to this instance. + * + * @param {Vector3} v - The vector to add. + * @return {Vector3} A reference to this vector. + */ + add( v ) { + + this.x += v.x; + this.y += v.y; + this.z += v.z; + + return this; + + } + + /** + * Adds the given scalar value to all components of this instance. + * + * @param {number} s - The scalar to add. + * @return {Vector3} A reference to this vector. + */ + addScalar( s ) { + + this.x += s; + this.y += s; + this.z += s; + + return this; + + } + + /** + * Adds the given vectors and stores the result in this instance. + * + * @param {Vector3} a - The first vector. + * @param {Vector3} b - The second vector. + * @return {Vector3} A reference to this vector. + */ + addVectors( a, b ) { + + this.x = a.x + b.x; + this.y = a.y + b.y; + this.z = a.z + b.z; + + return this; + + } + + /** + * Adds the given vector scaled by the given factor to this instance. + * + * @param {Vector3|Vector4} v - The vector. + * @param {number} s - The factor that scales `v`. + * @return {Vector3} A reference to this vector. + */ + addScaledVector( v, s ) { + + this.x += v.x * s; + this.y += v.y * s; + this.z += v.z * s; + + return this; + + } + + /** + * Subtracts the given vector from this instance. + * + * @param {Vector3} v - The vector to subtract. + * @return {Vector3} A reference to this vector. + */ + sub( v ) { + + this.x -= v.x; + this.y -= v.y; + this.z -= v.z; + + return this; + + } + + /** + * Subtracts the given scalar value from all components of this instance. + * + * @param {number} s - The scalar to subtract. + * @return {Vector3} A reference to this vector. + */ + subScalar( s ) { + + this.x -= s; + this.y -= s; + this.z -= s; + + return this; + + } + + /** + * Subtracts the given vectors and stores the result in this instance. + * + * @param {Vector3} a - The first vector. + * @param {Vector3} b - The second vector. + * @return {Vector3} A reference to this vector. + */ + subVectors( a, b ) { + + this.x = a.x - b.x; + this.y = a.y - b.y; + this.z = a.z - b.z; + + return this; + + } + + /** + * Multiplies the given vector with this instance. + * + * @param {Vector3} v - The vector to multiply. + * @return {Vector3} A reference to this vector. + */ + multiply( v ) { + + this.x *= v.x; + this.y *= v.y; + this.z *= v.z; + + return this; + + } + + /** + * Multiplies the given scalar value with all components of this instance. + * + * @param {number} scalar - The scalar to multiply. + * @return {Vector3} A reference to this vector. + */ + multiplyScalar( scalar ) { + + this.x *= scalar; + this.y *= scalar; + this.z *= scalar; + + return this; + + } + + /** + * Multiplies the given vectors and stores the result in this instance. + * + * @param {Vector3} a - The first vector. + * @param {Vector3} b - The second vector. + * @return {Vector3} A reference to this vector. + */ + multiplyVectors( a, b ) { + + this.x = a.x * b.x; + this.y = a.y * b.y; + this.z = a.z * b.z; + + return this; + + } + + /** + * Applies the given Euler rotation to this vector. + * + * @param {Euler} euler - The Euler angles. + * @return {Vector3} A reference to this vector. + */ + applyEuler( euler ) { + + return this.applyQuaternion( _quaternion$5.setFromEuler( euler ) ); + + } + + /** + * Applies a rotation specified by an axis and an angle to this vector. + * + * @param {Vector3} axis - A normalized vector representing the rotation axis. + * @param {number} angle - The angle in radians. + * @return {Vector3} A reference to this vector. + */ + applyAxisAngle( axis, angle ) { + + return this.applyQuaternion( _quaternion$5.setFromAxisAngle( axis, angle ) ); + + } + + /** + * Multiplies this vector with the given 3x3 matrix. + * + * @param {Matrix3} m - The 3x3 matrix. + * @return {Vector3} A reference to this vector. + */ + applyMatrix3( m ) { + + const x = this.x, y = this.y, z = this.z; + const e = m.elements; + + this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z; + this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z; + this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z; + + return this; + + } + + /** + * Multiplies this vector by the given normal matrix and normalizes + * the result. + * + * @param {Matrix3} m - The normal matrix. + * @return {Vector3} A reference to this vector. + */ + applyNormalMatrix( m ) { + + return this.applyMatrix3( m ).normalize(); + + } + + /** + * Multiplies this vector (with an implicit 1 in the 4th dimension) by m, and + * divides by perspective. + * + * @param {Matrix4} m - The matrix to apply. + * @return {Vector3} A reference to this vector. + */ + applyMatrix4( m ) { + + const x = this.x, y = this.y, z = this.z; + const e = m.elements; + + const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] ); + + this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w; + this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w; + this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w; + + return this; + + } + + /** + * Applies the given Quaternion to this vector. + * + * @param {Quaternion} q - The Quaternion. + * @return {Vector3} A reference to this vector. + */ + applyQuaternion( q ) { + + // quaternion q is assumed to have unit length + + const vx = this.x, vy = this.y, vz = this.z; + const qx = q.x, qy = q.y, qz = q.z, qw = q.w; + + // t = 2 * cross( q.xyz, v ); + const tx = 2 * ( qy * vz - qz * vy ); + const ty = 2 * ( qz * vx - qx * vz ); + const tz = 2 * ( qx * vy - qy * vx ); + + // v + q.w * t + cross( q.xyz, t ); + this.x = vx + qw * tx + qy * tz - qz * ty; + this.y = vy + qw * ty + qz * tx - qx * tz; + this.z = vz + qw * tz + qx * ty - qy * tx; + + return this; + + } + + /** + * Projects this vector from world space into the camera's normalized + * device coordinate (NDC) space. + * + * @param {Camera} camera - The camera. + * @return {Vector3} A reference to this vector. + */ + project( camera ) { + + return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix ); + + } + + /** + * Unprojects this vector from the camera's normalized device coordinate (NDC) + * space into world space. + * + * @param {Camera} camera - The camera. + * @return {Vector3} A reference to this vector. + */ + unproject( camera ) { + + return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld ); + + } + + /** + * Transforms this vector by the upper left 3x3 sub-matrix of the given 4x4 matrix, + * and normalizes the result. + * + * @param {Matrix4} m - The matrix. + * @return {Vector3} A reference to this vector. + */ + transformDirection( m ) { + + // input: THREE.Matrix4 affine matrix + // vector interpreted as a direction + + const x = this.x, y = this.y, z = this.z; + const e = m.elements; + + this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z; + this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z; + this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z; + + return this.normalize(); + + } + + /** + * Divides this instance by the given vector. + * + * @param {Vector3} v - The vector to divide. + * @return {Vector3} A reference to this vector. + */ + divide( v ) { + + this.x /= v.x; + this.y /= v.y; + this.z /= v.z; + + return this; + + } + + /** + * Divides this vector by the given scalar. + * + * @param {number} scalar - The scalar to divide. + * @return {Vector3} A reference to this vector. + */ + divideScalar( scalar ) { + + return this.multiplyScalar( 1 / scalar ); + + } + + /** + * If this vector's x, y or z value is greater than the given vector's x, y or z + * value, replace that value with the corresponding min value. + * + * @param {Vector3} v - The vector. + * @return {Vector3} A reference to this vector. + */ + min( v ) { + + this.x = Math.min( this.x, v.x ); + this.y = Math.min( this.y, v.y ); + this.z = Math.min( this.z, v.z ); + + return this; + + } + + /** + * If this vector's x, y or z value is less than the given vector's x, y or z + * value, replace that value with the corresponding max value. + * + * @param {Vector3} v - The vector. + * @return {Vector3} A reference to this vector. + */ + max( v ) { + + this.x = Math.max( this.x, v.x ); + this.y = Math.max( this.y, v.y ); + this.z = Math.max( this.z, v.z ); + + return this; + + } + + /** + * If this vector's x, y or z value is greater than the max vector's x, y or z + * value, it is replaced by the corresponding value. + * If this vector's x, y or z value is less than the min vector's x, y or z value, + * it is replaced by the corresponding value. + * + * @param {Vector3} min - The minimum x, y and z values. + * @param {Vector3} max - The maximum x, y and z values in the desired range. + * @return {Vector3} A reference to this vector. + */ + clamp( min, max ) { + + // assumes min < max, componentwise + + this.x = clamp( this.x, min.x, max.x ); + this.y = clamp( this.y, min.y, max.y ); + this.z = clamp( this.z, min.z, max.z ); + + return this; + + } + + /** + * If this vector's x, y or z values are greater than the max value, they are + * replaced by the max value. + * If this vector's x, y or z values are less than the min value, they are + * replaced by the min value. + * + * @param {number} minVal - The minimum value the components will be clamped to. + * @param {number} maxVal - The maximum value the components will be clamped to. + * @return {Vector3} A reference to this vector. + */ + clampScalar( minVal, maxVal ) { + + this.x = clamp( this.x, minVal, maxVal ); + this.y = clamp( this.y, minVal, maxVal ); + this.z = clamp( this.z, minVal, maxVal ); + + return this; + + } + + /** + * If this vector's length is greater than the max value, it is replaced by + * the max value. + * If this vector's length is less than the min value, it is replaced by the + * min value. + * + * @param {number} min - The minimum value the vector length will be clamped to. + * @param {number} max - The maximum value the vector length will be clamped to. + * @return {Vector3} A reference to this vector. + */ + clampLength( min, max ) { + + const length = this.length(); + + return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) ); + + } + + /** + * The components of this vector are rounded down to the nearest integer value. + * + * @return {Vector3} A reference to this vector. + */ + floor() { + + this.x = Math.floor( this.x ); + this.y = Math.floor( this.y ); + this.z = Math.floor( this.z ); + + return this; + + } + + /** + * The components of this vector are rounded up to the nearest integer value. + * + * @return {Vector3} A reference to this vector. + */ + ceil() { + + this.x = Math.ceil( this.x ); + this.y = Math.ceil( this.y ); + this.z = Math.ceil( this.z ); + + return this; + + } + + /** + * The components of this vector are rounded to the nearest integer value + * + * @return {Vector3} A reference to this vector. + */ + round() { + + this.x = Math.round( this.x ); + this.y = Math.round( this.y ); + this.z = Math.round( this.z ); + + return this; + + } + + /** + * The components of this vector are rounded towards zero (up if negative, + * down if positive) to an integer value. + * + * @return {Vector3} A reference to this vector. + */ + roundToZero() { + + this.x = Math.trunc( this.x ); + this.y = Math.trunc( this.y ); + this.z = Math.trunc( this.z ); + + return this; + + } + + /** + * Inverts this vector - i.e. sets x = -x, y = -y and z = -z. + * + * @return {Vector3} A reference to this vector. + */ + negate() { + + this.x = - this.x; + this.y = - this.y; + this.z = - this.z; + + return this; + + } + + /** + * Calculates the dot product of the given vector with this instance. + * + * @param {Vector3} v - The vector to compute the dot product with. + * @return {number} The result of the dot product. + */ + dot( v ) { + + return this.x * v.x + this.y * v.y + this.z * v.z; + + } + + /** + * Computes the square of the Euclidean length (straight-line length) from + * (0, 0, 0) to (x, y, z). If you are comparing the lengths of vectors, you should + * compare the length squared instead as it is slightly more efficient to calculate. + * + * @return {number} The square length of this vector. + */ + lengthSq() { + + return this.x * this.x + this.y * this.y + this.z * this.z; + + } + + /** + * Computes the Euclidean length (straight-line length) from (0, 0, 0) to (x, y, z). + * + * @return {number} The length of this vector. + */ + length() { + + return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z ); + + } + + /** + * Computes the Manhattan length of this vector. + * + * @return {number} The length of this vector. + */ + manhattanLength() { + + return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ); + + } + + /** + * Converts this vector to a unit vector - that is, sets it equal to a vector + * with the same direction as this one, but with a vector length of `1`. + * + * @return {Vector3} A reference to this vector. + */ + normalize() { + + return this.divideScalar( this.length() || 1 ); + + } + + /** + * Sets this vector to a vector with the same direction as this one, but + * with the specified length. + * + * @param {number} length - The new length of this vector. + * @return {Vector3} A reference to this vector. + */ + setLength( length ) { + + return this.normalize().multiplyScalar( length ); + + } + + /** + * Linearly interpolates between the given vector and this instance, where + * alpha is the percent distance along the line - alpha = 0 will be this + * vector, and alpha = 1 will be the given one. + * + * @param {Vector3} v - The vector to interpolate towards. + * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`. + * @return {Vector3} A reference to this vector. + */ + lerp( v, alpha ) { + + this.x += ( v.x - this.x ) * alpha; + this.y += ( v.y - this.y ) * alpha; + this.z += ( v.z - this.z ) * alpha; + + return this; + + } + + /** + * Linearly interpolates between the given vectors, where alpha is the percent + * distance along the line - alpha = 0 will be first vector, and alpha = 1 will + * be the second one. The result is stored in this instance. + * + * @param {Vector3} v1 - The first vector. + * @param {Vector3} v2 - The second vector. + * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`. + * @return {Vector3} A reference to this vector. + */ + lerpVectors( v1, v2, alpha ) { + + this.x = v1.x + ( v2.x - v1.x ) * alpha; + this.y = v1.y + ( v2.y - v1.y ) * alpha; + this.z = v1.z + ( v2.z - v1.z ) * alpha; + + return this; + + } + + /** + * Calculates the cross product of the given vector with this instance. + * + * @param {Vector3} v - The vector to compute the cross product with. + * @return {Vector3} The result of the cross product. + */ + cross( v ) { + + return this.crossVectors( this, v ); + + } + + /** + * Calculates the cross product of the given vectors and stores the result + * in this instance. + * + * @param {Vector3} a - The first vector. + * @param {Vector3} b - The second vector. + * @return {Vector3} A reference to this vector. + */ + crossVectors( a, b ) { + + const ax = a.x, ay = a.y, az = a.z; + const bx = b.x, by = b.y, bz = b.z; + + this.x = ay * bz - az * by; + this.y = az * bx - ax * bz; + this.z = ax * by - ay * bx; + + return this; + + } + + /** + * Projects this vector onto the given one. + * + * @param {Vector3} v - The vector to project to. + * @return {Vector3} A reference to this vector. + */ + projectOnVector( v ) { + + const denominator = v.lengthSq(); + + if ( denominator === 0 ) return this.set( 0, 0, 0 ); + + const scalar = v.dot( this ) / denominator; + + return this.copy( v ).multiplyScalar( scalar ); + + } + + /** + * Projects this vector onto a plane by subtracting this + * vector projected onto the plane's normal from this vector. + * + * @param {Vector3} planeNormal - The plane normal. + * @return {Vector3} A reference to this vector. + */ + projectOnPlane( planeNormal ) { + + _vector$c.copy( this ).projectOnVector( planeNormal ); + + return this.sub( _vector$c ); + + } + + /** + * Reflects this vector off a plane orthogonal to the given normal vector. + * + * @param {Vector3} normal - The (normalized) normal vector. + * @return {Vector3} A reference to this vector. + */ + reflect( normal ) { + + return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) ); + + } + /** + * Returns the angle between the given vector and this instance in radians. + * + * @param {Vector3} v - The vector to compute the angle with. + * @return {number} The angle in radians. + */ + angleTo( v ) { + + const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() ); + + if ( denominator === 0 ) return Math.PI / 2; + + const theta = this.dot( v ) / denominator; + + // clamp, to handle numerical problems + + return Math.acos( clamp( theta, -1, 1 ) ); + + } + + /** + * Computes the distance from the given vector to this instance. + * + * @param {Vector3} v - The vector to compute the distance to. + * @return {number} The distance. + */ + distanceTo( v ) { + + return Math.sqrt( this.distanceToSquared( v ) ); + + } + + /** + * Computes the squared distance from the given vector to this instance. + * If you are just comparing the distance with another distance, you should compare + * the distance squared instead as it is slightly more efficient to calculate. + * + * @param {Vector3} v - The vector to compute the squared distance to. + * @return {number} The squared distance. + */ + distanceToSquared( v ) { + + const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z; + + return dx * dx + dy * dy + dz * dz; + + } + + /** + * Computes the Manhattan distance from the given vector to this instance. + * + * @param {Vector3} v - The vector to compute the Manhattan distance to. + * @return {number} The Manhattan distance. + */ + manhattanDistanceTo( v ) { + + return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z ); + + } + + /** + * Sets the vector components from the given spherical coordinates. + * + * @param {Spherical} s - The spherical coordinates. + * @return {Vector3} A reference to this vector. + */ + setFromSpherical( s ) { + + return this.setFromSphericalCoords( s.radius, s.phi, s.theta ); + + } + + /** + * Sets the vector components from the given spherical coordinates. + * + * @param {number} radius - The radius. + * @param {number} phi - The phi angle in radians. + * @param {number} theta - The theta angle in radians. + * @return {Vector3} A reference to this vector. + */ + setFromSphericalCoords( radius, phi, theta ) { + + const sinPhiRadius = Math.sin( phi ) * radius; + + this.x = sinPhiRadius * Math.sin( theta ); + this.y = Math.cos( phi ) * radius; + this.z = sinPhiRadius * Math.cos( theta ); + + return this; + + } + + /** + * Sets the vector components from the given cylindrical coordinates. + * + * @param {Cylindrical} c - The cylindrical coordinates. + * @return {Vector3} A reference to this vector. + */ + setFromCylindrical( c ) { + + return this.setFromCylindricalCoords( c.radius, c.theta, c.y ); + + } + + /** + * Sets the vector components from the given cylindrical coordinates. + * + * @param {number} radius - The radius. + * @param {number} theta - The theta angle in radians. + * @param {number} y - The y value. + * @return {Vector3} A reference to this vector. + */ + setFromCylindricalCoords( radius, theta, y ) { + + this.x = radius * Math.sin( theta ); + this.y = y; + this.z = radius * Math.cos( theta ); + + return this; + + } + + /** + * Sets the vector components to the position elements of the + * given transformation matrix. + * + * @param {Matrix4} m - The 4x4 matrix. + * @return {Vector3} A reference to this vector. + */ + setFromMatrixPosition( m ) { + + const e = m.elements; + + this.x = e[ 12 ]; + this.y = e[ 13 ]; + this.z = e[ 14 ]; + + return this; + + } + + /** + * Sets the vector components to the scale elements of the + * given transformation matrix. + * + * @param {Matrix4} m - The 4x4 matrix. + * @return {Vector3} A reference to this vector. + */ + setFromMatrixScale( m ) { + + const sx = this.setFromMatrixColumn( m, 0 ).length(); + const sy = this.setFromMatrixColumn( m, 1 ).length(); + const sz = this.setFromMatrixColumn( m, 2 ).length(); + + this.x = sx; + this.y = sy; + this.z = sz; + + return this; + + } + + /** + * Sets the vector components from the specified matrix column. + * + * @param {Matrix4} m - The 4x4 matrix. + * @param {number} index - The column index. + * @return {Vector3} A reference to this vector. + */ + setFromMatrixColumn( m, index ) { + + return this.fromArray( m.elements, index * 4 ); + + } + + /** + * Sets the vector components from the specified matrix column. + * + * @param {Matrix3} m - The 3x3 matrix. + * @param {number} index - The column index. + * @return {Vector3} A reference to this vector. + */ + setFromMatrix3Column( m, index ) { + + return this.fromArray( m.elements, index * 3 ); + + } + + /** + * Sets the vector components from the given Euler angles. + * + * @param {Euler} e - The Euler angles to set. + * @return {Vector3} A reference to this vector. + */ + setFromEuler( e ) { + + this.x = e._x; + this.y = e._y; + this.z = e._z; + + return this; + + } + + /** + * Sets the vector components from the RGB components of the + * given color. + * + * @param {Color} c - The color to set. + * @return {Vector3} A reference to this vector. + */ + setFromColor( c ) { + + this.x = c.r; + this.y = c.g; + this.z = c.b; + + return this; + + } + + /** + * Returns `true` if this vector is equal with the given one. + * + * @param {Vector3} v - The vector to test for equality. + * @return {boolean} Whether this vector is equal with the given one. + */ + equals( v ) { + + return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) ); + + } + + /** + * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]` + * and z value to be `array[ offset + 2 ]`. + * + * @param {Array} array - An array holding the vector component values. + * @param {number} [offset=0] - The offset into the array. + * @return {Vector3} A reference to this vector. + */ + fromArray( array, offset = 0 ) { + + this.x = array[ offset ]; + this.y = array[ offset + 1 ]; + this.z = array[ offset + 2 ]; + + return this; + + } + + /** + * Writes the components of this vector to the given array. If no array is provided, + * the method returns a new instance. + * + * @param {Array} [array=[]] - The target array holding the vector components. + * @param {number} [offset=0] - Index of the first element in the array. + * @return {Array} The vector components. + */ + toArray( array = [], offset = 0 ) { + + array[ offset ] = this.x; + array[ offset + 1 ] = this.y; + array[ offset + 2 ] = this.z; + + return array; + + } + + /** + * Sets the components of this vector from the given buffer attribute. + * + * @param {BufferAttribute} attribute - The buffer attribute holding vector data. + * @param {number} index - The index into the attribute. + * @return {Vector3} A reference to this vector. + */ + fromBufferAttribute( attribute, index ) { + + this.x = attribute.getX( index ); + this.y = attribute.getY( index ); + this.z = attribute.getZ( index ); + + return this; + + } + + /** + * Sets each component of this vector to a pseudo-random value between `0` and + * `1`, excluding `1`. + * + * @return {Vector3} A reference to this vector. + */ + random() { + + this.x = Math.random(); + this.y = Math.random(); + this.z = Math.random(); + + return this; + + } + + /** + * Sets this vector to a uniformly random point on a unit sphere. + * + * @return {Vector3} A reference to this vector. + */ + randomDirection() { + + // https://mathworld.wolfram.com/SpherePointPicking.html + + const theta = Math.random() * Math.PI * 2; + const u = Math.random() * 2 - 1; + const c = Math.sqrt( 1 - u * u ); + + this.x = c * Math.cos( theta ); + this.y = u; + this.z = c * Math.sin( theta ); + + return this; + + } + + *[ Symbol.iterator ]() { + + yield this.x; + yield this.y; + yield this.z; + + } + +} + +const _vector$c = /*@__PURE__*/ new Vector3(); +const _quaternion$5 = /*@__PURE__*/ new Quaternion(); + +/** + * Represents a 3x3 matrix. + * + * A Note on Row-Major and Column-Major Ordering: + * + * The constructor and {@link Matrix3#set} method take arguments in + * [row-major](https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order) + * order, while internally they are stored in the {@link Matrix3#elements} array in column-major order. + * This means that calling: + * ```js + * const m = new THREE.Matrix(); + * m.set( 11, 12, 13, + * 21, 22, 23, + * 31, 32, 33 ); + * ``` + * will result in the elements array containing: + * ```js + * m.elements = [ 11, 21, 31, + * 12, 22, 32, + * 13, 23, 33 ]; + * ``` + * and internally all calculations are performed using column-major ordering. + * However, as the actual ordering makes no difference mathematically and + * most people are used to thinking about matrices in row-major order, the + * three.js documentation shows matrices in row-major order. Just bear in + * mind that if you are reading the source code, you'll have to take the + * transpose of any matrices outlined here to make sense of the calculations. + */ +class Matrix3 { + + static { + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + Matrix3.prototype.isMatrix3 = true; + + } + + /** + * Constructs a new 3x3 matrix. The arguments are supposed to be + * in row-major order. If no arguments are provided, the constructor + * initializes the matrix as an identity matrix. + * + * @param {number} [n11] - 1-1 matrix element. + * @param {number} [n12] - 1-2 matrix element. + * @param {number} [n13] - 1-3 matrix element. + * @param {number} [n21] - 2-1 matrix element. + * @param {number} [n22] - 2-2 matrix element. + * @param {number} [n23] - 2-3 matrix element. + * @param {number} [n31] - 3-1 matrix element. + * @param {number} [n32] - 3-2 matrix element. + * @param {number} [n33] - 3-3 matrix element. + */ + constructor( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) { + + /** + * A column-major list of matrix values. + * + * @type {Array} + */ + this.elements = [ + + 1, 0, 0, + 0, 1, 0, + 0, 0, 1 + + ]; + + if ( n11 !== undefined ) { + + this.set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ); + + } + + } + + /** + * Sets the elements of the matrix.The arguments are supposed to be + * in row-major order. + * + * @param {number} [n11] - 1-1 matrix element. + * @param {number} [n12] - 1-2 matrix element. + * @param {number} [n13] - 1-3 matrix element. + * @param {number} [n21] - 2-1 matrix element. + * @param {number} [n22] - 2-2 matrix element. + * @param {number} [n23] - 2-3 matrix element. + * @param {number} [n31] - 3-1 matrix element. + * @param {number} [n32] - 3-2 matrix element. + * @param {number} [n33] - 3-3 matrix element. + * @return {Matrix3} A reference to this matrix. + */ + set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) { + + const te = this.elements; + + te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31; + te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32; + te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33; + + return this; + + } + + /** + * Sets this matrix to the 3x3 identity matrix. + * + * @return {Matrix3} A reference to this matrix. + */ + identity() { + + this.set( + + 1, 0, 0, + 0, 1, 0, + 0, 0, 1 + + ); + + return this; + + } + + /** + * Copies the values of the given matrix to this instance. + * + * @param {Matrix3} m - The matrix to copy. + * @return {Matrix3} A reference to this matrix. + */ + copy( m ) { + + const te = this.elements; + const me = m.elements; + + te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; + te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; + te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ]; + + return this; + + } + + /** + * Extracts the basis of this matrix into the three axis vectors provided. + * + * @param {Vector3} xAxis - The basis's x axis. + * @param {Vector3} yAxis - The basis's y axis. + * @param {Vector3} zAxis - The basis's z axis. + * @return {Matrix3} A reference to this matrix. + */ + extractBasis( xAxis, yAxis, zAxis ) { + + xAxis.setFromMatrix3Column( this, 0 ); + yAxis.setFromMatrix3Column( this, 1 ); + zAxis.setFromMatrix3Column( this, 2 ); + + return this; + + } + + /** + * Set this matrix to the upper 3x3 matrix of the given 4x4 matrix. + * + * @param {Matrix4} m - The 4x4 matrix. + * @return {Matrix3} A reference to this matrix. + */ + setFromMatrix4( m ) { + + const me = m.elements; + + this.set( + + me[ 0 ], me[ 4 ], me[ 8 ], + me[ 1 ], me[ 5 ], me[ 9 ], + me[ 2 ], me[ 6 ], me[ 10 ] + + ); + + return this; + + } + + /** + * Post-multiplies this matrix by the given 3x3 matrix. + * + * @param {Matrix3} m - The matrix to multiply with. + * @return {Matrix3} A reference to this matrix. + */ + multiply( m ) { + + return this.multiplyMatrices( this, m ); + + } + + /** + * Pre-multiplies this matrix by the given 3x3 matrix. + * + * @param {Matrix3} m - The matrix to multiply with. + * @return {Matrix3} A reference to this matrix. + */ + premultiply( m ) { + + return this.multiplyMatrices( m, this ); + + } + + /** + * Multiples the given 3x3 matrices and stores the result + * in this matrix. + * + * @param {Matrix3} a - The first matrix. + * @param {Matrix3} b - The second matrix. + * @return {Matrix3} A reference to this matrix. + */ + multiplyMatrices( a, b ) { + + const ae = a.elements; + const be = b.elements; + const te = this.elements; + + const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ]; + const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ]; + const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ]; + + const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ]; + const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ]; + const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ]; + + te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31; + te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32; + te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33; + + te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31; + te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32; + te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33; + + te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31; + te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32; + te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33; + + return this; + + } + + /** + * Multiplies every component of the matrix by the given scalar. + * + * @param {number} s - The scalar. + * @return {Matrix3} A reference to this matrix. + */ + multiplyScalar( s ) { + + const te = this.elements; + + te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s; + te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s; + te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s; + + return this; + + } + + /** + * Computes and returns the determinant of this matrix. + * + * @return {number} The determinant. + */ + determinant() { + + const te = this.elements; + + const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ], + d = te[ 3 ], e = te[ 4 ], f = te[ 5 ], + g = te[ 6 ], h = te[ 7 ], i = te[ 8 ]; + + return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g; + + } + + /** + * Inverts this matrix, using the [analytic method](https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution). + * You can not invert with a determinant of zero. If you attempt this, the method produces + * a zero matrix instead. + * + * @return {Matrix3} A reference to this matrix. + */ + invert() { + + const te = this.elements, + + n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], + n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ], + n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ], + + t11 = n33 * n22 - n32 * n23, + t12 = n32 * n13 - n33 * n12, + t13 = n23 * n12 - n22 * n13, + + det = n11 * t11 + n21 * t12 + n31 * t13; + + if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 ); + + const detInv = 1 / det; + + te[ 0 ] = t11 * detInv; + te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv; + te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv; + + te[ 3 ] = t12 * detInv; + te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv; + te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv; + + te[ 6 ] = t13 * detInv; + te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv; + te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv; + + return this; + + } + + /** + * Transposes this matrix in place. + * + * @return {Matrix3} A reference to this matrix. + */ + transpose() { + + let tmp; + const m = this.elements; + + tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp; + tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp; + tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp; + + return this; + + } + + /** + * Computes the normal matrix which is the inverse transpose of the upper + * left 3x3 portion of the given 4x4 matrix. + * + * @param {Matrix4} matrix4 - The 4x4 matrix. + * @return {Matrix3} A reference to this matrix. + */ + getNormalMatrix( matrix4 ) { + + return this.setFromMatrix4( matrix4 ).invert().transpose(); + + } + + /** + * Transposes this matrix into the supplied array, and returns itself unchanged. + * + * @param {Array} r - An array to store the transposed matrix elements. + * @return {Matrix3} A reference to this matrix. + */ + transposeIntoArray( r ) { + + const m = this.elements; + + r[ 0 ] = m[ 0 ]; + r[ 1 ] = m[ 3 ]; + r[ 2 ] = m[ 6 ]; + r[ 3 ] = m[ 1 ]; + r[ 4 ] = m[ 4 ]; + r[ 5 ] = m[ 7 ]; + r[ 6 ] = m[ 2 ]; + r[ 7 ] = m[ 5 ]; + r[ 8 ] = m[ 8 ]; + + return this; + + } + + /** + * Sets the UV transform matrix from offset, repeat, rotation, and center. + * + * @param {number} tx - Offset x. + * @param {number} ty - Offset y. + * @param {number} sx - Repeat x. + * @param {number} sy - Repeat y. + * @param {number} rotation - Rotation, in radians. Positive values rotate counterclockwise. + * @param {number} cx - Center x of rotation. + * @param {number} cy - Center y of rotation + * @return {Matrix3} A reference to this matrix. + */ + setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) { + + const c = Math.cos( rotation ); + const s = Math.sin( rotation ); + + this.set( + sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx, + - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty, + 0, 0, 1 + ); + + return this; + + } + + /** + * Scales this matrix with the given scalar values. + * + * @deprecated + * @param {number} sx - The amount to scale in the X axis. + * @param {number} sy - The amount to scale in the Y axis. + * @return {Matrix3} A reference to this matrix. + */ + scale( sx, sy ) { + + warnOnce( 'Matrix3: .scale() is deprecated. Use .makeScale() instead.' ); // @deprecated r185 + + this.premultiply( _m3.makeScale( sx, sy ) ); + + return this; + + } + + /** + * Rotates this matrix by the given angle. + * + * @deprecated + * @param {number} theta - The rotation in radians. + * @return {Matrix3} A reference to this matrix. + */ + rotate( theta ) { + + warnOnce( 'Matrix3: .rotate() is deprecated. Use .makeRotation() instead.' ); // @deprecated r185 + + this.premultiply( _m3.makeRotation( - theta ) ); + + return this; + + } + + /** + * Translates this matrix by the given scalar values. + * + * @deprecated + * @param {number} tx - The amount to translate in the X axis. + * @param {number} ty - The amount to translate in the Y axis. + * @return {Matrix3} A reference to this matrix. + */ + translate( tx, ty ) { + + warnOnce( 'Matrix3: .translate() is deprecated. Use .makeTranslation() instead.' ); // @deprecated r185 + + this.premultiply( _m3.makeTranslation( tx, ty ) ); + + return this; + + } + + // for 2D Transforms + + /** + * Sets this matrix as a 2D translation transform. + * + * @param {number|Vector2} x - The amount to translate in the X axis or alternatively a translation vector. + * @param {number} y - The amount to translate in the Y axis. + * @return {Matrix3} A reference to this matrix. + */ + makeTranslation( x, y ) { + + if ( x.isVector2 ) { + + this.set( + + 1, 0, x.x, + 0, 1, x.y, + 0, 0, 1 + + ); + + } else { + + this.set( + + 1, 0, x, + 0, 1, y, + 0, 0, 1 + + ); + + } + + return this; + + } + + /** + * Sets this matrix as a 2D rotational transformation. + * + * @param {number} theta - The rotation in radians. + * @return {Matrix3} A reference to this matrix. + */ + makeRotation( theta ) { + + // counterclockwise + + const c = Math.cos( theta ); + const s = Math.sin( theta ); + + this.set( + + c, - s, 0, + s, c, 0, + 0, 0, 1 + + ); + + return this; + + } + + /** + * Sets this matrix as a 2D scale transform. + * + * @param {number} x - The amount to scale in the X axis. + * @param {number} y - The amount to scale in the Y axis. + * @return {Matrix3} A reference to this matrix. + */ + makeScale( x, y ) { + + this.set( + + x, 0, 0, + 0, y, 0, + 0, 0, 1 + + ); + + return this; + + } + + /** + * Returns `true` if this matrix is equal with the given one. + * + * @param {Matrix3} matrix - The matrix to test for equality. + * @return {boolean} Whether this matrix is equal with the given one. + */ + equals( matrix ) { + + const te = this.elements; + const me = matrix.elements; + + for ( let i = 0; i < 9; i ++ ) { + + if ( te[ i ] !== me[ i ] ) return false; + + } + + return true; + + } + + /** + * Sets the elements of the matrix from the given array. + * + * @param {Array} array - The matrix elements in column-major order. + * @param {number} [offset=0] - Index of the first element in the array. + * @return {Matrix3} A reference to this matrix. + */ + fromArray( array, offset = 0 ) { + + for ( let i = 0; i < 9; i ++ ) { + + this.elements[ i ] = array[ i + offset ]; + + } + + return this; + + } + + /** + * Writes the elements of this matrix to the given array. If no array is provided, + * the method returns a new instance. + * + * @param {Array} [array=[]] - The target array holding the matrix elements in column-major order. + * @param {number} [offset=0] - Index of the first element in the array. + * @return {Array} The matrix elements in column-major order. + */ + toArray( array = [], offset = 0 ) { + + const te = this.elements; + + array[ offset ] = te[ 0 ]; + array[ offset + 1 ] = te[ 1 ]; + array[ offset + 2 ] = te[ 2 ]; + + array[ offset + 3 ] = te[ 3 ]; + array[ offset + 4 ] = te[ 4 ]; + array[ offset + 5 ] = te[ 5 ]; + + array[ offset + 6 ] = te[ 6 ]; + array[ offset + 7 ] = te[ 7 ]; + array[ offset + 8 ] = te[ 8 ]; + + return array; + + } + + /** + * Returns a matrix with copied values from this instance. + * + * @return {Matrix3} A clone of this instance. + */ + clone() { + + return new this.constructor().fromArray( this.elements ); + + } + +} + +const _m3 = /*@__PURE__*/ new Matrix3(); + +const LINEAR_REC709_TO_XYZ = /*@__PURE__*/ new Matrix3().set( + 0.4123908, 0.3575843, 0.1804808, + 0.2126390, 0.7151687, 0.0721923, + 0.0193308, 0.1191948, 0.9505322 +); + +const XYZ_TO_LINEAR_REC709 = /*@__PURE__*/ new Matrix3().set( + 3.2409699, -1.5373832, -0.4986108, + -0.9692436, 1.8759675, 0.0415551, + 0.0556301, -0.203977, 1.0569715 +); + +function createColorManagement() { + + const ColorManagement = { + + enabled: true, + + workingColorSpace: LinearSRGBColorSpace, + + /** + * Implementations of supported color spaces. + * + * Required: + * - primaries: chromaticity coordinates [ rx ry gx gy bx by ] + * - whitePoint: reference white [ x y ] + * - transfer: transfer function (pre-defined) + * - toXYZ: Matrix3 RGB to XYZ transform + * - fromXYZ: Matrix3 XYZ to RGB transform + * - luminanceCoefficients: RGB luminance coefficients + * + * Optional: + * - outputColorSpaceConfig: { drawingBufferColorSpace: ColorSpace, toneMappingMode: 'extended' | 'standard' } + * - workingColorSpaceConfig: { unpackColorSpace: ColorSpace } + * + * Reference: + * - https://www.russellcottrell.com/photo/matrixCalculator.htm + */ + spaces: {}, + + convert: function ( color, sourceColorSpace, targetColorSpace ) { + + if ( this.enabled === false || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) { + + return color; + + } + + if ( this.spaces[ sourceColorSpace ].transfer === SRGBTransfer ) { + + color.r = SRGBToLinear( color.r ); + color.g = SRGBToLinear( color.g ); + color.b = SRGBToLinear( color.b ); + + } + + if ( this.spaces[ sourceColorSpace ].primaries !== this.spaces[ targetColorSpace ].primaries ) { + + color.applyMatrix3( this.spaces[ sourceColorSpace ].toXYZ ); + color.applyMatrix3( this.spaces[ targetColorSpace ].fromXYZ ); + + } + + if ( this.spaces[ targetColorSpace ].transfer === SRGBTransfer ) { + + color.r = LinearToSRGB( color.r ); + color.g = LinearToSRGB( color.g ); + color.b = LinearToSRGB( color.b ); + + } + + return color; + + }, + + workingToColorSpace: function ( color, targetColorSpace ) { + + return this.convert( color, this.workingColorSpace, targetColorSpace ); + + }, + + colorSpaceToWorking: function ( color, sourceColorSpace ) { + + return this.convert( color, sourceColorSpace, this.workingColorSpace ); + + }, + + getPrimaries: function ( colorSpace ) { + + return this.spaces[ colorSpace ].primaries; + + }, + + getTransfer: function ( colorSpace ) { + + if ( colorSpace === NoColorSpace ) return LinearTransfer; + + return this.spaces[ colorSpace ].transfer; + + }, + + getToneMappingMode: function ( colorSpace ) { + + return this.spaces[ colorSpace ].outputColorSpaceConfig.toneMappingMode || 'standard'; + + }, + + getLuminanceCoefficients: function ( target, colorSpace = this.workingColorSpace ) { + + return target.fromArray( this.spaces[ colorSpace ].luminanceCoefficients ); + + }, + + define: function ( colorSpaces ) { + + Object.assign( this.spaces, colorSpaces ); + + }, + + // Internal APIs + + _getMatrix: function ( targetMatrix, sourceColorSpace, targetColorSpace ) { + + return targetMatrix + .copy( this.spaces[ sourceColorSpace ].toXYZ ) + .multiply( this.spaces[ targetColorSpace ].fromXYZ ); + + }, + + _getDrawingBufferColorSpace: function ( colorSpace ) { + + return this.spaces[ colorSpace ].outputColorSpaceConfig.drawingBufferColorSpace; + + }, + + _getUnpackColorSpace: function ( colorSpace = this.workingColorSpace ) { + + return this.spaces[ colorSpace ].workingColorSpaceConfig.unpackColorSpace; + + }, + + // Deprecated + + fromWorkingColorSpace: function ( color, targetColorSpace ) { + + warnOnce( 'ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace().' ); // @deprecated, r177 + + return ColorManagement.workingToColorSpace( color, targetColorSpace ); + + }, + + toWorkingColorSpace: function ( color, sourceColorSpace ) { + + warnOnce( 'ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking().' ); // @deprecated, r177 + + return ColorManagement.colorSpaceToWorking( color, sourceColorSpace ); + + }, + + }; + + /****************************************************************************** + * sRGB definitions + */ + + const REC709_PRIMARIES = [ 0.640, 0.330, 0.300, 0.600, 0.150, 0.060 ]; + const REC709_LUMINANCE_COEFFICIENTS = [ 0.2126, 0.7152, 0.0722 ]; + const D65 = [ 0.3127, 0.3290 ]; + + ColorManagement.define( { + + [ LinearSRGBColorSpace ]: { + primaries: REC709_PRIMARIES, + whitePoint: D65, + transfer: LinearTransfer, + toXYZ: LINEAR_REC709_TO_XYZ, + fromXYZ: XYZ_TO_LINEAR_REC709, + luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS, + workingColorSpaceConfig: { unpackColorSpace: SRGBColorSpace }, + outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace } + }, + + [ SRGBColorSpace ]: { + primaries: REC709_PRIMARIES, + whitePoint: D65, + transfer: SRGBTransfer, + toXYZ: LINEAR_REC709_TO_XYZ, + fromXYZ: XYZ_TO_LINEAR_REC709, + luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS, + outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace } + }, + + } ); + + return ColorManagement; + +} + +const ColorManagement = /*@__PURE__*/ createColorManagement(); + +function SRGBToLinear( c ) { + + return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 ); + +} + +function LinearToSRGB( c ) { + + return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055; + +} + +let _canvas; + +/** + * A class containing utility functions for images. + * + * @hideconstructor + */ +class ImageUtils { + + /** + * Returns a data URI containing a representation of the given image. + * + * @param {(HTMLImageElement|HTMLCanvasElement)} image - The image object. + * @param {string} [type='image/png'] - Indicates the image format. + * @return {string} The data URI. + */ + static getDataURL( image, type = 'image/png' ) { + + if ( /^data:/i.test( image.src ) ) { + + return image.src; + + } + + if ( typeof HTMLCanvasElement === 'undefined' ) { + + return image.src; + + } + + let canvas; + + if ( image instanceof HTMLCanvasElement ) { + + canvas = image; + + } else { + + if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' ); + + _canvas.width = image.width; + _canvas.height = image.height; + + const context = _canvas.getContext( '2d' ); + + if ( image instanceof ImageData ) { + + context.putImageData( image, 0, 0 ); + + } else { + + context.drawImage( image, 0, 0, image.width, image.height ); + + } + + canvas = _canvas; + + } + + return canvas.toDataURL( type ); + + } + + /** + * Converts the given sRGB image data to linear color space. + * + * @param {(HTMLImageElement|HTMLCanvasElement|ImageBitmap|Object)} image - The image object. + * @return {HTMLCanvasElement|Object} The converted image. + */ + static sRGBToLinear( image ) { + + if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) || + ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) || + ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) { + + const canvas = createElementNS( 'canvas' ); + + canvas.width = image.width; + canvas.height = image.height; + + const context = canvas.getContext( '2d' ); + context.drawImage( image, 0, 0, image.width, image.height ); + + const imageData = context.getImageData( 0, 0, image.width, image.height ); + const data = imageData.data; + + for ( let i = 0; i < data.length; i ++ ) { + + data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255; + + } + + context.putImageData( imageData, 0, 0 ); + + return canvas; + + } else if ( image.data ) { + + const data = image.data.slice( 0 ); + + for ( let i = 0; i < data.length; i ++ ) { + + if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) { + + data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 ); + + } else { + + // assuming float + + data[ i ] = SRGBToLinear( data[ i ] ); + + } + + } + + return { + data: data, + width: image.width, + height: image.height + }; + + } else { + + warn( 'ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' ); + return image; + + } + + } + +} + +let _sourceId = 0; + +/** + * Represents the data source of a texture. + * + * The main purpose of this class is to decouple the data definition from the texture + * definition so the same data can be used with multiple texture instances. + */ +class TextureSource { + + /** + * Constructs a new texture source. + * + * @param {any} [data=null] - The data definition of a texture. + */ + constructor( data = null ) { + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isTextureSource = true; + + /** + * The ID of the source. + * + * @name TextureSource#id + * @type {number} + * @readonly + */ + Object.defineProperty( this, 'id', { value: _sourceId ++ } ); + + /** + * The UUID of the source. + * + * @type {string} + * @readonly + */ + this.uuid = generateUUID(); + + /** + * The data definition of a texture. + * + * @type {any} + */ + this.data = data; + + /** + * This property is only relevant when {@link TextureSource#needsUpdate} is set to `true` and + * provides more control on how texture data should be processed. When `dataReady` is set + * to `false`, the engine performs the memory allocation (if necessary) but does not transfer + * the data into the GPU memory. + * + * @type {boolean} + * @default true + */ + this.dataReady = true; + + /** + * This starts at `0` and counts how many times {@link TextureSource#needsUpdate} is set to `true`. + * + * @type {number} + * @readonly + * @default 0 + */ + this.version = 0; + + } + + /** + * Returns the dimensions of the source into the given target vector. + * + * @param {(Vector2|Vector3)} target - The target object the result is written into. + * @return {(Vector2|Vector3)} The dimensions of the source. + */ + getSize( target ) { + + const data = this.data; + + if ( ( typeof HTMLVideoElement !== 'undefined' ) && ( data instanceof HTMLVideoElement ) ) { + + target.set( data.videoWidth, data.videoHeight, 0 ); + + } else if ( ( typeof VideoFrame !== 'undefined' ) && ( data instanceof VideoFrame ) ) { + + target.set( data.displayWidth, data.displayHeight, 0 ); + + } else if ( data !== null ) { + + target.set( data.width, data.height, data.depth || 0 ); + + } else { + + target.set( 0, 0, 0 ); + + } + + return target; + + } + + /** + * When the property is set to `true`, the engine allocates the memory + * for the texture (if necessary) and triggers the actual texture upload + * to the GPU next time the source is used. + * + * @type {boolean} + * @default false + * @param {boolean} value + */ + set needsUpdate( value ) { + + if ( value === true ) this.version ++; + + } + + /** + * Serializes the source into JSON. + * + * @param {?(Object|string)} meta - An optional value holding meta information about the serialization. + * @return {Object} A JSON object representing the serialized source. + * @see {@link ObjectLoader#parse} + */ + toJSON( meta ) { + + const isRootObject = ( meta === undefined || typeof meta === 'string' ); + + if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) { + + return meta.images[ this.uuid ]; + + } + + const output = { + uuid: this.uuid, + url: '' + }; + + const data = this.data; + + if ( data !== null ) { + + let url; + + if ( Array.isArray( data ) ) { + + // cube texture + + url = []; + + for ( let i = 0, l = data.length; i < l; i ++ ) { + + if ( data[ i ].isDataTexture ) { + + url.push( serializeImage( data[ i ].image ) ); + + } else { + + url.push( serializeImage( data[ i ] ) ); + + } + + } + + } else { + + // texture + + url = serializeImage( data ); + + } + + output.url = url; + + } + + if ( ! isRootObject ) { + + meta.images[ this.uuid ] = output; + + } + + return output; + + } + +} + +function serializeImage( image ) { + + if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) || + ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) || + ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) { + + // default images + + return ImageUtils.getDataURL( image ); + + } else { + + if ( image.data ) { + + // images of DataTexture + + return { + data: Array.from( image.data ), + width: image.width, + height: image.height, + type: image.data.constructor.name + }; + + } else { + + warn( 'Texture: Unable to serialize Texture.' ); + return {}; + + } + + } + +} + +/** + * @deprecated since r186. Use {@link TextureSource} instead. `Source` has been renamed to `TextureSource`. + */ +class Source extends TextureSource { + + /** + * Constructs a new texture source. + * + * @param {any} [data=null] - The data definition of a texture. + * @deprecated since r186. Use {@link TextureSource} instead. + */ + constructor( data = null ) { + + warnOnce( 'Source: "Source" has been renamed to "TextureSource". Please update your code to use "THREE.TextureSource" instead.' ); // @deprecated, r186 + + super( data ); + + /** + * This flag can be used for type testing. + * + * @deprecated since r186. Use {@link TextureSource#isTextureSource} instead. + * @type {boolean} + * @readonly + * @default true + */ + this.isSource = true; + + } + +} + +let _textureId = 0; + +const _tempVec3 = /*@__PURE__*/ new Vector3(); + +/** + * Base class for all textures. + * + * Note: After the initial use of a texture, its dimensions, format, and type + * cannot be changed. Instead, call {@link Texture#dispose} on the texture and instantiate a new one. + * + * @augments EventDispatcher + */ +class Texture extends EventDispatcher { + + /** + * Constructs a new texture. + * + * @param {?Object} [image=Texture.DEFAULT_IMAGE] - The image holding the texture data. + * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping. + * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value. + * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value. + * @param {number} [magFilter=LinearFilter] - The mag filter value. + * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value. + * @param {number} [format=RGBAFormat] - The texture format. + * @param {number} [type=UnsignedByteType] - The texture type. + * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value. + * @param {string} [colorSpace=NoColorSpace] - The color space. + */ + constructor( image = Texture.DEFAULT_IMAGE, mapping = Texture.DEFAULT_MAPPING, wrapS = ClampToEdgeWrapping, wrapT = ClampToEdgeWrapping, magFilter = LinearFilter, minFilter = LinearMipmapLinearFilter, format = RGBAFormat, type = UnsignedByteType, anisotropy = Texture.DEFAULT_ANISOTROPY, colorSpace = NoColorSpace ) { + + super(); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isTexture = true; + + /** + * The ID of the texture. + * + * @name Texture#id + * @type {number} + * @readonly + */ + Object.defineProperty( this, 'id', { value: _textureId ++ } ); + + /** + * The UUID of the texture. + * + * @type {string} + * @readonly + */ + this.uuid = generateUUID(); + + /** + * The name of the texture. + * + * @type {string} + */ + this.name = ''; + + /** + * The data definition of a texture. A reference to the data source can be + * shared across textures. This is often useful in context of spritesheets + * where multiple textures render the same data but with different texture + * transformations. + * + * @type {TextureSource} + */ + this.source = new TextureSource( image ); + + /** + * An array holding user-defined mipmaps. + * + * @type {Array} + */ + this.mipmaps = []; + + /** + * How the texture is applied to the object. The value `UVMapping` + * is the default, where texture or uv coordinates are used to apply the map. + * + * @type {(UVMapping|CubeReflectionMapping|CubeRefractionMapping|EquirectangularReflectionMapping|EquirectangularRefractionMapping|CubeUVReflectionMapping)} + * @default UVMapping + */ + this.mapping = mapping; + + /** + * Lets you select the uv attribute to map the texture to. `0` for `uv`, + * `1` for `uv1`, `2` for `uv2` and `3` for `uv3`. + * + * @type {number} + * @default 0 + */ + this.channel = 0; + + /** + * This defines how the texture is wrapped horizontally and corresponds to + * *U* in UV mapping. + * + * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)} + * @default ClampToEdgeWrapping + */ + this.wrapS = wrapS; + + /** + * This defines how the texture is wrapped horizontally and corresponds to + * *V* in UV mapping. + * + * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)} + * @default ClampToEdgeWrapping + */ + this.wrapT = wrapT; + + /** + * How the texture is sampled when a texel covers more than one pixel. + * + * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)} + * @default LinearFilter + */ + this.magFilter = magFilter; + + /** + * How the texture is sampled when a texel covers less than one pixel. + * + * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)} + * @default LinearMipmapLinearFilter + */ + this.minFilter = minFilter; + + /** + * The number of samples taken along the axis through the pixel that has the + * highest density of texels. By default, this value is `1`. A higher value + * gives a less blurry result than a basic mipmap, at the cost of more + * texture samples being used. + * + * @type {number} + * @default Texture.DEFAULT_ANISOTROPY + */ + this.anisotropy = anisotropy; + + /** + * The format of the texture. + * + * @type {number} + * @default RGBAFormat + */ + this.format = format; + + /** + * The default internal format is derived from {@link Texture#format} and {@link Texture#type} and + * defines how the texture data is going to be stored on the GPU. + * + * This property allows to overwrite the default format. + * + * @type {?string} + * @default null + */ + this.internalFormat = null; + + /** + * The data type of the texture. + * + * @type {number} + * @default UnsignedByteType + */ + this.type = type; + + /** + * How much a single repetition of the texture is offset from the beginning, + * in each direction U and V. Typical range is `0.0` to `1.0`. + * + * @type {Vector2} + * @default (0,0) + */ + this.offset = new Vector2( 0, 0 ); + + /** + * How many times the texture is repeated across the surface, in each + * direction U and V. If repeat is set greater than `1` in either direction, + * the corresponding wrap parameter should also be set to `RepeatWrapping` + * or `MirroredRepeatWrapping` to achieve the desired tiling effect. + * + * @type {Vector2} + * @default (1,1) + */ + this.repeat = new Vector2( 1, 1 ); + + /** + * The point around which rotation occurs. A value of `(0.5, 0.5)` corresponds + * to the center of the texture. Default is `(0, 0)`, the lower left. + * + * @type {Vector2} + * @default (0,0) + */ + this.center = new Vector2( 0, 0 ); + + /** + * How much the texture is rotated around the center point, in radians. + * Positive values are counter-clockwise. + * + * @type {number} + * @default 0 + */ + this.rotation = 0; + + /** + * Whether to update the texture's uv-transformation {@link Texture#matrix} + * from the properties {@link Texture#offset}, {@link Texture#repeat}, + * {@link Texture#rotation}, and {@link Texture#center}. + * + * Set this to `false` if you are specifying the uv-transform matrix directly. + * + * @type {boolean} + * @default true + */ + this.matrixAutoUpdate = true; + + /** + * The uv-transformation matrix of the texture. + * + * @type {Matrix3} + */ + this.matrix = new Matrix3(); + + /** + * Whether to generate mipmaps (if possible) for a texture. + * + * Set this to `false` if you are creating mipmaps manually. + * + * @type {boolean} + * @default true + */ + this.generateMipmaps = true; + + /** + * If set to `true`, the alpha channel, if present, is multiplied into the + * color channels when the texture is uploaded to the GPU. + * + * Note that this property has no effect when using `ImageBitmap`. You need to + * configure premultiply alpha on bitmap creation instead. + * + * @type {boolean} + * @default false + */ + this.premultiplyAlpha = false; + + /** + * If set to `true`, the texture is flipped along the vertical axis when + * uploaded to the GPU. + * + * Note that this property has no effect when using `ImageBitmap`. You need to + * configure the flip on bitmap creation instead. + * + * @type {boolean} + * @default true + */ + this.flipY = true; + + /** + * Specifies the alignment requirements for the start of each pixel row in memory. + * The allowable values are `1` (byte-alignment), `2` (rows aligned to even-numbered bytes), + * `4` (word-alignment), and `8` (rows start on double-word boundaries). + * + * @type {number} + * @default 4 + */ + this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml) + + /** + * Textures containing color data should be annotated with `SRGBColorSpace` or `LinearSRGBColorSpace`. + * + * @type {string} + * @default NoColorSpace + */ + this.colorSpace = colorSpace; + + /** + * An object that can be used to store custom data about the texture. It + * should not hold references to functions as these will not be cloned. + * + * @type {Object} + */ + this.userData = {}; + + /** + * This can be used to only update a subregion or specific rows of the texture (for example, just the + * first 3 rows). Use the `addUpdateRange()` function to add ranges to this array. + * + * @type {Array} + */ + this.updateRanges = []; + + /** + * This starts at `0` and counts how many times {@link Texture#needsUpdate} is set to `true`. + * + * @type {number} + * @readonly + * @default 0 + */ + this.version = 0; + + /** + * A callback function, called when the texture is updated (e.g., when + * {@link Texture#needsUpdate} has been set to true and then the texture is used). + * + * @type {?Function} + * @default null + */ + this.onUpdate = null; + + /** + * An optional back reference to the textures render target. + * + * @type {?(RenderTarget|WebGLRenderTarget)} + * @default null + */ + this.renderTarget = null; + + /** + * Indicates whether a texture belongs to a render target or not. + * + * @type {boolean} + * @readonly + * @default false + */ + this.isRenderTargetTexture = false; + + /** + * Indicates if a texture should be handled like a texture array. + * + * @type {boolean} + * @readonly + * @default false + */ + this.isArrayTexture = image && image.depth && image.depth > 1 ? true : false; + + /** + * Indicates whether this texture should be processed by `PMREMGenerator` or not + * (only relevant for render target textures). + * + * @type {number} + * @readonly + * @default 0 + */ + this.pmremVersion = 0; + + /** + * Whether the texture should use one of the 16 bit integer formats which are normalized + * to [0, 1] or [-1, 1] (depending on signed/unsigned) when sampled. + * + * @type {boolean} + * @default false + */ + this.normalized = false; + + } + + /** + * The width of the texture in pixels. + */ + get width() { + + return this.source.getSize( _tempVec3 ).x; + + } + + /** + * The height of the texture in pixels. + */ + get height() { + + return this.source.getSize( _tempVec3 ).y; + + } + + /** + * The depth of the texture in pixels. + */ + get depth() { + + return this.source.getSize( _tempVec3 ).z; + + } + + /** + * The image object holding the texture data. + * + * @type {?Object} + */ + get image() { + + return this.source.data; + + } + + set image( value ) { + + this.source.data = value; + + } + + /** + * Updates the texture transformation matrix from the properties {@link Texture#offset}, + * {@link Texture#repeat}, {@link Texture#rotation}, and {@link Texture#center}. + */ + updateMatrix() { + + this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y ); + + } + + /** + * Adds a range of data in the data texture to be updated on the GPU. + * + * @param {number} start - Position at which to start update. + * @param {number} count - The number of components to update. + */ + addUpdateRange( start, count ) { + + this.updateRanges.push( { start, count } ); + + } + + /** + * Clears the update ranges. + */ + clearUpdateRanges() { + + this.updateRanges.length = 0; + + } + + /** + * Returns a new texture with copied values from this instance. + * + * @return {Texture} A clone of this instance. + */ + clone() { + + return new this.constructor().copy( this ); + + } + + /** + * Copies the values of the given texture to this instance. + * + * @param {Texture} source - The texture to copy. + * @return {Texture} A reference to this instance. + */ + copy( source ) { + + this.name = source.name; + + this.source = source.source; + this.mipmaps = source.mipmaps.slice( 0 ); + + this.mapping = source.mapping; + this.channel = source.channel; + + this.wrapS = source.wrapS; + this.wrapT = source.wrapT; + + this.magFilter = source.magFilter; + this.minFilter = source.minFilter; + + this.anisotropy = source.anisotropy; + + this.format = source.format; + this.internalFormat = source.internalFormat; + this.type = source.type; + this.normalized = source.normalized; + + this.offset.copy( source.offset ); + this.repeat.copy( source.repeat ); + this.center.copy( source.center ); + this.rotation = source.rotation; + + this.matrixAutoUpdate = source.matrixAutoUpdate; + this.matrix.copy( source.matrix ); + + this.generateMipmaps = source.generateMipmaps; + this.premultiplyAlpha = source.premultiplyAlpha; + this.flipY = source.flipY; + this.unpackAlignment = source.unpackAlignment; + this.colorSpace = source.colorSpace; + + this.renderTarget = source.renderTarget; + this.isRenderTargetTexture = source.isRenderTargetTexture; + this.isArrayTexture = source.isArrayTexture; + + this.userData = JSON.parse( JSON.stringify( source.userData ) ); + + this.needsUpdate = true; + + return this; + + } + + /** + * Sets this texture's properties based on `values`. + * @param {Object} values - A container with texture parameters. + */ + setValues( values ) { + + for ( const key in values ) { + + const newValue = values[ key ]; + + if ( newValue === undefined ) { + + warn( `Texture.setValues(): parameter '${ key }' has value of undefined.` ); + continue; + + } + + const currentValue = this[ key ]; + + if ( currentValue === undefined ) { + + warn( `Texture.setValues(): property '${ key }' does not exist.` ); + continue; + + } + + if ( ( currentValue && newValue ) && ( currentValue.isVector2 && newValue.isVector2 ) ) { + + currentValue.copy( newValue ); + + } else if ( ( currentValue && newValue ) && ( currentValue.isVector3 && newValue.isVector3 ) ) { + + currentValue.copy( newValue ); + + } else if ( ( currentValue && newValue ) && ( currentValue.isMatrix3 && newValue.isMatrix3 ) ) { + + currentValue.copy( newValue ); + + } else { + + this[ key ] = newValue; + + } + + } + + } + + /** + * Serializes the texture into JSON. + * + * @param {?(Object|string)} meta - An optional value holding meta information about the serialization. + * @return {Object} A JSON object representing the serialized texture. + * @see {@link ObjectLoader#parse} + */ + toJSON( meta ) { + + const isRootObject = ( meta === undefined || typeof meta === 'string' ); + + if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) { + + return meta.textures[ this.uuid ]; + + } + + const output = { + + metadata: { + version: 4.7, + type: 'Texture', + generator: 'Texture.toJSON' + }, + + uuid: this.uuid, + name: this.name, + + image: this.source.toJSON( meta ).uuid, + + mapping: this.mapping, + channel: this.channel, + + repeat: [ this.repeat.x, this.repeat.y ], + offset: [ this.offset.x, this.offset.y ], + center: [ this.center.x, this.center.y ], + rotation: this.rotation, + + wrap: [ this.wrapS, this.wrapT ], + + format: this.format, + internalFormat: this.internalFormat, + type: this.type, + normalized: this.normalized, + colorSpace: this.colorSpace, + + minFilter: this.minFilter, + magFilter: this.magFilter, + anisotropy: this.anisotropy, + + flipY: this.flipY, + + generateMipmaps: this.generateMipmaps, + premultiplyAlpha: this.premultiplyAlpha, + unpackAlignment: this.unpackAlignment + + }; + + if ( Object.keys( this.userData ).length > 0 ) output.userData = this.userData; + + if ( ! isRootObject ) { + + meta.textures[ this.uuid ] = output; + + } + + return output; + + } + + /** + * Frees the GPU-related resources allocated by this instance. Call this + * method whenever this instance is no longer used in your app. + * + * @fires Texture#dispose + */ + dispose() { + + /** + * Fires when the texture has been disposed of. + * + * @event Texture#dispose + * @type {Object} + */ + this.dispatchEvent( { type: 'dispose' } ); + + } + + /** + * Transforms the given uv vector with the textures uv transformation matrix. + * + * @param {Vector2} uv - The uv vector. + * @return {Vector2} The transformed uv vector. + */ + transformUv( uv ) { + + if ( this.mapping !== UVMapping ) return uv; + + uv.applyMatrix3( this.matrix ); + + if ( uv.x < 0 || uv.x > 1 ) { + + switch ( this.wrapS ) { + + case RepeatWrapping: + + uv.x = uv.x - Math.floor( uv.x ); + break; + + case ClampToEdgeWrapping: + + uv.x = uv.x < 0 ? 0 : 1; + break; + + case MirroredRepeatWrapping: + + if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) { + + uv.x = Math.ceil( uv.x ) - uv.x; + + } else { + + uv.x = uv.x - Math.floor( uv.x ); + + } + + break; + + } + + } + + if ( uv.y < 0 || uv.y > 1 ) { + + switch ( this.wrapT ) { + + case RepeatWrapping: + + uv.y = uv.y - Math.floor( uv.y ); + break; + + case ClampToEdgeWrapping: + + uv.y = uv.y < 0 ? 0 : 1; + break; + + case MirroredRepeatWrapping: + + if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) { + + uv.y = Math.ceil( uv.y ) - uv.y; + + } else { + + uv.y = uv.y - Math.floor( uv.y ); + + } + + break; + + } + + } + + if ( this.flipY ) { + + uv.y = 1 - uv.y; + + } + + return uv; + + } + + /** + * Setting this property to `true` indicates the engine the texture + * must be updated in the next render. This triggers a texture upload + * to the GPU and ensures correct texture parameter configuration. + * + * @type {boolean} + * @default false + * @param {boolean} value + */ + set needsUpdate( value ) { + + if ( value === true ) { + + this.version ++; + this.source.needsUpdate = true; + + } + + } + + /** + * Setting this property to `true` indicates the engine the PMREM + * must be regenerated. + * + * @type {boolean} + * @default false + * @param {boolean} value + */ + set needsPMREMUpdate( value ) { + + if ( value === true ) { + + this.pmremVersion ++; + + } + + } + +} + +/** + * The default image for all textures. + * + * @static + * @type {?Image} + * @default null + */ +Texture.DEFAULT_IMAGE = null; + +/** + * The default mapping for all textures. + * + * @static + * @type {number} + * @default UVMapping + */ +Texture.DEFAULT_MAPPING = UVMapping; + +/** + * The default anisotropy value for all textures. + * + * @static + * @type {number} + * @default 1 + */ +Texture.DEFAULT_ANISOTROPY = 1; + +/** + * Class representing a 4D vector. A 4D vector is an ordered quadruplet of numbers + * (labeled x, y, z and w), which can be used to represent a number of things, such as: + * + * - A point in 4D space. + * - A direction and length in 4D space. In three.js the length will + * always be the Euclidean distance(straight-line distance) from `(0, 0, 0, 0)` to `(x, y, z, w)` + * and the direction is also measured from `(0, 0, 0, 0)` towards `(x, y, z, w)`. + * - Any arbitrary ordered quadruplet of numbers. + * + * There are other things a 4D vector can be used to represent, however these + * are the most common uses in *three.js*. + * + * Iterating through a vector instance will yield its components `(x, y, z, w)` in + * the corresponding order. + * ```js + * const a = new THREE.Vector4( 0, 1, 0, 0 ); + * + * //no arguments; will be initialised to (0, 0, 0, 1) + * const b = new THREE.Vector4( ); + * + * const d = a.dot( b ); + * ``` + */ +class Vector4 { + + static { + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + Vector4.prototype.isVector4 = true; + + } + + /** + * Constructs a new 4D vector. + * + * @param {number} [x=0] - The x value of this vector. + * @param {number} [y=0] - The y value of this vector. + * @param {number} [z=0] - The z value of this vector. + * @param {number} [w=1] - The w value of this vector. + */ + constructor( x = 0, y = 0, z = 0, w = 1 ) { + + /** + * The x value of this vector. + * + * @type {number} + */ + this.x = x; + + /** + * The y value of this vector. + * + * @type {number} + */ + this.y = y; + + /** + * The z value of this vector. + * + * @type {number} + */ + this.z = z; + + /** + * The w value of this vector. + * + * @type {number} + */ + this.w = w; + + } + + /** + * Alias for {@link Vector4#z}. + * + * @type {number} + */ + get width() { + + return this.z; + + } + + set width( value ) { + + this.z = value; + + } + + /** + * Alias for {@link Vector4#w}. + * + * @type {number} + */ + get height() { + + return this.w; + + } + + set height( value ) { + + this.w = value; + + } + + /** + * Sets the vector components. + * + * @param {number} x - The value of the x component. + * @param {number} y - The value of the y component. + * @param {number} z - The value of the z component. + * @param {number} w - The value of the w component. + * @return {Vector4} A reference to this vector. + */ + set( x, y, z, w ) { + + this.x = x; + this.y = y; + this.z = z; + this.w = w; + + return this; + + } + + /** + * Sets the vector components to the same value. + * + * @param {number} scalar - The value to set for all vector components. + * @return {Vector4} A reference to this vector. + */ + setScalar( scalar ) { + + this.x = scalar; + this.y = scalar; + this.z = scalar; + this.w = scalar; + + return this; + + } + + /** + * Sets the vector's x component to the given value + * + * @param {number} x - The value to set. + * @return {Vector4} A reference to this vector. + */ + setX( x ) { + + this.x = x; + + return this; + + } + + /** + * Sets the vector's y component to the given value + * + * @param {number} y - The value to set. + * @return {Vector4} A reference to this vector. + */ + setY( y ) { + + this.y = y; + + return this; + + } + + /** + * Sets the vector's z component to the given value + * + * @param {number} z - The value to set. + * @return {Vector4} A reference to this vector. + */ + setZ( z ) { + + this.z = z; + + return this; + + } + + /** + * Sets the vector's w component to the given value + * + * @param {number} w - The value to set. + * @return {Vector4} A reference to this vector. + */ + setW( w ) { + + this.w = w; + + return this; + + } + + /** + * Allows to set a vector component with an index. + * + * @param {number} index - The component index. `0` equals to x, `1` equals to y, + * `2` equals to z, `3` equals to w. + * @param {number} value - The value to set. + * @return {Vector4} A reference to this vector. + */ + setComponent( index, value ) { + + switch ( index ) { + + case 0: this.x = value; break; + case 1: this.y = value; break; + case 2: this.z = value; break; + case 3: this.w = value; break; + default: throw new Error( 'THREE.Vector4: index is out of range: ' + index ); + + } + + return this; + + } + + /** + * Returns the value of the vector component which matches the given index. + * + * @param {number} index - The component index. `0` equals to x, `1` equals to y, + * `2` equals to z, `3` equals to w. + * @return {number} A vector component value. + */ + getComponent( index ) { + + switch ( index ) { + + case 0: return this.x; + case 1: return this.y; + case 2: return this.z; + case 3: return this.w; + default: throw new Error( 'THREE.Vector4: index is out of range: ' + index ); + + } + + } + + /** + * Returns a new vector with copied values from this instance. + * + * @return {Vector4} A clone of this instance. + */ + clone() { + + return new this.constructor( this.x, this.y, this.z, this.w ); + + } + + /** + * Copies the values of the given vector to this instance. + * + * @param {Vector3|Vector4} v - The vector to copy. + * @return {Vector4} A reference to this vector. + */ + copy( v ) { + + this.x = v.x; + this.y = v.y; + this.z = v.z; + this.w = ( v.w !== undefined ) ? v.w : 1; + + return this; + + } + + /** + * Adds the given vector to this instance. + * + * @param {Vector4} v - The vector to add. + * @return {Vector4} A reference to this vector. + */ + add( v ) { + + this.x += v.x; + this.y += v.y; + this.z += v.z; + this.w += v.w; + + return this; + + } + + /** + * Adds the given scalar value to all components of this instance. + * + * @param {number} s - The scalar to add. + * @return {Vector4} A reference to this vector. + */ + addScalar( s ) { + + this.x += s; + this.y += s; + this.z += s; + this.w += s; + + return this; + + } + + /** + * Adds the given vectors and stores the result in this instance. + * + * @param {Vector4} a - The first vector. + * @param {Vector4} b - The second vector. + * @return {Vector4} A reference to this vector. + */ + addVectors( a, b ) { + + this.x = a.x + b.x; + this.y = a.y + b.y; + this.z = a.z + b.z; + this.w = a.w + b.w; + + return this; + + } + + /** + * Adds the given vector scaled by the given factor to this instance. + * + * @param {Vector4} v - The vector. + * @param {number} s - The factor that scales `v`. + * @return {Vector4} A reference to this vector. + */ + addScaledVector( v, s ) { + + this.x += v.x * s; + this.y += v.y * s; + this.z += v.z * s; + this.w += v.w * s; + + return this; + + } + + /** + * Subtracts the given vector from this instance. + * + * @param {Vector4} v - The vector to subtract. + * @return {Vector4} A reference to this vector. + */ + sub( v ) { + + this.x -= v.x; + this.y -= v.y; + this.z -= v.z; + this.w -= v.w; + + return this; + + } + + /** + * Subtracts the given scalar value from all components of this instance. + * + * @param {number} s - The scalar to subtract. + * @return {Vector4} A reference to this vector. + */ + subScalar( s ) { + + this.x -= s; + this.y -= s; + this.z -= s; + this.w -= s; + + return this; + + } + + /** + * Subtracts the given vectors and stores the result in this instance. + * + * @param {Vector4} a - The first vector. + * @param {Vector4} b - The second vector. + * @return {Vector4} A reference to this vector. + */ + subVectors( a, b ) { + + this.x = a.x - b.x; + this.y = a.y - b.y; + this.z = a.z - b.z; + this.w = a.w - b.w; + + return this; + + } + + /** + * Multiplies the given vector with this instance. + * + * @param {Vector4} v - The vector to multiply. + * @return {Vector4} A reference to this vector. + */ + multiply( v ) { + + this.x *= v.x; + this.y *= v.y; + this.z *= v.z; + this.w *= v.w; + + return this; + + } + + /** + * Multiplies the given scalar value with all components of this instance. + * + * @param {number} scalar - The scalar to multiply. + * @return {Vector4} A reference to this vector. + */ + multiplyScalar( scalar ) { + + this.x *= scalar; + this.y *= scalar; + this.z *= scalar; + this.w *= scalar; + + return this; + + } + + /** + * Multiplies this vector with the given 4x4 matrix. + * + * @param {Matrix4} m - The 4x4 matrix. + * @return {Vector4} A reference to this vector. + */ + applyMatrix4( m ) { + + const x = this.x, y = this.y, z = this.z, w = this.w; + const e = m.elements; + + this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w; + this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w; + this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w; + this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w; + + return this; + + } + + /** + * Divides this instance by the given vector. + * + * @param {Vector4} v - The vector to divide. + * @return {Vector4} A reference to this vector. + */ + divide( v ) { + + this.x /= v.x; + this.y /= v.y; + this.z /= v.z; + this.w /= v.w; + + return this; + + } + + /** + * Divides this vector by the given scalar. + * + * @param {number} scalar - The scalar to divide. + * @return {Vector4} A reference to this vector. + */ + divideScalar( scalar ) { + + return this.multiplyScalar( 1 / scalar ); + + } + + /** + * Sets the x, y and z components of this + * vector to the quaternion's axis and w to the angle. + * + * @param {Quaternion} q - The Quaternion to set. + * @return {Vector4} A reference to this vector. + */ + setAxisAngleFromQuaternion( q ) { + + // q is assumed to be normalized + + this.w = 2 * Math.acos( q.w ); + + const s = Math.sqrt( 1 - q.w * q.w ); + + if ( s < 0.0001 ) { + + this.x = 1; + this.y = 0; + this.z = 0; + + } else { + + this.x = q.x / s; + this.y = q.y / s; + this.z = q.z / s; + + } + + return this; + + } + + /** + * Sets the x, y and z components of this + * vector to the axis of rotation and w to the angle. + * + * @param {Matrix4} m - A 4x4 matrix of which the upper left 3x3 matrix is a pure rotation matrix. + * @return {Vector4} A reference to this vector. + */ + setAxisAngleFromRotationMatrix( m ) { + + // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) + + let angle, x, y, z; // variables for result + const epsilon = 0.01, // margin to allow for rounding errors + epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees + + te = m.elements, + + m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ], + m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ], + m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ]; + + if ( ( Math.abs( m12 - m21 ) < epsilon ) && + ( Math.abs( m13 - m31 ) < epsilon ) && + ( Math.abs( m23 - m32 ) < epsilon ) ) { + + // singularity found + // first check for identity matrix which must have +1 for all terms + // in leading diagonal and zero in other terms + + if ( ( Math.abs( m12 + m21 ) < epsilon2 ) && + ( Math.abs( m13 + m31 ) < epsilon2 ) && + ( Math.abs( m23 + m32 ) < epsilon2 ) && + ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) { + + // this singularity is identity matrix so angle = 0 + + this.set( 1, 0, 0, 0 ); + + return this; // zero angle, arbitrary axis + + } + + // otherwise this singularity is angle = 180 + + angle = Math.PI; + + const xx = ( m11 + 1 ) / 2; + const yy = ( m22 + 1 ) / 2; + const zz = ( m33 + 1 ) / 2; + const xy = ( m12 + m21 ) / 4; + const xz = ( m13 + m31 ) / 4; + const yz = ( m23 + m32 ) / 4; + + if ( ( xx > yy ) && ( xx > zz ) ) { + + // m11 is the largest diagonal term + + if ( xx < epsilon ) { + + x = 0; + y = 0.707106781; + z = 0.707106781; + + } else { + + x = Math.sqrt( xx ); + y = xy / x; + z = xz / x; + + } + + } else if ( yy > zz ) { + + // m22 is the largest diagonal term + + if ( yy < epsilon ) { + + x = 0.707106781; + y = 0; + z = 0.707106781; + + } else { + + y = Math.sqrt( yy ); + x = xy / y; + z = yz / y; + + } + + } else { + + // m33 is the largest diagonal term so base result on this + + if ( zz < epsilon ) { + + x = 0.707106781; + y = 0.707106781; + z = 0; + + } else { + + z = Math.sqrt( zz ); + x = xz / z; + y = yz / z; + + } + + } + + this.set( x, y, z, angle ); + + return this; // return 180 deg rotation + + } + + // as we have reached here there are no singularities so we can handle normally + + let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) + + ( m13 - m31 ) * ( m13 - m31 ) + + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize + + if ( Math.abs( s ) < 0.001 ) s = 1; + + // prevent divide by zero, should not happen if matrix is orthogonal and should be + // caught by singularity test above, but I've left it in just in case + + this.x = ( m32 - m23 ) / s; + this.y = ( m13 - m31 ) / s; + this.z = ( m21 - m12 ) / s; + this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 ); + + return this; + + } + + /** + * Sets the vector components to the position elements of the + * given transformation matrix. + * + * @param {Matrix4} m - The 4x4 matrix. + * @return {Vector4} A reference to this vector. + */ + setFromMatrixPosition( m ) { + + const e = m.elements; + + this.x = e[ 12 ]; + this.y = e[ 13 ]; + this.z = e[ 14 ]; + this.w = e[ 15 ]; + + return this; + + } + + /** + * If this vector's x, y, z or w value is greater than the given vector's x, y, z or w + * value, replace that value with the corresponding min value. + * + * @param {Vector4} v - The vector. + * @return {Vector4} A reference to this vector. + */ + min( v ) { + + this.x = Math.min( this.x, v.x ); + this.y = Math.min( this.y, v.y ); + this.z = Math.min( this.z, v.z ); + this.w = Math.min( this.w, v.w ); + + return this; + + } + + /** + * If this vector's x, y, z or w value is less than the given vector's x, y, z or w + * value, replace that value with the corresponding max value. + * + * @param {Vector4} v - The vector. + * @return {Vector4} A reference to this vector. + */ + max( v ) { + + this.x = Math.max( this.x, v.x ); + this.y = Math.max( this.y, v.y ); + this.z = Math.max( this.z, v.z ); + this.w = Math.max( this.w, v.w ); + + return this; + + } + + /** + * If this vector's x, y, z or w value is greater than the max vector's x, y, z or w + * value, it is replaced by the corresponding value. + * If this vector's x, y, z or w value is less than the min vector's x, y, z or w value, + * it is replaced by the corresponding value. + * + * @param {Vector4} min - The minimum x, y and z values. + * @param {Vector4} max - The maximum x, y and z values in the desired range. + * @return {Vector4} A reference to this vector. + */ + clamp( min, max ) { + + // assumes min < max, componentwise + + this.x = clamp( this.x, min.x, max.x ); + this.y = clamp( this.y, min.y, max.y ); + this.z = clamp( this.z, min.z, max.z ); + this.w = clamp( this.w, min.w, max.w ); + + return this; + + } + + /** + * If this vector's x, y, z or w values are greater than the max value, they are + * replaced by the max value. + * If this vector's x, y, z or w values are less than the min value, they are + * replaced by the min value. + * + * @param {number} minVal - The minimum value the components will be clamped to. + * @param {number} maxVal - The maximum value the components will be clamped to. + * @return {Vector4} A reference to this vector. + */ + clampScalar( minVal, maxVal ) { + + this.x = clamp( this.x, minVal, maxVal ); + this.y = clamp( this.y, minVal, maxVal ); + this.z = clamp( this.z, minVal, maxVal ); + this.w = clamp( this.w, minVal, maxVal ); + + return this; + + } + + /** + * If this vector's length is greater than the max value, it is replaced by + * the max value. + * If this vector's length is less than the min value, it is replaced by the + * min value. + * + * @param {number} min - The minimum value the vector length will be clamped to. + * @param {number} max - The maximum value the vector length will be clamped to. + * @return {Vector4} A reference to this vector. + */ + clampLength( min, max ) { + + const length = this.length(); + + return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) ); + + } + + /** + * The components of this vector are rounded down to the nearest integer value. + * + * @return {Vector4} A reference to this vector. + */ + floor() { + + this.x = Math.floor( this.x ); + this.y = Math.floor( this.y ); + this.z = Math.floor( this.z ); + this.w = Math.floor( this.w ); + + return this; + + } + + /** + * The components of this vector are rounded up to the nearest integer value. + * + * @return {Vector4} A reference to this vector. + */ + ceil() { + + this.x = Math.ceil( this.x ); + this.y = Math.ceil( this.y ); + this.z = Math.ceil( this.z ); + this.w = Math.ceil( this.w ); + + return this; + + } + + /** + * The components of this vector are rounded to the nearest integer value + * + * @return {Vector4} A reference to this vector. + */ + round() { + + this.x = Math.round( this.x ); + this.y = Math.round( this.y ); + this.z = Math.round( this.z ); + this.w = Math.round( this.w ); + + return this; + + } + + /** + * The components of this vector are rounded towards zero (up if negative, + * down if positive) to an integer value. + * + * @return {Vector4} A reference to this vector. + */ + roundToZero() { + + this.x = Math.trunc( this.x ); + this.y = Math.trunc( this.y ); + this.z = Math.trunc( this.z ); + this.w = Math.trunc( this.w ); + + return this; + + } + + /** + * Inverts this vector - i.e. sets x = -x, y = -y, z = -z, w = -w. + * + * @return {Vector4} A reference to this vector. + */ + negate() { + + this.x = - this.x; + this.y = - this.y; + this.z = - this.z; + this.w = - this.w; + + return this; + + } + + /** + * Calculates the dot product of the given vector with this instance. + * + * @param {Vector4} v - The vector to compute the dot product with. + * @return {number} The result of the dot product. + */ + dot( v ) { + + return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w; + + } + + /** + * Computes the square of the Euclidean length (straight-line length) from + * (0, 0, 0, 0) to (x, y, z, w). If you are comparing the lengths of vectors, you should + * compare the length squared instead as it is slightly more efficient to calculate. + * + * @return {number} The square length of this vector. + */ + lengthSq() { + + return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w; + + } + + /** + * Computes the Euclidean length (straight-line length) from (0, 0, 0, 0) to (x, y, z, w). + * + * @return {number} The length of this vector. + */ + length() { + + return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w ); + + } + + /** + * Computes the Manhattan length of this vector. + * + * @return {number} The length of this vector. + */ + manhattanLength() { + + return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w ); + + } + + /** + * Converts this vector to a unit vector - that is, sets it equal to a vector + * with the same direction as this one, but with a vector length of `1`. + * + * @return {Vector4} A reference to this vector. + */ + normalize() { + + return this.divideScalar( this.length() || 1 ); + + } + + /** + * Sets this vector to a vector with the same direction as this one, but + * with the specified length. + * + * @param {number} length - The new length of this vector. + * @return {Vector4} A reference to this vector. + */ + setLength( length ) { + + return this.normalize().multiplyScalar( length ); + + } + + /** + * Linearly interpolates between the given vector and this instance, where + * alpha is the percent distance along the line - alpha = 0 will be this + * vector, and alpha = 1 will be the given one. + * + * @param {Vector4} v - The vector to interpolate towards. + * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`. + * @return {Vector4} A reference to this vector. + */ + lerp( v, alpha ) { + + this.x += ( v.x - this.x ) * alpha; + this.y += ( v.y - this.y ) * alpha; + this.z += ( v.z - this.z ) * alpha; + this.w += ( v.w - this.w ) * alpha; + + return this; + + } + + /** + * Linearly interpolates between the given vectors, where alpha is the percent + * distance along the line - alpha = 0 will be first vector, and alpha = 1 will + * be the second one. The result is stored in this instance. + * + * @param {Vector4} v1 - The first vector. + * @param {Vector4} v2 - The second vector. + * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`. + * @return {Vector4} A reference to this vector. + */ + lerpVectors( v1, v2, alpha ) { + + this.x = v1.x + ( v2.x - v1.x ) * alpha; + this.y = v1.y + ( v2.y - v1.y ) * alpha; + this.z = v1.z + ( v2.z - v1.z ) * alpha; + this.w = v1.w + ( v2.w - v1.w ) * alpha; + + return this; + + } + + /** + * Returns `true` if this vector is equal with the given one. + * + * @param {Vector4} v - The vector to test for equality. + * @return {boolean} Whether this vector is equal with the given one. + */ + equals( v ) { + + return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) ); + + } + + /** + * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]`, + * z value to be `array[ offset + 2 ]`, w value to be `array[ offset + 3 ]`. + * + * @param {Array} array - An array holding the vector component values. + * @param {number} [offset=0] - The offset into the array. + * @return {Vector4} A reference to this vector. + */ + fromArray( array, offset = 0 ) { + + this.x = array[ offset ]; + this.y = array[ offset + 1 ]; + this.z = array[ offset + 2 ]; + this.w = array[ offset + 3 ]; + + return this; + + } + + /** + * Writes the components of this vector to the given array. If no array is provided, + * the method returns a new instance. + * + * @param {Array} [array=[]] - The target array holding the vector components. + * @param {number} [offset=0] - Index of the first element in the array. + * @return {Array} The vector components. + */ + toArray( array = [], offset = 0 ) { + + array[ offset ] = this.x; + array[ offset + 1 ] = this.y; + array[ offset + 2 ] = this.z; + array[ offset + 3 ] = this.w; + + return array; + + } + + /** + * Sets the components of this vector from the given buffer attribute. + * + * @param {BufferAttribute} attribute - The buffer attribute holding vector data. + * @param {number} index - The index into the attribute. + * @return {Vector4} A reference to this vector. + */ + fromBufferAttribute( attribute, index ) { + + this.x = attribute.getX( index ); + this.y = attribute.getY( index ); + this.z = attribute.getZ( index ); + this.w = attribute.getW( index ); + + return this; + + } + + /** + * Sets each component of this vector to a pseudo-random value between `0` and + * `1`, excluding `1`. + * + * @return {Vector4} A reference to this vector. + */ + random() { + + this.x = Math.random(); + this.y = Math.random(); + this.z = Math.random(); + this.w = Math.random(); + + return this; + + } + + *[ Symbol.iterator ]() { + + yield this.x; + yield this.y; + yield this.z; + yield this.w; + + } + +} + +/** + * A render target is a buffer where the video card draws pixels for a scene + * that is being rendered in the background. It is used in different effects, + * such as applying postprocessing to a rendered image before displaying it + * on the screen. + * + * @augments EventDispatcher + */ +class RenderTarget extends EventDispatcher { + + /** + * Render target options. + * + * @typedef {Object} RenderTarget~Options + * @property {boolean} [generateMipmaps=false] - Whether to generate mipmaps or not. + * @property {number} [magFilter=LinearFilter] - The mag filter. + * @property {number} [minFilter=LinearFilter] - The min filter. + * @property {number} [format=RGBAFormat] - The texture format. + * @property {number} [type=UnsignedByteType] - The texture type. + * @property {?string} [internalFormat=null] - The texture's internal format. + * @property {number} [wrapS=ClampToEdgeWrapping] - The texture's uv wrapping mode. + * @property {number} [wrapT=ClampToEdgeWrapping] - The texture's uv wrapping mode. + * @property {number} [anisotropy=1] - The texture's anisotropy value. + * @property {string} [colorSpace=NoColorSpace] - The texture's color space. + * @property {boolean} [depthBuffer=true] - Whether to allocate a depth buffer or not. + * @property {boolean} [stencilBuffer=false] - Whether to allocate a stencil buffer or not. + * @property {boolean} [resolveColorBuffer=true] - Whether to resolve the color buffer or not. Only relevant for multisampled render targets. + * @property {boolean} [resolveDepthBuffer=true] - Whether to resolve the depth buffer or not. Only relevant for multisampled render targets. + * @property {boolean} [resolveStencilBuffer=true] - Whether to resolve the stencil buffer or not. Only relevant for multisampled render targets. + * @property {boolean} [storeMultisampledColorBuffer=true] - Whether to store the multisampled color buffer or not. Setting to `false` saves memory bandwidth when the multisampled data are not needed after a render pass. + * @property {boolean} [storeMultisampledDepthBuffer=true] - Whether to store the multisampled depth buffer or not. Setting to `false` saves memory bandwidth when the multisampled data are not needed after a render pass. + * @property {boolean} [storeMultisampledStencilBuffer=true] - Whether to store the multisampled stencil buffer or not. Setting to `false` saves memory bandwidth when the multisampled data are not needed after a render pass. + * @property {?Texture} [depthTexture=null] - Reference to a depth texture. + * @property {number} [samples=0] - The MSAA samples count. + * @property {number} [count=1] - Defines the number of color attachments . Must be at least `1`. + * @property {number} [depth=1] - The texture depth. + * @property {boolean} [multiview=false] - Whether this target is used for multiview rendering (WebGL OVR_multiview2 extension). + * @property {boolean} [useArrayDepthTexture=false] - Whether to create the depth texture as an array texture for per-layer depth testing. This is separate from multiview so layered render targets can use array depth without the multiview extension. + */ + + /** + * Constructs a new render target. + * + * @param {number} [width=1] - The width of the render target. + * @param {number} [height=1] - The height of the render target. + * @param {RenderTarget~Options} [options] - The configuration object. + */ + constructor( width = 1, height = 1, options = {} ) { + + super(); + + options = Object.assign( { + generateMipmaps: false, + internalFormat: null, + minFilter: LinearFilter, + depthBuffer: true, + stencilBuffer: false, + resolveColorBuffer: true, + resolveDepthBuffer: true, + resolveStencilBuffer: true, + storeMultisampledColorBuffer: true, + storeMultisampledDepthBuffer: true, + storeMultisampledStencilBuffer: true, + depthTexture: null, + samples: 0, + count: 1, + depth: 1, + multiview: false, + useArrayDepthTexture: false + }, options ); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isRenderTarget = true; + + /** + * The width of the render target. + * + * @type {number} + * @default 1 + */ + this.width = width; + + /** + * The height of the render target. + * + * @type {number} + * @default 1 + */ + this.height = height; + + /** + * The depth of the render target. + * + * @type {number} + * @default 1 + */ + this.depth = options.depth; + + /** + * A rectangular area inside the render target's viewport. Fragments that are + * outside the area will be discarded. + * + * @type {Vector4} + * @default (0,0,width,height) + */ + this.scissor = new Vector4( 0, 0, width, height ); + + /** + * Indicates whether the scissor test should be enabled when rendering into + * this render target or not. + * + * @type {boolean} + * @default false + */ + this.scissorTest = false; + + /** + * A rectangular area representing the render target's viewport. + * + * @type {Vector4} + * @default (0,0,width,height) + */ + this.viewport = new Vector4( 0, 0, width, height ); + + /** + * An array of textures. Each color attachment is represented as a separate texture. + * Has at least a single entry for the default color attachment. + * + * @type {Array} + */ + this.textures = []; + + const image = { width: width, height: height, depth: options.depth }; + const texture = new Texture( image ); + + const count = options.count; + for ( let i = 0; i < count; i ++ ) { + + this.textures[ i ] = texture.clone(); + this.textures[ i ].isRenderTargetTexture = true; + this.textures[ i ].renderTarget = this; + + } + + this._setTextureOptions( options ); + + /** + * Whether to allocate a depth buffer or not. + * + * @type {boolean} + * @default true + */ + this.depthBuffer = options.depthBuffer; + + /** + * Whether to allocate a stencil buffer or not. + * + * @type {boolean} + * @default false + */ + this.stencilBuffer = options.stencilBuffer; + + /** + * Whether to resolve the color buffer or not. When set to `false`, the color + * attachments do not receive the resolved (single-sampled) output of a render + * pass and the render target's textures are left untouched. The rendered + * content is then only accessible within the render pass itself. + * + * Only relevant for multisampled render targets. + * + * @type {boolean} + * @default true + */ + this.resolveColorBuffer = options.resolveColorBuffer; + + /** + * Whether to resolve the depth buffer or not. When set to `false`, the depth + * texture does not receive the resolved depth output of a render pass which + * saves memory bandwidth. Use this setting when the depth data of a render + * pass are not required afterwards. + * + * Only relevant for multisampled render targets in WebGL. WebGPU does not + * support depth resolves; sampling the depth texture of a multisampled render + * target accesses the multisampled data directly, see + * {@link RenderTarget#storeMultisampledDepthBuffer}. + * + * @type {boolean} + * @default true + */ + this.resolveDepthBuffer = options.resolveDepthBuffer; + + /** + * Whether to resolve the stencil buffer or not. Analogous to + * {@link RenderTarget#resolveDepthBuffer} but for the stencil aspect. + * + * @type {boolean} + * @default true + */ + this.resolveStencilBuffer = options.resolveStencilBuffer; + + /** + * Whether to store the multisampled color buffer or not. When set to `false`, + * the multisampled data are discarded at the end of a render pass, right after + * they have been resolved. This saves memory bandwidth, especially on tile-based + * GPUs, and is the recommended setting for render targets that are fully redrawn + * each frame and whose output is only accessed via the resolved textures (e.g. + * scene passes in post-processing chains). + * + * Must be kept `true` when the multisampled data are needed after the render + * pass ends, e.g. when rendering into the target without clearing or when the + * scene contains transmissive objects which require a mid-pass framebuffer copy. + * + * @type {boolean} + * @default true + */ + this.storeMultisampledColorBuffer = options.storeMultisampledColorBuffer; + + /** + * Whether to store the multisampled depth buffer or not. When set to `false`, + * the multisampled depth data are discarded at the end of a render pass which + * saves memory bandwidth. + * + * Must be kept `true` in WebGPU when the depth texture of a multisampled render + * target is sampled (e.g. by depth-based post-processing effects) since depth + * is read directly from the multisampled data. + * + * @type {boolean} + * @default true + */ + this.storeMultisampledDepthBuffer = options.storeMultisampledDepthBuffer; + + /** + * Whether to store the multisampled stencil buffer or not. Analogous to + * {@link RenderTarget#storeMultisampledDepthBuffer} but for the stencil aspect. + * + * @type {boolean} + * @default true + */ + this.storeMultisampledStencilBuffer = options.storeMultisampledStencilBuffer; + + this._depthTexture = null; + this.depthTexture = options.depthTexture; + + /** + * The number of MSAA samples. + * + * A value of `0` disables MSAA. + * + * @type {number} + * @default 0 + */ + this.samples = options.samples; + + /** + * Whether to this target is used in multiview rendering. + * + * @type {boolean} + * @default false + */ + this.multiview = options.multiview; + + /** + * Whether to create the depth texture as an array texture for per-layer depth testing. + * This is separate from multiview so layered render targets can use array depth without + * the multiview extension. + * + * @type {boolean} + * @default false + */ + this.useArrayDepthTexture = options.useArrayDepthTexture; + + } + + _setTextureOptions( options = {} ) { + + const values = { + minFilter: LinearFilter, + generateMipmaps: false, + flipY: false, + internalFormat: null + }; + + if ( options.mapping !== undefined ) values.mapping = options.mapping; + if ( options.wrapS !== undefined ) values.wrapS = options.wrapS; + if ( options.wrapT !== undefined ) values.wrapT = options.wrapT; + if ( options.wrapR !== undefined ) values.wrapR = options.wrapR; + if ( options.magFilter !== undefined ) values.magFilter = options.magFilter; + if ( options.minFilter !== undefined ) values.minFilter = options.minFilter; + if ( options.format !== undefined ) values.format = options.format; + if ( options.type !== undefined ) values.type = options.type; + if ( options.anisotropy !== undefined ) values.anisotropy = options.anisotropy; + if ( options.colorSpace !== undefined ) values.colorSpace = options.colorSpace; + if ( options.flipY !== undefined ) values.flipY = options.flipY; + if ( options.generateMipmaps !== undefined ) values.generateMipmaps = options.generateMipmaps; + if ( options.internalFormat !== undefined ) values.internalFormat = options.internalFormat; + + for ( let i = 0; i < this.textures.length; i ++ ) { + + const texture = this.textures[ i ]; + texture.setValues( values ); + + } + + } + + /** + * The texture representing the default color attachment. + * + * @type {Texture} + */ + get texture() { + + return this.textures[ 0 ]; + + } + + set texture( value ) { + + this.textures[ 0 ] = value; + + } + + set depthTexture( current ) { + + if ( this._depthTexture !== null && this._depthTexture.renderTarget === this ) this._depthTexture.renderTarget = null; + if ( current !== null && current.renderTarget === null ) current.renderTarget = this; + + this._depthTexture = current; + + } + + /** + * Instead of saving the depth in a renderbuffer, a texture + * can be used instead which is useful for further processing + * e.g. in context of post-processing. + * + * @type {?DepthTexture} + * @default null + */ + get depthTexture() { + + return this._depthTexture; + + } + + /** + * Sets the size of this render target. + * + * @param {number} width - The width. + * @param {number} height - The height. + * @param {number} [depth=1] - The depth. + */ + setSize( width, height, depth = 1 ) { + + if ( this.width !== width || this.height !== height || this.depth !== depth ) { + + this.width = width; + this.height = height; + this.depth = depth; + + for ( let i = 0, il = this.textures.length; i < il; i ++ ) { + + this.textures[ i ].image.width = width; + this.textures[ i ].image.height = height; + this.textures[ i ].image.depth = depth; + + if ( this.textures[ i ].isData3DTexture !== true ) { // Fix for #31693 + + // TODO: Reconsider setting isArrayTexture flag here and in the ctor of Texture. + // Maybe a method `isArrayTexture()` or just a getter could replace a flag since + // both are evaluated on each call? + + this.textures[ i ].isArrayTexture = this.textures[ i ].image.depth > 1; + + } + + } + + this.dispose(); + + } + + this.viewport.set( 0, 0, width, height ); + this.scissor.set( 0, 0, width, height ); + + } + + /** + * Returns a new render target with copied values from this instance. + * + * @return {RenderTarget} A clone of this instance. + */ + clone() { + + return new this.constructor().copy( this ); + + } + + /** + * Copies the settings of the given render target. This is a structural copy so + * no resources are shared between render targets after the copy. That includes + * all MRT textures and the depth texture. + * + * @param {RenderTarget} source - The render target to copy. + * @return {RenderTarget} A reference to this instance. + */ + copy( source ) { + + this.width = source.width; + this.height = source.height; + this.depth = source.depth; + + this.scissor.copy( source.scissor ); + this.scissorTest = source.scissorTest; + + this.viewport.copy( source.viewport ); + + this.textures.length = 0; + + for ( let i = 0, il = source.textures.length; i < il; i ++ ) { + + this.textures[ i ] = source.textures[ i ].clone(); + this.textures[ i ].isRenderTargetTexture = true; + this.textures[ i ].renderTarget = this; + + // ensure image object is not shared, see #20328 + + const image = Object.assign( {}, source.textures[ i ].image ); + this.textures[ i ].source = new TextureSource( image ); + + } + + this.depthBuffer = source.depthBuffer; + this.stencilBuffer = source.stencilBuffer; + + this.resolveColorBuffer = source.resolveColorBuffer; + this.resolveDepthBuffer = source.resolveDepthBuffer; + this.resolveStencilBuffer = source.resolveStencilBuffer; + + this.storeMultisampledColorBuffer = source.storeMultisampledColorBuffer; + this.storeMultisampledDepthBuffer = source.storeMultisampledDepthBuffer; + this.storeMultisampledStencilBuffer = source.storeMultisampledStencilBuffer; + + if ( source.depthTexture !== null ) { + + if ( source.depthTexture.renderTarget === source ) { + + const depthTexture = source.depthTexture.clone(); + depthTexture.renderTarget = null; + + this.depthTexture = depthTexture; + + } else { + + this.depthTexture = source.depthTexture; + + } + + } + + this.samples = source.samples; + this.multiview = source.multiview; + this.useArrayDepthTexture = source.useArrayDepthTexture; + + return this; + + } + + /** + * Frees the GPU-related resources allocated by this instance. Call this + * method whenever this instance is no longer used in your app. + * + * @fires RenderTarget#dispose + */ + dispose() { + + this.dispatchEvent( { type: 'dispose' } ); + + } + +} + +/** + * A render target used in context of {@link WebGLRenderer}. + * + * @augments RenderTarget + */ +class WebGLRenderTarget extends RenderTarget { + + /** + * Constructs a new 3D render target. + * + * @param {number} [width=1] - The width of the render target. + * @param {number} [height=1] - The height of the render target. + * @param {RenderTarget~Options} [options] - The configuration object. + */ + constructor( width = 1, height = 1, options = {} ) { + + super( width, height, options ); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isWebGLRenderTarget = true; + + } + +} + +/** + * Creates an array of textures directly from raw buffer data. + * + * @augments Texture + */ +class DataArrayTexture extends Texture { + + /** + * Constructs a new data array texture. + * + * @param {?TypedArray} [data=null] - The buffer data. + * @param {number} [width=1] - The width of the texture. + * @param {number} [height=1] - The height of the texture. + * @param {number} [depth=1] - The depth of the texture. + */ + constructor( data = null, width = 1, height = 1, depth = 1 ) { + + super( null ); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isDataArrayTexture = true; + + /** + * The image definition of a data texture. + * + * @type {{data:TypedArray,width:number,height:number,depth:number}} + */ + this.image = { data, width, height, depth }; + + /** + * How the texture is sampled when a texel covers more than one pixel. + * + * Overwritten and set to `NearestFilter` by default. + * + * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)} + * @default NearestFilter + */ + this.magFilter = NearestFilter; + + /** + * How the texture is sampled when a texel covers less than one pixel. + * + * Overwritten and set to `NearestFilter` by default. + * + * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)} + * @default NearestFilter + */ + this.minFilter = NearestFilter; + + /** + * This defines how the texture is wrapped in the depth and corresponds to + * *W* in UVW mapping. + * + * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)} + * @default ClampToEdgeWrapping + */ + this.wrapR = ClampToEdgeWrapping; + + /** + * Whether to generate mipmaps (if possible) for a texture. + * + * Overwritten and set to `false` by default. + * + * @type {boolean} + * @default false + */ + this.generateMipmaps = false; + + /** + * If set to `true`, the texture is flipped along the vertical axis when + * uploaded to the GPU. + * + * Overwritten and set to `false` by default. + * + * @type {boolean} + * @default false + */ + this.flipY = false; + + /** + * Specifies the alignment requirements for the start of each pixel row in memory. + * + * Overwritten and set to `1` by default. + * + * @type {boolean} + * @default 1 + */ + this.unpackAlignment = 1; + + /** + * A set of all layers which need to be updated in the texture. + * + * @type {Set} + */ + this.layerUpdates = new Set(); + + } + + /** + * Copies the values of the given texture to this instance. + * + * @param {DataArrayTexture} source - The texture to copy. + * @return {DataArrayTexture} A reference to this instance. + */ + copy( source ) { + + super.copy( source ); + + this.wrapR = source.wrapR; + + return this; + + } + + /** + * Describes that a specific layer of the texture needs to be updated. + * Normally when {@link Texture#needsUpdate} is set to `true`, the + * entire data texture array is sent to the GPU. Marking specific + * layers will only transmit subsets of all mipmaps associated with a + * specific depth in the array which is often much more performant. + * + * @param {number} layerIndex - The layer index that should be updated. + */ + addLayerUpdate( layerIndex ) { + + this.layerUpdates.add( layerIndex ); + + } + + /** + * Resets the layer updates registry. + */ + clearLayerUpdates() { + + this.layerUpdates.clear(); + + } + +} + +/** + * An array render target used in context of {@link WebGLRenderer}. + * + * @augments WebGLRenderTarget + */ +class WebGLArrayRenderTarget extends WebGLRenderTarget { + + /** + * Constructs a new array render target. + * + * @param {number} [width=1] - The width of the render target. + * @param {number} [height=1] - The height of the render target. + * @param {number} [depth=1] - The height of the render target. + * @param {RenderTarget~Options} [options] - The configuration object. + */ + constructor( width = 1, height = 1, depth = 1, options = {} ) { + + super( width, height, options ); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isWebGLArrayRenderTarget = true; + + this.depth = depth; + + /** + * Overwritten with a different texture type. + * + * @type {DataArrayTexture} + */ + this.texture = new DataArrayTexture( null, width, height, depth ); + this._setTextureOptions( options ); + + this.texture.isRenderTargetTexture = true; + + } + +} + +/** + * Creates a three-dimensional texture from raw data, with parameters to + * divide it into width, height, and depth. + * + * @augments Texture + */ +class Data3DTexture extends Texture { + + /** + * Constructs a new data array texture. + * + * @param {?TypedArray} [data=null] - The buffer data. + * @param {number} [width=1] - The width of the texture. + * @param {number} [height=1] - The height of the texture. + * @param {number} [depth=1] - The depth of the texture. + */ + constructor( data = null, width = 1, height = 1, depth = 1 ) { + + // We're going to add .setXXX() methods for setting properties later. + // Users can still set in Data3DTexture directly. + // + // const texture = new THREE.Data3DTexture( data, width, height, depth ); + // texture.anisotropy = 16; + // + // See #14839 + + super( null ); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isData3DTexture = true; + + /** + * The image definition of a data texture. + * + * @type {{data:TypedArray,width:number,height:number,depth:number}} + */ + this.image = { data, width, height, depth }; + + /** + * How the texture is sampled when a texel covers more than one pixel. + * + * Overwritten and set to `NearestFilter` by default. + * + * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)} + * @default NearestFilter + */ + this.magFilter = NearestFilter; + + /** + * How the texture is sampled when a texel covers less than one pixel. + * + * Overwritten and set to `NearestFilter` by default. + * + * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)} + * @default NearestFilter + */ + this.minFilter = NearestFilter; + + /** + * This defines how the texture is wrapped in the depth and corresponds to + * *W* in UVW mapping. + * + * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)} + * @default ClampToEdgeWrapping + */ + this.wrapR = ClampToEdgeWrapping; + + /** + * Whether to generate mipmaps (if possible) for a texture. + * + * Overwritten and set to `false` by default. + * + * @type {boolean} + * @default false + */ + this.generateMipmaps = false; + + /** + * If set to `true`, the texture is flipped along the vertical axis when + * uploaded to the GPU. + * + * Overwritten and set to `false` by default. + * + * @type {boolean} + * @default false + */ + this.flipY = false; + + /** + * Specifies the alignment requirements for the start of each pixel row in memory. + * + * Overwritten and set to `1` by default. + * + * @type {boolean} + * @default 1 + */ + this.unpackAlignment = 1; + + } + + /** + * Copies the values of the given texture to this instance. + * + * @param {Data3DTexture} source - The texture to copy. + * @return {Data3DTexture} A reference to this instance. + */ + copy( source ) { + + super.copy( source ); + + this.wrapR = source.wrapR; + + return this; + + } + +} + +/** + * A 3D render target used in context of {@link WebGLRenderer}. + * + * @augments WebGLRenderTarget + */ +class WebGL3DRenderTarget extends WebGLRenderTarget { + + /** + * Constructs a new 3D render target. + * + * @param {number} [width=1] - The width of the render target. + * @param {number} [height=1] - The height of the render target. + * @param {number} [depth=1] - The height of the render target. + * @param {RenderTarget~Options} [options] - The configuration object. + */ + constructor( width = 1, height = 1, depth = 1, options = {} ) { + + super( width, height, options ); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isWebGL3DRenderTarget = true; + + this.depth = depth; + + /** + * Overwritten with a different texture type. + * + * @type {Data3DTexture} + */ + this.texture = new Data3DTexture( null, width, height, depth ); + this._setTextureOptions( options ); + + this.texture.isRenderTargetTexture = true; + + } + +} + +/** + * Represents a 4x4 matrix. + * + * The most common use of a 4x4 matrix in 3D computer graphics is as a transformation matrix. + * For an introduction to transformation matrices as used in WebGL, check out [this tutorial](https://www.opengl-tutorial.org/beginners-tutorials/tutorial-3-matrices) + * + * This allows a 3D vector representing a point in 3D space to undergo + * transformations such as translation, rotation, shear, scale, reflection, + * orthogonal or perspective projection and so on, by being multiplied by the + * matrix. This is known as `applying` the matrix to the vector. + * + * A Note on Row-Major and Column-Major Ordering: + * + * The constructor and {@link Matrix3#set} method take arguments in + * [row-major](https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order) + * order, while internally they are stored in the {@link Matrix3#elements} array in column-major order. + * This means that calling: + * ```js + * const m = new THREE.Matrix4(); + * m.set( 11, 12, 13, 14, + * 21, 22, 23, 24, + * 31, 32, 33, 34, + * 41, 42, 43, 44 ); + * ``` + * will result in the elements array containing: + * ```js + * m.elements = [ 11, 21, 31, 41, + * 12, 22, 32, 42, + * 13, 23, 33, 43, + * 14, 24, 34, 44 ]; + * ``` + * and internally all calculations are performed using column-major ordering. + * However, as the actual ordering makes no difference mathematically and + * most people are used to thinking about matrices in row-major order, the + * three.js documentation shows matrices in row-major order. Just bear in + * mind that if you are reading the source code, you'll have to take the + * transpose of any matrices outlined here to make sense of the calculations. + */ +class Matrix4 { + + static { + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + Matrix4.prototype.isMatrix4 = true; + + } + + /** + * Constructs a new 4x4 matrix. The arguments are supposed to be + * in row-major order. If no arguments are provided, the constructor + * initializes the matrix as an identity matrix. + * + * @param {number} [n11] - 1-1 matrix element. + * @param {number} [n12] - 1-2 matrix element. + * @param {number} [n13] - 1-3 matrix element. + * @param {number} [n14] - 1-4 matrix element. + * @param {number} [n21] - 2-1 matrix element. + * @param {number} [n22] - 2-2 matrix element. + * @param {number} [n23] - 2-3 matrix element. + * @param {number} [n24] - 2-4 matrix element. + * @param {number} [n31] - 3-1 matrix element. + * @param {number} [n32] - 3-2 matrix element. + * @param {number} [n33] - 3-3 matrix element. + * @param {number} [n34] - 3-4 matrix element. + * @param {number} [n41] - 4-1 matrix element. + * @param {number} [n42] - 4-2 matrix element. + * @param {number} [n43] - 4-3 matrix element. + * @param {number} [n44] - 4-4 matrix element. + */ + constructor( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) { + + /** + * A column-major list of matrix values. + * + * @type {Array} + */ + this.elements = [ + + 1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 + + ]; + + if ( n11 !== undefined ) { + + this.set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ); + + } + + } + + /** + * Sets the elements of the matrix.The arguments are supposed to be + * in row-major order. + * + * @param {number} [n11] - 1-1 matrix element. + * @param {number} [n12] - 1-2 matrix element. + * @param {number} [n13] - 1-3 matrix element. + * @param {number} [n14] - 1-4 matrix element. + * @param {number} [n21] - 2-1 matrix element. + * @param {number} [n22] - 2-2 matrix element. + * @param {number} [n23] - 2-3 matrix element. + * @param {number} [n24] - 2-4 matrix element. + * @param {number} [n31] - 3-1 matrix element. + * @param {number} [n32] - 3-2 matrix element. + * @param {number} [n33] - 3-3 matrix element. + * @param {number} [n34] - 3-4 matrix element. + * @param {number} [n41] - 4-1 matrix element. + * @param {number} [n42] - 4-2 matrix element. + * @param {number} [n43] - 4-3 matrix element. + * @param {number} [n44] - 4-4 matrix element. + * @return {Matrix4} A reference to this matrix. + */ + set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) { + + const te = this.elements; + + te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14; + te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24; + te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34; + te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44; + + return this; + + } + + /** + * Sets this matrix to the 4x4 identity matrix. + * + * @return {Matrix4} A reference to this matrix. + */ + identity() { + + this.set( + + 1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 + + ); + + return this; + + } + + /** + * Returns a matrix with copied values from this instance. + * + * @return {Matrix4} A clone of this instance. + */ + clone() { + + return new Matrix4().fromArray( this.elements ); + + } + + /** + * Copies the values of the given matrix to this instance. + * + * @param {Matrix4} m - The matrix to copy. + * @return {Matrix4} A reference to this matrix. + */ + copy( m ) { + + const te = this.elements; + const me = m.elements; + + te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ]; + te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; + te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ]; + te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ]; + + return this; + + } + + /** + * Copies the translation component of the given matrix + * into this matrix's translation component. + * + * @param {Matrix4} m - The matrix to copy the translation component. + * @return {Matrix4} A reference to this matrix. + */ + copyPosition( m ) { + + const te = this.elements, me = m.elements; + + te[ 12 ] = me[ 12 ]; + te[ 13 ] = me[ 13 ]; + te[ 14 ] = me[ 14 ]; + + return this; + + } + + /** + * Set the upper 3x3 elements of this matrix to the values of given 3x3 matrix. + * + * @param {Matrix3} m - The 3x3 matrix. + * @return {Matrix4} A reference to this matrix. + */ + setFromMatrix3( m ) { + + const me = m.elements; + + this.set( + + me[ 0 ], me[ 3 ], me[ 6 ], 0, + me[ 1 ], me[ 4 ], me[ 7 ], 0, + me[ 2 ], me[ 5 ], me[ 8 ], 0, + 0, 0, 0, 1 + + ); + + return this; + + } + + /** + * Extracts the basis vectors of this matrix into the three vectors provided. + * + * @param {Vector3} xAxis - The basis's x axis. + * @param {Vector3} yAxis - The basis's y axis. + * @param {Vector3} zAxis - The basis's z axis. + * @return {Matrix4} A reference to this matrix. + */ + extractBasis( xAxis, yAxis, zAxis ) { + + if ( this.determinantAffine() === 0 ) { + + xAxis.set( 1, 0, 0 ); + yAxis.set( 0, 1, 0 ); + zAxis.set( 0, 0, 1 ); + + return this; + + } + + xAxis.setFromMatrixColumn( this, 0 ); + yAxis.setFromMatrixColumn( this, 1 ); + zAxis.setFromMatrixColumn( this, 2 ); + + return this; + + } + + /** + * Sets the given basis vectors to this matrix. + * + * @param {Vector3} xAxis - The basis's x axis. + * @param {Vector3} yAxis - The basis's y axis. + * @param {Vector3} zAxis - The basis's z axis. + * @return {Matrix4} A reference to this matrix. + */ + makeBasis( xAxis, yAxis, zAxis ) { + + this.set( + xAxis.x, yAxis.x, zAxis.x, 0, + xAxis.y, yAxis.y, zAxis.y, 0, + xAxis.z, yAxis.z, zAxis.z, 0, + 0, 0, 0, 1 + ); + + return this; + + } + + /** + * Extracts the rotation component of the given matrix + * into this matrix's rotation component. + * + * Note: This method does not support reflection matrices. + * + * @param {Matrix4} m - The matrix. + * @return {Matrix4} A reference to this matrix. + */ + extractRotation( m ) { + + if ( m.determinantAffine() === 0 ) { + + return this.identity(); + + } + + const te = this.elements; + const me = m.elements; + + const scaleX = 1 / _v1$7.setFromMatrixColumn( m, 0 ).length(); + const scaleY = 1 / _v1$7.setFromMatrixColumn( m, 1 ).length(); + const scaleZ = 1 / _v1$7.setFromMatrixColumn( m, 2 ).length(); + + te[ 0 ] = me[ 0 ] * scaleX; + te[ 1 ] = me[ 1 ] * scaleX; + te[ 2 ] = me[ 2 ] * scaleX; + te[ 3 ] = 0; + + te[ 4 ] = me[ 4 ] * scaleY; + te[ 5 ] = me[ 5 ] * scaleY; + te[ 6 ] = me[ 6 ] * scaleY; + te[ 7 ] = 0; + + te[ 8 ] = me[ 8 ] * scaleZ; + te[ 9 ] = me[ 9 ] * scaleZ; + te[ 10 ] = me[ 10 ] * scaleZ; + te[ 11 ] = 0; + + te[ 12 ] = 0; + te[ 13 ] = 0; + te[ 14 ] = 0; + te[ 15 ] = 1; + + return this; + + } + + /** + * Sets the rotation component (the upper left 3x3 matrix) of this matrix to + * the rotation specified by the given Euler angles. The rest of + * the matrix is set to the identity. Depending on the {@link Euler#order}, + * there are six possible outcomes. See [this page](https://en.wikipedia.org/wiki/Euler_angles#Rotation_matrix) + * for a complete list. + * + * @param {Euler} euler - The Euler angles. + * @return {Matrix4} A reference to this matrix. + */ + makeRotationFromEuler( euler ) { + + const te = this.elements; + + const x = euler.x, y = euler.y, z = euler.z; + const a = Math.cos( x ), b = Math.sin( x ); + const c = Math.cos( y ), d = Math.sin( y ); + const e = Math.cos( z ), f = Math.sin( z ); + + if ( euler.order === 'XYZ' ) { + + const ae = a * e, af = a * f, be = b * e, bf = b * f; + + te[ 0 ] = c * e; + te[ 4 ] = - c * f; + te[ 8 ] = d; + + te[ 1 ] = af + be * d; + te[ 5 ] = ae - bf * d; + te[ 9 ] = - b * c; + + te[ 2 ] = bf - ae * d; + te[ 6 ] = be + af * d; + te[ 10 ] = a * c; + + } else if ( euler.order === 'YXZ' ) { + + const ce = c * e, cf = c * f, de = d * e, df = d * f; + + te[ 0 ] = ce + df * b; + te[ 4 ] = de * b - cf; + te[ 8 ] = a * d; + + te[ 1 ] = a * f; + te[ 5 ] = a * e; + te[ 9 ] = - b; + + te[ 2 ] = cf * b - de; + te[ 6 ] = df + ce * b; + te[ 10 ] = a * c; + + } else if ( euler.order === 'ZXY' ) { + + const ce = c * e, cf = c * f, de = d * e, df = d * f; + + te[ 0 ] = ce - df * b; + te[ 4 ] = - a * f; + te[ 8 ] = de + cf * b; + + te[ 1 ] = cf + de * b; + te[ 5 ] = a * e; + te[ 9 ] = df - ce * b; + + te[ 2 ] = - a * d; + te[ 6 ] = b; + te[ 10 ] = a * c; + + } else if ( euler.order === 'ZYX' ) { + + const ae = a * e, af = a * f, be = b * e, bf = b * f; + + te[ 0 ] = c * e; + te[ 4 ] = be * d - af; + te[ 8 ] = ae * d + bf; + + te[ 1 ] = c * f; + te[ 5 ] = bf * d + ae; + te[ 9 ] = af * d - be; + + te[ 2 ] = - d; + te[ 6 ] = b * c; + te[ 10 ] = a * c; + + } else if ( euler.order === 'YZX' ) { + + const ac = a * c, ad = a * d, bc = b * c, bd = b * d; + + te[ 0 ] = c * e; + te[ 4 ] = bd - ac * f; + te[ 8 ] = bc * f + ad; + + te[ 1 ] = f; + te[ 5 ] = a * e; + te[ 9 ] = - b * e; + + te[ 2 ] = - d * e; + te[ 6 ] = ad * f + bc; + te[ 10 ] = ac - bd * f; + + } else if ( euler.order === 'XZY' ) { + + const ac = a * c, ad = a * d, bc = b * c, bd = b * d; + + te[ 0 ] = c * e; + te[ 4 ] = - f; + te[ 8 ] = d * e; + + te[ 1 ] = ac * f + bd; + te[ 5 ] = a * e; + te[ 9 ] = ad * f - bc; + + te[ 2 ] = bc * f - ad; + te[ 6 ] = b * e; + te[ 10 ] = bd * f + ac; + + } + + // bottom row + te[ 3 ] = 0; + te[ 7 ] = 0; + te[ 11 ] = 0; + + // last column + te[ 12 ] = 0; + te[ 13 ] = 0; + te[ 14 ] = 0; + te[ 15 ] = 1; + + return this; + + } + + /** + * Sets the rotation component of this matrix to the rotation specified by + * the given Quaternion as outlined [here](https://en.wikipedia.org/wiki/Rotation_matrix#Quaternion) + * The rest of the matrix is set to the identity. + * + * @param {Quaternion} q - The Quaternion. + * @return {Matrix4} A reference to this matrix. + */ + makeRotationFromQuaternion( q ) { + + return this.compose( _zero, q, _one ); + + } + + /** + * Sets the rotation component of the transformation matrix, looking from `eye` towards + * `target`, and oriented by the up-direction. + * + * @param {Vector3} eye - The eye vector. + * @param {Vector3} target - The target vector. + * @param {Vector3} up - The up vector. + * @return {Matrix4} A reference to this matrix. + */ + lookAt( eye, target, up ) { + + const te = this.elements; + + _z.subVectors( eye, target ); + + if ( _z.lengthSq() === 0 ) { + + // eye and target are in the same position + + _z.z = 1; + + } + + _z.normalize(); + _x.crossVectors( up, _z ); + + if ( _x.lengthSq() === 0 ) { + + // up and z are parallel + + if ( Math.abs( up.z ) === 1 ) { + + _z.x += 0.0001; + + } else { + + _z.z += 0.0001; + + } + + _z.normalize(); + _x.crossVectors( up, _z ); + + } + + _x.normalize(); + _y.crossVectors( _z, _x ); + + te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x; + te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y; + te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z; + + return this; + + } + + /** + * Post-multiplies this matrix by the given 4x4 matrix. + * + * @param {Matrix4} m - The matrix to multiply with. + * @return {Matrix4} A reference to this matrix. + */ + multiply( m ) { + + return this.multiplyMatrices( this, m ); + + } + + /** + * Pre-multiplies this matrix by the given 4x4 matrix. + * + * @param {Matrix4} m - The matrix to multiply with. + * @return {Matrix4} A reference to this matrix. + */ + premultiply( m ) { + + return this.multiplyMatrices( m, this ); + + } + + /** + * Multiples the given 4x4 matrices and stores the result + * in this matrix. + * + * @param {Matrix4} a - The first matrix. + * @param {Matrix4} b - The second matrix. + * @return {Matrix4} A reference to this matrix. + */ + multiplyMatrices( a, b ) { + + const ae = a.elements; + const be = b.elements; + const te = this.elements; + + const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ]; + const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ]; + const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ]; + const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ]; + + const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ]; + const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ]; + const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ]; + const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ]; + + te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41; + te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42; + te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43; + te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44; + + te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41; + te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42; + te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43; + te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44; + + te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41; + te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42; + te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43; + te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44; + + te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41; + te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42; + te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43; + te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44; + + return this; + + } + + /** + * Multiplies every component of the matrix by the given scalar. + * + * @param {number} s - The scalar. + * @return {Matrix4} A reference to this matrix. + */ + multiplyScalar( s ) { + + const te = this.elements; + + te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s; + te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s; + te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s; + te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s; + + return this; + + } + + /** + * Computes and returns the determinant of this matrix. + * + * @return {number} The determinant. + */ + determinant() { + + const te = this.elements; + + const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ]; + const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ]; + const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ]; + const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ]; + + const t11 = n23 * n34 - n24 * n33; + const t12 = n22 * n34 - n24 * n32; + const t13 = n22 * n33 - n23 * n32; + + const t21 = n21 * n34 - n24 * n31; + const t22 = n21 * n33 - n23 * n31; + const t23 = n21 * n32 - n22 * n31; + + return n11 * ( n42 * t11 - n43 * t12 + n44 * t13 ) - + n12 * ( n41 * t11 - n43 * t21 + n44 * t22 ) + + n13 * ( n41 * t12 - n42 * t21 + n44 * t23 ) - + n14 * ( n41 * t13 - n42 * t22 + n43 * t23 ); + + } + + /** + * Computes and returns the determinant of the 4x4 matrix, but assumes the + * matrix is affine, saving some computations. + * + * For affine matrices (like an object's world matrix), this value equals the + * full 4x4 {@link Matrix4#determinant} but is cheaper to compute. + * + * Assumes the bottom row is [0, 0, 0, 1]. + * + * @return {number} The determinant of the matrix. + */ + determinantAffine() { + + const te = this.elements; + + const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ]; + const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ]; + const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ]; + + return n11 * ( n22 * n33 - n23 * n32 ) - + n12 * ( n21 * n33 - n23 * n31 ) + + n13 * ( n21 * n32 - n22 * n31 ); + + } + + /** + * Transposes this matrix in place. + * + * @return {Matrix4} A reference to this matrix. + */ + transpose() { + + const te = this.elements; + let tmp; + + tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp; + tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp; + tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp; + + tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp; + tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp; + tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp; + + return this; + + } + + /** + * Sets the position component for this matrix from the given vector, + * without affecting the rest of the matrix. + * + * @param {number|Vector3} x - The x component of the vector or alternatively the vector object. + * @param {number} y - The y component of the vector. + * @param {number} z - The z component of the vector. + * @return {Matrix4} A reference to this matrix. + */ + setPosition( x, y, z ) { + + const te = this.elements; + + if ( x.isVector3 ) { + + te[ 12 ] = x.x; + te[ 13 ] = x.y; + te[ 14 ] = x.z; + + } else { + + te[ 12 ] = x; + te[ 13 ] = y; + te[ 14 ] = z; + + } + + return this; + + } + + /** + * Inverts this matrix, using the [analytic method](https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution). + * You can not invert with a determinant of zero. If you attempt this, the method produces + * a zero matrix instead. + * + * @return {Matrix4} A reference to this matrix. + */ + invert() { + + // based on https://github.com/toji/gl-matrix + const te = this.elements, + + n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ], + n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ], + n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ], + n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ], + + t1 = n11 * n22 - n21 * n12, + t2 = n11 * n32 - n31 * n12, + t3 = n11 * n42 - n41 * n12, + t4 = n21 * n32 - n31 * n22, + t5 = n21 * n42 - n41 * n22, + t6 = n31 * n42 - n41 * n32, + t7 = n13 * n24 - n23 * n14, + t8 = n13 * n34 - n33 * n14, + t9 = n13 * n44 - n43 * n14, + t10 = n23 * n34 - n33 * n24, + t11 = n23 * n44 - n43 * n24, + t12 = n33 * n44 - n43 * n34; + + const det = t1 * t12 - t2 * t11 + t3 * t10 + t4 * t9 - t5 * t8 + t6 * t7; + + if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ); + + const detInv = 1 / det; + + te[ 0 ] = ( n22 * t12 - n32 * t11 + n42 * t10 ) * detInv; + te[ 1 ] = ( n31 * t11 - n21 * t12 - n41 * t10 ) * detInv; + te[ 2 ] = ( n24 * t6 - n34 * t5 + n44 * t4 ) * detInv; + te[ 3 ] = ( n33 * t5 - n23 * t6 - n43 * t4 ) * detInv; + + te[ 4 ] = ( n32 * t9 - n12 * t12 - n42 * t8 ) * detInv; + te[ 5 ] = ( n11 * t12 - n31 * t9 + n41 * t8 ) * detInv; + te[ 6 ] = ( n34 * t3 - n14 * t6 - n44 * t2 ) * detInv; + te[ 7 ] = ( n13 * t6 - n33 * t3 + n43 * t2 ) * detInv; + + te[ 8 ] = ( n12 * t11 - n22 * t9 + n42 * t7 ) * detInv; + te[ 9 ] = ( n21 * t9 - n11 * t11 - n41 * t7 ) * detInv; + te[ 10 ] = ( n14 * t5 - n24 * t3 + n44 * t1 ) * detInv; + te[ 11 ] = ( n23 * t3 - n13 * t5 - n43 * t1 ) * detInv; + + te[ 12 ] = ( n22 * t8 - n12 * t10 - n32 * t7 ) * detInv; + te[ 13 ] = ( n11 * t10 - n21 * t8 + n31 * t7 ) * detInv; + te[ 14 ] = ( n24 * t2 - n14 * t4 - n34 * t1 ) * detInv; + te[ 15 ] = ( n13 * t4 - n23 * t2 + n33 * t1 ) * detInv; + + return this; + + } + + /** + * Scales each of the first three columns of this matrix by the corresponding component of the given vector. + * + * @param {Vector3} v - The scale vector. + * @return {Matrix4} A reference to this matrix. + */ + scale( v ) { + + const te = this.elements; + const x = v.x, y = v.y, z = v.z; + + te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z; + te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z; + te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z; + te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z; + + return this; + + } + + /** + * Gets the maximum scale value of the three axes. + * + * @return {number} The maximum scale. + */ + getMaxScaleOnAxis() { + + const te = this.elements; + + const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ]; + const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ]; + const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ]; + + return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) ); + + } + + /** + * Sets this matrix as a translation transform from the given vector. + * + * @param {number|Vector3} x - The amount to translate in the X axis or alternatively a translation vector. + * @param {number} y - The amount to translate in the Y axis. + * @param {number} z - The amount to translate in the z axis. + * @return {Matrix4} A reference to this matrix. + */ + makeTranslation( x, y, z ) { + + if ( x.isVector3 ) { + + this.set( + + 1, 0, 0, x.x, + 0, 1, 0, x.y, + 0, 0, 1, x.z, + 0, 0, 0, 1 + + ); + + } else { + + this.set( + + 1, 0, 0, x, + 0, 1, 0, y, + 0, 0, 1, z, + 0, 0, 0, 1 + + ); + + } + + return this; + + } + + /** + * Sets this matrix as a rotational transformation around the X axis by + * the given angle. + * + * @param {number} theta - The rotation in radians. + * @return {Matrix4} A reference to this matrix. + */ + makeRotationX( theta ) { + + const c = Math.cos( theta ), s = Math.sin( theta ); + + this.set( + + 1, 0, 0, 0, + 0, c, - s, 0, + 0, s, c, 0, + 0, 0, 0, 1 + + ); + + return this; + + } + + /** + * Sets this matrix as a rotational transformation around the Y axis by + * the given angle. + * + * @param {number} theta - The rotation in radians. + * @return {Matrix4} A reference to this matrix. + */ + makeRotationY( theta ) { + + const c = Math.cos( theta ), s = Math.sin( theta ); + + this.set( + + c, 0, s, 0, + 0, 1, 0, 0, + - s, 0, c, 0, + 0, 0, 0, 1 + + ); + + return this; + + } + + /** + * Sets this matrix as a rotational transformation around the Z axis by + * the given angle. + * + * @param {number} theta - The rotation in radians. + * @return {Matrix4} A reference to this matrix. + */ + makeRotationZ( theta ) { + + const c = Math.cos( theta ), s = Math.sin( theta ); + + this.set( + + c, - s, 0, 0, + s, c, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 + + ); + + return this; + + } + + /** + * Sets this matrix as a rotational transformation around the given axis by + * the given angle. + * + * @param {Vector3} axis - The normalized rotation axis. + * @param {number} angle - The rotation in radians. + * @return {Matrix4} A reference to this matrix. + */ + makeRotationAxis( axis, angle ) { + + const c = Math.cos( angle ); + const s = Math.sin( angle ); + const t = 1 - c; + const x = axis.x, y = axis.y, z = axis.z; + const tx = t * x, ty = t * y; + + this.set( + + tx * x + c, tx * y - s * z, tx * z + s * y, 0, + tx * y + s * z, ty * y + c, ty * z - s * x, 0, + tx * z - s * y, ty * z + s * x, t * z * z + c, 0, + 0, 0, 0, 1 + + ); + + return this; + + } + + /** + * Sets this matrix as a scale transformation. + * + * @param {number} x - The amount to scale in the X axis. + * @param {number} y - The amount to scale in the Y axis. + * @param {number} z - The amount to scale in the Z axis. + * @return {Matrix4} A reference to this matrix. + */ + makeScale( x, y, z ) { + + this.set( + + x, 0, 0, 0, + 0, y, 0, 0, + 0, 0, z, 0, + 0, 0, 0, 1 + + ); + + return this; + + } + + /** + * Sets this matrix as a shear transformation. + * + * @param {number} xy - The amount to shear X by Y. + * @param {number} xz - The amount to shear X by Z. + * @param {number} yx - The amount to shear Y by X. + * @param {number} yz - The amount to shear Y by Z. + * @param {number} zx - The amount to shear Z by X. + * @param {number} zy - The amount to shear Z by Y. + * @return {Matrix4} A reference to this matrix. + */ + makeShear( xy, xz, yx, yz, zx, zy ) { + + this.set( + + 1, yx, zx, 0, + xy, 1, zy, 0, + xz, yz, 1, 0, + 0, 0, 0, 1 + + ); + + return this; + + } + + /** + * Sets this matrix to the transformation composed of the given position, + * rotation (Quaternion) and scale. + * + * @param {Vector3} position - The position vector. + * @param {Quaternion} quaternion - The rotation as a Quaternion. + * @param {Vector3} scale - The scale vector. + * @return {Matrix4} A reference to this matrix. + */ + compose( position, quaternion, scale ) { + + const te = this.elements; + + const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w; + const x2 = x + x, y2 = y + y, z2 = z + z; + const xx = x * x2, xy = x * y2, xz = x * z2; + const yy = y * y2, yz = y * z2, zz = z * z2; + const wx = w * x2, wy = w * y2, wz = w * z2; + + const sx = scale.x, sy = scale.y, sz = scale.z; + + te[ 0 ] = ( 1 - ( yy + zz ) ) * sx; + te[ 1 ] = ( xy + wz ) * sx; + te[ 2 ] = ( xz - wy ) * sx; + te[ 3 ] = 0; + + te[ 4 ] = ( xy - wz ) * sy; + te[ 5 ] = ( 1 - ( xx + zz ) ) * sy; + te[ 6 ] = ( yz + wx ) * sy; + te[ 7 ] = 0; + + te[ 8 ] = ( xz + wy ) * sz; + te[ 9 ] = ( yz - wx ) * sz; + te[ 10 ] = ( 1 - ( xx + yy ) ) * sz; + te[ 11 ] = 0; + + te[ 12 ] = position.x; + te[ 13 ] = position.y; + te[ 14 ] = position.z; + te[ 15 ] = 1; + + return this; + + } + + /** + * Decomposes this matrix into its position, rotation and scale components + * and provides the result in the given objects. + * + * Note: Not all matrices are decomposable in this way. For example, if an + * object has a non-uniformly scaled parent, then the object's world matrix + * may not be decomposable, and this method may not be appropriate. + * + * @param {Vector3} position - The position vector. + * @param {Quaternion} quaternion - The rotation as a Quaternion. + * @param {Vector3} scale - The scale vector. + * @return {Matrix4} A reference to this matrix. + */ + decompose( position, quaternion, scale ) { + + const te = this.elements; + + position.x = te[ 12 ]; + position.y = te[ 13 ]; + position.z = te[ 14 ]; + + const det = this.determinantAffine(); + + if ( det === 0 ) { + + scale.set( 1, 1, 1 ); + quaternion.identity(); + + return this; + + } + + let sx = _v1$7.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length(); + const sy = _v1$7.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length(); + const sz = _v1$7.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length(); + + // if determinant is negative, we need to invert one scale + if ( det < 0 ) sx = - sx; + + // scale the rotation part + _m1$2.copy( this ); + + const invSX = 1 / sx; + const invSY = 1 / sy; + const invSZ = 1 / sz; + + _m1$2.elements[ 0 ] *= invSX; + _m1$2.elements[ 1 ] *= invSX; + _m1$2.elements[ 2 ] *= invSX; + + _m1$2.elements[ 4 ] *= invSY; + _m1$2.elements[ 5 ] *= invSY; + _m1$2.elements[ 6 ] *= invSY; + + _m1$2.elements[ 8 ] *= invSZ; + _m1$2.elements[ 9 ] *= invSZ; + _m1$2.elements[ 10 ] *= invSZ; + + quaternion.setFromRotationMatrix( _m1$2 ); + + scale.x = sx; + scale.y = sy; + scale.z = sz; + + return this; + + } + + /** + * Creates a perspective projection matrix. This is used internally by + * {@link PerspectiveCamera#updateProjectionMatrix}. + + * @param {number} left - Left boundary of the viewing frustum at the near plane. + * @param {number} right - Right boundary of the viewing frustum at the near plane. + * @param {number} top - Top boundary of the viewing frustum at the near plane. + * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane. + * @param {number} near - The distance from the camera to the near plane. + * @param {number} far - The distance from the camera to the far plane. + * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system. + * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth. + * @return {Matrix4} A reference to this matrix. + */ + makePerspective( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) { + + const te = this.elements; + + const x = 2 * near / ( right - left ); + const y = 2 * near / ( top - bottom ); + + const a = ( right + left ) / ( right - left ); + const b = ( top + bottom ) / ( top - bottom ); + + let c, d; + + if ( reversedDepth ) { + + c = near / ( far - near ); + d = ( far * near ) / ( far - near ); + + } else { + + if ( coordinateSystem === WebGLCoordinateSystem ) { + + c = - ( far + near ) / ( far - near ); + d = ( -2 * far * near ) / ( far - near ); + + } else if ( coordinateSystem === WebGPUCoordinateSystem ) { + + c = - far / ( far - near ); + d = ( - far * near ) / ( far - near ); + + } else { + + throw new Error( 'THREE.Matrix4.makePerspective(): Invalid coordinate system: ' + coordinateSystem ); + + } + + } + + te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0; + te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0; + te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d; + te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = -1; te[ 15 ] = 0; + + return this; + + } + + /** + * Creates a orthographic projection matrix. This is used internally by + * {@link OrthographicCamera#updateProjectionMatrix}. + + * @param {number} left - Left boundary of the viewing frustum at the near plane. + * @param {number} right - Right boundary of the viewing frustum at the near plane. + * @param {number} top - Top boundary of the viewing frustum at the near plane. + * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane. + * @param {number} near - The distance from the camera to the near plane. + * @param {number} far - The distance from the camera to the far plane. + * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system. + * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth. + * @return {Matrix4} A reference to this matrix. + */ + makeOrthographic( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) { + + const te = this.elements; + + const x = 2 / ( right - left ); + const y = 2 / ( top - bottom ); + + const a = - ( right + left ) / ( right - left ); + const b = - ( top + bottom ) / ( top - bottom ); + + let c, d; + + if ( reversedDepth ) { + + c = 1 / ( far - near ); + d = far / ( far - near ); + + } else { + + if ( coordinateSystem === WebGLCoordinateSystem ) { + + c = -2 / ( far - near ); + d = - ( far + near ) / ( far - near ); + + } else if ( coordinateSystem === WebGPUCoordinateSystem ) { + + c = -1 / ( far - near ); + d = - near / ( far - near ); + + } else { + + throw new Error( 'THREE.Matrix4.makeOrthographic(): Invalid coordinate system: ' + coordinateSystem ); + + } + + } + + te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = a; + te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = 0; te[ 13 ] = b; + te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d; + te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1; + + return this; + + } + + /** + * Returns `true` if this matrix is equal with the given one. + * + * @param {Matrix4} matrix - The matrix to test for equality. + * @return {boolean} Whether this matrix is equal with the given one. + */ + equals( matrix ) { + + const te = this.elements; + const me = matrix.elements; + + for ( let i = 0; i < 16; i ++ ) { + + if ( te[ i ] !== me[ i ] ) return false; + + } + + return true; + + } + + /** + * Sets the elements of the matrix from the given array. + * + * @param {Array} array - The matrix elements in column-major order. + * @param {number} [offset=0] - Index of the first element in the array. + * @return {Matrix4} A reference to this matrix. + */ + fromArray( array, offset = 0 ) { + + for ( let i = 0; i < 16; i ++ ) { + + this.elements[ i ] = array[ i + offset ]; + + } + + return this; + + } + + /** + * Writes the elements of this matrix to the given array. If no array is provided, + * the method returns a new instance. + * + * @param {Array} [array=[]] - The target array holding the matrix elements in column-major order. + * @param {number} [offset=0] - Index of the first element in the array. + * @return {Array} The matrix elements in column-major order. + */ + toArray( array = [], offset = 0 ) { + + const te = this.elements; + + array[ offset ] = te[ 0 ]; + array[ offset + 1 ] = te[ 1 ]; + array[ offset + 2 ] = te[ 2 ]; + array[ offset + 3 ] = te[ 3 ]; + + array[ offset + 4 ] = te[ 4 ]; + array[ offset + 5 ] = te[ 5 ]; + array[ offset + 6 ] = te[ 6 ]; + array[ offset + 7 ] = te[ 7 ]; + + array[ offset + 8 ] = te[ 8 ]; + array[ offset + 9 ] = te[ 9 ]; + array[ offset + 10 ] = te[ 10 ]; + array[ offset + 11 ] = te[ 11 ]; + + array[ offset + 12 ] = te[ 12 ]; + array[ offset + 13 ] = te[ 13 ]; + array[ offset + 14 ] = te[ 14 ]; + array[ offset + 15 ] = te[ 15 ]; + + return array; + + } + +} + +const _v1$7 = /*@__PURE__*/ new Vector3(); +const _m1$2 = /*@__PURE__*/ new Matrix4(); +const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 ); +const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 ); +const _x = /*@__PURE__*/ new Vector3(); +const _y = /*@__PURE__*/ new Vector3(); +const _z = /*@__PURE__*/ new Vector3(); + +const _matrix$2 = /*@__PURE__*/ new Matrix4(); +const _quaternion$4 = /*@__PURE__*/ new Quaternion(); + +/** + * A class representing Euler angles. + * + * Euler angles describe a rotational transformation by rotating an object on + * its various axes in specified amounts per axis, and a specified axis + * order. + * + * Iterating through an instance will yield its components (x, y, z, + * order) in the corresponding order. + * + * ```js + * const a = new THREE.Euler( 0, 1, 1.57, 'XYZ' ); + * const b = new THREE.Vector3( 1, 0, 1 ); + * b.applyEuler(a); + * ``` + */ +class Euler { + + /** + * Constructs a new euler instance. + * + * @param {number} [x=0] - The angle of the x axis in radians. + * @param {number} [y=0] - The angle of the y axis in radians. + * @param {number} [z=0] - The angle of the z axis in radians. + * @param {string} [order=Euler.DEFAULT_ORDER] - A string representing the order that the rotations are applied. + */ + constructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) { + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isEuler = true; + + this._x = x; + this._y = y; + this._z = z; + this._order = order; + + } + + /** + * The angle of the x axis in radians. + * + * @type {number} + * @default 0 + */ + get x() { + + return this._x; + + } + + set x( value ) { + + this._x = value; + this._onChangeCallback(); + + } + + /** + * The angle of the y axis in radians. + * + * @type {number} + * @default 0 + */ + get y() { + + return this._y; + + } + + set y( value ) { + + this._y = value; + this._onChangeCallback(); + + } + + /** + * The angle of the z axis in radians. + * + * @type {number} + * @default 0 + */ + get z() { + + return this._z; + + } + + set z( value ) { + + this._z = value; + this._onChangeCallback(); + + } + + /** + * A string representing the order that the rotations are applied. + * + * @type {string} + * @default 'XYZ' + */ + get order() { + + return this._order; + + } + + set order( value ) { + + this._order = value; + this._onChangeCallback(); + + } + + /** + * Sets the Euler components. + * + * @param {number} x - The angle of the x axis in radians. + * @param {number} y - The angle of the y axis in radians. + * @param {number} z - The angle of the z axis in radians. + * @param {string} [order] - A string representing the order that the rotations are applied. + * @return {Euler} A reference to this Euler instance. + */ + set( x, y, z, order = this._order ) { + + this._x = x; + this._y = y; + this._z = z; + this._order = order; + + this._onChangeCallback(); + + return this; + + } + + /** + * Returns a new Euler instance with copied values from this instance. + * + * @return {Euler} A clone of this instance. + */ + clone() { + + return new this.constructor( this._x, this._y, this._z, this._order ); + + } + + /** + * Copies the values of the given Euler instance to this instance. + * + * @param {Euler} euler - The Euler instance to copy. + * @return {Euler} A reference to this Euler instance. + */ + copy( euler ) { + + this._x = euler._x; + this._y = euler._y; + this._z = euler._z; + this._order = euler._order; + + this._onChangeCallback(); + + return this; + + } + + /** + * Sets the angles of this Euler instance from a pure rotation matrix. + * + * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled). + * @param {string} [order] - A string representing the order that the rotations are applied. + * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not. + * @return {Euler} A reference to this Euler instance. + */ + setFromRotationMatrix( m, order = this._order, update = true ) { + + const te = m.elements; + const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ]; + const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ]; + const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ]; + + switch ( order ) { + + case 'XYZ': + + this._y = Math.asin( clamp( m13, -1, 1 ) ); + + if ( Math.abs( m13 ) < 0.9999999 ) { + + this._x = Math.atan2( - m23, m33 ); + this._z = Math.atan2( - m12, m11 ); + + } else { + + this._x = Math.atan2( m32, m22 ); + this._z = 0; + + } + + break; + + case 'YXZ': + + this._x = Math.asin( - clamp( m23, -1, 1 ) ); + + if ( Math.abs( m23 ) < 0.9999999 ) { + + this._y = Math.atan2( m13, m33 ); + this._z = Math.atan2( m21, m22 ); + + } else { + + this._y = Math.atan2( - m31, m11 ); + this._z = 0; + + } + + break; + + case 'ZXY': + + this._x = Math.asin( clamp( m32, -1, 1 ) ); + + if ( Math.abs( m32 ) < 0.9999999 ) { + + this._y = Math.atan2( - m31, m33 ); + this._z = Math.atan2( - m12, m22 ); + + } else { + + this._y = 0; + this._z = Math.atan2( m21, m11 ); + + } + + break; + + case 'ZYX': + + this._y = Math.asin( - clamp( m31, -1, 1 ) ); + + if ( Math.abs( m31 ) < 0.9999999 ) { + + this._x = Math.atan2( m32, m33 ); + this._z = Math.atan2( m21, m11 ); + + } else { + + this._x = 0; + this._z = Math.atan2( - m12, m22 ); + + } + + break; + + case 'YZX': + + this._z = Math.asin( clamp( m21, -1, 1 ) ); + + if ( Math.abs( m21 ) < 0.9999999 ) { + + this._x = Math.atan2( - m23, m22 ); + this._y = Math.atan2( - m31, m11 ); + + } else { + + this._x = 0; + this._y = Math.atan2( m13, m33 ); + + } + + break; + + case 'XZY': + + this._z = Math.asin( - clamp( m12, -1, 1 ) ); + + if ( Math.abs( m12 ) < 0.9999999 ) { + + this._x = Math.atan2( m32, m22 ); + this._y = Math.atan2( m13, m11 ); + + } else { + + this._x = Math.atan2( - m23, m33 ); + this._y = 0; + + } + + break; + + default: + + warn( 'Euler: .setFromRotationMatrix() encountered an unknown order: ' + order ); + + } + + this._order = order; + + if ( update === true ) this._onChangeCallback(); + + return this; + + } + + /** + * Sets the angles of this Euler instance from a normalized quaternion. + * + * @param {Quaternion} q - A normalized Quaternion. + * @param {string} [order] - A string representing the order that the rotations are applied. + * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not. + * @return {Euler} A reference to this Euler instance. + */ + setFromQuaternion( q, order, update ) { + + _matrix$2.makeRotationFromQuaternion( q ); + + return this.setFromRotationMatrix( _matrix$2, order, update ); + + } + + /** + * Sets the angles of this Euler instance from the given vector. + * + * @param {Vector3} v - The vector. + * @param {string} [order] - A string representing the order that the rotations are applied. + * @return {Euler} A reference to this Euler instance. + */ + setFromVector3( v, order = this._order ) { + + return this.set( v.x, v.y, v.z, order ); + + } + + /** + * Resets the euler angle with a new order by creating a quaternion from this + * euler angle and then setting this euler angle with the quaternion and the + * new order. + * + * Warning: This discards revolution information. + * + * @param {string} [newOrder] - A string representing the new order that the rotations are applied. + * @return {Euler} A reference to this Euler instance. + */ + reorder( newOrder ) { + + _quaternion$4.setFromEuler( this ); + + return this.setFromQuaternion( _quaternion$4, newOrder ); + + } + + /** + * Returns `true` if this Euler instance is equal with the given one. + * + * @param {Euler} euler - The Euler instance to test for equality. + * @return {boolean} Whether this Euler instance is equal with the given one. + */ + equals( euler ) { + + return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order ); + + } + + /** + * Sets this Euler instance's components to values from the given array. The first three + * entries of the array are assign to the x,y and z components. An optional fourth entry + * defines the Euler order. + * + * @param {Array} array - An array holding the Euler component values. + * @return {Euler} A reference to this Euler instance. + */ + fromArray( array ) { + + this._x = array[ 0 ]; + this._y = array[ 1 ]; + this._z = array[ 2 ]; + if ( array[ 3 ] !== undefined ) this._order = array[ 3 ]; + + this._onChangeCallback(); + + return this; + + } + + /** + * Writes the components of this Euler instance to the given array. If no array is provided, + * the method returns a new instance. + * + * @param {Array} [array=[]] - The target array holding the Euler components. + * @param {number} [offset=0] - Index of the first element in the array. + * @return {Array} The Euler components. + */ + toArray( array = [], offset = 0 ) { + + array[ offset ] = this._x; + array[ offset + 1 ] = this._y; + array[ offset + 2 ] = this._z; + array[ offset + 3 ] = this._order; + + return array; + + } + + _onChange( callback ) { + + this._onChangeCallback = callback; + + return this; + + } + + _onChangeCallback() {} + + *[ Symbol.iterator ]() { + + yield this._x; + yield this._y; + yield this._z; + yield this._order; + + } + +} + +/** + * The default Euler angle order. + * + * @static + * @type {string} + * @default 'XYZ' + */ +Euler.DEFAULT_ORDER = 'XYZ'; + +/** + * A layers object assigns an 3D object to 1 or more of 32 + * layers numbered `0` to `31` - internally the layers are stored as a + * bit mask], and by default all 3D objects are a member of layer `0`. + * + * This can be used to control visibility - an object must share a layer with + * a camera to be visible when that camera's view is + * rendered. + * + * All classes that inherit from {@link Object3D} have an `layers` property which + * is an instance of this class. + */ +class Layers { + + /** + * Constructs a new layers instance, with membership + * initially set to layer `0`. + */ + constructor() { + + /** + * A bit mask storing which of the 32 layers this layers object is currently + * a member of. + * + * @type {number} + */ + this.mask = 1 | 0; + + } + + /** + * Sets membership to the given layer, and remove membership all other layers. + * + * @param {number} layer - The layer to set. + */ + set( layer ) { + + this.mask = ( 1 << layer | 0 ) >>> 0; + + } + + /** + * Adds membership of the given layer. + * + * @param {number} layer - The layer to enable. + */ + enable( layer ) { + + this.mask |= 1 << layer | 0; + + } + + /** + * Adds membership to all layers. + */ + enableAll() { + + this.mask = 0xffffffff | 0; + + } + + /** + * Toggles the membership of the given layer. + * + * @param {number} layer - The layer to toggle. + */ + toggle( layer ) { + + this.mask ^= 1 << layer | 0; + + } + + /** + * Removes membership of the given layer. + * + * @param {number} layer - The layer to enable. + */ + disable( layer ) { + + this.mask &= ~ ( 1 << layer | 0 ); + + } + + /** + * Removes the membership from all layers. + */ + disableAll() { + + this.mask = 0; + + } + + /** + * Returns `true` if this and the given layers object have at least one + * layer in common. + * + * @param {Layers} layers - The layers to test. + * @return {boolean } Whether this and the given layers object have at least one layer in common or not. + */ + test( layers ) { + + return ( this.mask & layers.mask ) !== 0; + + } + + /** + * Returns `true` if the given layer is enabled. + * + * @param {number} layer - The layer to test. + * @return {boolean } Whether the given layer is enabled or not. + */ + isEnabled( layer ) { + + return ( this.mask & ( 1 << layer | 0 ) ) !== 0; + + } + +} + +let _object3DId = 0; + +const _v1$6 = /*@__PURE__*/ new Vector3(); +const _q1 = /*@__PURE__*/ new Quaternion(); +const _m1$1 = /*@__PURE__*/ new Matrix4(); +const _target = /*@__PURE__*/ new Vector3(); + +const _position$4 = /*@__PURE__*/ new Vector3(); +const _scale$3 = /*@__PURE__*/ new Vector3(); +const _quaternion$3 = /*@__PURE__*/ new Quaternion(); + +const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 ); +const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 ); +const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 ); + +/** + * Fires when the object has been added to its parent object. + * + * @event Object3D#added + * @type {Object} + */ +const _addedEvent = { type: 'added' }; + +/** + * Fires when the object has been removed from its parent object. + * + * @event Object3D#removed + * @type {Object} + */ +const _removedEvent = { type: 'removed' }; + +/** + * Fires when a new child object has been added. + * + * @event Object3D#childadded + * @type {Object} + */ +const _childaddedEvent = { type: 'childadded', child: null }; + +/** + * Fires when a child object has been removed. + * + * @event Object3D#childremoved + * @type {Object} + */ +const _childremovedEvent = { type: 'childremoved', child: null }; + +/** + * This is the base class for most objects in three.js and provides a set of + * properties and methods for manipulating objects in 3D space. + * + * @augments EventDispatcher + */ +class Object3D extends EventDispatcher { + + /** + * Constructs a new 3D object. + */ + constructor() { + + super(); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isObject3D = true; + + /** + * The ID of the 3D object. + * + * @name Object3D#id + * @type {number} + * @readonly + */ + Object.defineProperty( this, 'id', { value: _object3DId ++ } ); + + /** + * The UUID of the 3D object. + * + * @type {string} + * @readonly + */ + this.uuid = generateUUID(); + + /** + * The name of the 3D object. + * + * @type {string} + */ + this.name = ''; + + /** + * The type property is used for detecting the object type + * in context of serialization/deserialization. + * + * @type {string} + * @readonly + */ + this.type = 'Object3D'; + + /** + * A reference to the parent object. + * + * @type {?Object3D} + * @default null + */ + this.parent = null; + + /** + * An array holding the child 3D objects of this instance. + * + * @type {Array} + */ + this.children = []; + + /** + * Defines the `up` direction of the 3D object which influences + * the orientation via methods like {@link Object3D#lookAt}. + * + * The default values for all 3D objects is defined by `Object3D.DEFAULT_UP`. + * + * @type {Vector3} + */ + this.up = Object3D.DEFAULT_UP.clone(); + + const position = new Vector3(); + const rotation = new Euler(); + const quaternion = new Quaternion(); + const scale = new Vector3( 1, 1, 1 ); + + function onRotationChange() { + + quaternion.setFromEuler( rotation, false ); + + } + + function onQuaternionChange() { + + rotation.setFromQuaternion( quaternion, undefined, false ); + + } + + rotation._onChange( onRotationChange ); + quaternion._onChange( onQuaternionChange ); + + Object.defineProperties( this, { + /** + * Represents the object's local position. + * + * @name Object3D#position + * @type {Vector3} + * @default (0,0,0) + */ + position: { + configurable: true, + enumerable: true, + value: position + }, + /** + * Represents the object's local rotation as Euler angles, in radians. + * + * @name Object3D#rotation + * @type {Euler} + * @default (0,0,0) + */ + rotation: { + configurable: true, + enumerable: true, + value: rotation + }, + /** + * Represents the object's local rotation as Quaternions. + * + * @name Object3D#quaternion + * @type {Quaternion} + */ + quaternion: { + configurable: true, + enumerable: true, + value: quaternion + }, + /** + * Represents the object's local scale. + * + * @name Object3D#scale + * @type {Vector3} + * @default (1,1,1) + */ + scale: { + configurable: true, + enumerable: true, + value: scale + }, + /** + * Represents the object's model-view matrix. + * + * @name Object3D#modelViewMatrix + * @type {Matrix4} + */ + modelViewMatrix: { + value: new Matrix4() + }, + /** + * Represents the object's normal matrix. + * + * @name Object3D#normalMatrix + * @type {Matrix3} + */ + normalMatrix: { + value: new Matrix3() + } + } ); + + /** + * Represents the object's transformation matrix in local space. + * + * @type {Matrix4} + */ + this.matrix = new Matrix4(); + + /** + * Represents the object's transformation matrix in world space. + * If the 3D object has no parent, then it's identical to the local transformation matrix + * + * @type {Matrix4} + */ + this.matrixWorld = new Matrix4(); + + /** + * When set to `true`, the engine automatically computes the local matrix from position, + * rotation and scale every frame. If set to `false`, the app is responsible for recomputing + * the local matrix by calling `updateMatrix()`. + * + * The default values for all 3D objects is defined by `Object3D.DEFAULT_MATRIX_AUTO_UPDATE`. + * + * @type {boolean} + * @default true + */ + this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE; + + /** + * When set to `true`, the engine automatically computes the world matrix from the current local + * matrix and the object's transformation hierarchy. If set to `false`, the app is responsible for + * recomputing the world matrix by directly updating the `matrixWorld` property. + * + * The default values for all 3D objects is defined by `Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE`. + * + * @type {boolean} + * @default true + */ + this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer + + /** + * When set to `true`, it calculates the world matrix in that frame and resets this property + * to `false`. + * + * @type {boolean} + * @default false + */ + this.matrixWorldNeedsUpdate = false; + + /** + * The layer membership of the 3D object. The 3D object is only visible if it has + * at least one layer in common with the camera in use. This property can also be + * used to filter out unwanted objects in ray-intersection tests when using {@link Raycaster}. + * + * @type {Layers} + */ + this.layers = new Layers(); + + /** + * When set to `true`, the 3D object gets rendered. + * + * @type {boolean} + * @default true + */ + this.visible = true; + + /** + * When set to `true`, the 3D object gets rendered into shadow maps. + * + * @type {boolean} + * @default false + */ + this.castShadow = false; + + /** + * When set to `true`, the 3D object is affected by shadows in the scene. + * + * @type {boolean} + * @default false + */ + this.receiveShadow = false; + + /** + * When set to `true`, the 3D object is honored by view frustum culling. + * + * @type {boolean} + * @default true + */ + this.frustumCulled = true; + + /** + * This value allows the default rendering order of scene graph objects to be + * overridden although opaque and transparent objects remain sorted independently. + * When this property is set for an instance of {@link Group},all descendants + * objects will be sorted and rendered together. Sorting is from lowest to highest + * render order. + * + * @type {number} + * @default 0 + */ + this.renderOrder = 0; + + /** + * An array holding the animation clips of the 3D object. + * + * @type {Array} + */ + this.animations = []; + + /** + * Custom depth material to be used when rendering to the depth map. Can only be used + * in context of meshes. When shadow-casting with a {@link DirectionalLight} or {@link SpotLight}, + * if you are modifying vertex positions in the vertex shader you must specify a custom depth + * material for proper shadows. + * + * Only relevant in context of {@link WebGLRenderer}. + * + * @type {(Material|undefined)} + * @default undefined + */ + this.customDepthMaterial = undefined; + + /** + * Same as {@link Object3D#customDepthMaterial}, but used with {@link PointLight}. + * + * Only relevant in context of {@link WebGLRenderer}. + * + * @type {(Material|undefined)} + * @default undefined + */ + this.customDistanceMaterial = undefined; + + /** + * Whether the 3D object is supposed to be static or not. If set to `true`, it means + * the 3D object is not going to be changed after the initial renderer. This includes + * geometry and material settings. A static 3D object can be processed by the renderer + * slightly faster since certain state checks can be bypassed. + * + * Only relevant in context of {@link WebGPURenderer}. + * + * @type {boolean} + * @default false + */ + this.static = false; + + /** + * An object that can be used to store custom data about the 3D object. It + * should not hold references to functions as these will not be cloned. + * + * @type {Object} + */ + this.userData = {}; + + /** + * The pivot point for rotation and scale transformations. + * When set, rotation and scale are applied around this point + * instead of the object's origin. + * + * @type {?Vector3} + * @default null + */ + this.pivot = null; + + } + + /** + * A callback that is executed immediately before a 3D object is rendered to a shadow map. + * + * @param {Renderer|WebGLRenderer} renderer - The renderer. + * @param {Object3D} object - The 3D object. + * @param {Camera} camera - The camera that is used to render the scene. + * @param {Camera} shadowCamera - The shadow camera. + * @param {BufferGeometry} geometry - The 3D object's geometry. + * @param {Material} depthMaterial - The depth material. + * @param {Object} group - The geometry group data. + */ + onBeforeShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {} + + /** + * A callback that is executed immediately after a 3D object is rendered to a shadow map. + * + * @param {Renderer|WebGLRenderer} renderer - The renderer. + * @param {Object3D} object - The 3D object. + * @param {Camera} camera - The camera that is used to render the scene. + * @param {Camera} shadowCamera - The shadow camera. + * @param {BufferGeometry} geometry - The 3D object's geometry. + * @param {Material} depthMaterial - The depth material. + * @param {Object} group - The geometry group data. + */ + onAfterShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {} + + /** + * A callback that is executed immediately before a 3D object is rendered. + * + * @param {Renderer|WebGLRenderer} renderer - The renderer. + * @param {Object3D} object - The 3D object. + * @param {Camera} camera - The camera that is used to render the scene. + * @param {BufferGeometry} geometry - The 3D object's geometry. + * @param {Material} material - The 3D object's material. + * @param {Object} group - The geometry group data. + */ + onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {} + + /** + * A callback that is executed immediately after a 3D object is rendered. + * + * @param {Renderer|WebGLRenderer} renderer - The renderer. + * @param {Object3D} object - The 3D object. + * @param {Camera} camera - The camera that is used to render the scene. + * @param {BufferGeometry} geometry - The 3D object's geometry. + * @param {Material} material - The 3D object's material. + * @param {Object} group - The geometry group data. + */ + onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {} + + /** + * Applies the given transformation matrix to the object and updates the object's position, + * rotation and scale. + * + * @param {Matrix4} matrix - The transformation matrix. + */ + applyMatrix4( matrix ) { + + if ( this.matrixAutoUpdate ) this.updateMatrix(); + + this.matrix.premultiply( matrix ); + + this.matrix.decompose( this.position, this.quaternion, this.scale ); + + } + + /** + * Applies a rotation represented by given the quaternion to the 3D object. + * + * @param {Quaternion} q - The quaternion. + * @return {Object3D} A reference to this instance. + */ + applyQuaternion( q ) { + + this.quaternion.premultiply( q ); + + return this; + + } + + /** + * Sets the given rotation represented as an axis/angle couple to the 3D object. + * + * @param {Vector3} axis - The (normalized) axis vector. + * @param {number} angle - The angle in radians. + */ + setRotationFromAxisAngle( axis, angle ) { + + // assumes axis is normalized + + this.quaternion.setFromAxisAngle( axis, angle ); + + } + + /** + * Sets the given rotation represented as Euler angles to the 3D object. + * + * @param {Euler} euler - The Euler angles. + */ + setRotationFromEuler( euler ) { + + this.quaternion.setFromEuler( euler, true ); + + } + + /** + * Sets the given rotation represented as rotation matrix to the 3D object. + * + * @param {Matrix4} m - Although a 4x4 matrix is expected, the upper 3x3 portion must be + * a pure rotation matrix (i.e, unscaled). + */ + setRotationFromMatrix( m ) { + + // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) + + this.quaternion.setFromRotationMatrix( m ); + + } + + /** + * Sets the given rotation represented as a Quaternion to the 3D object. + * + * @param {Quaternion} q - The Quaternion + */ + setRotationFromQuaternion( q ) { + + // assumes q is normalized + + this.quaternion.copy( q ); + + } + + /** + * Rotates the 3D object along an axis in local space. + * + * @param {Vector3} axis - The (normalized) axis vector. + * @param {number} angle - The angle in radians. + * @return {Object3D} A reference to this instance. + */ + rotateOnAxis( axis, angle ) { + + // rotate object on axis in object space + // axis is assumed to be normalized + + _q1.setFromAxisAngle( axis, angle ); + + this.quaternion.multiply( _q1 ); + + return this; + + } + + /** + * Rotates the 3D object along an axis in world space. + * + * @param {Vector3} axis - The (normalized) axis vector. + * @param {number} angle - The angle in radians. + * @return {Object3D} A reference to this instance. + */ + rotateOnWorldAxis( axis, angle ) { + + // rotate object on axis in world space + // axis is assumed to be normalized + // method assumes no rotated parent + + _q1.setFromAxisAngle( axis, angle ); + + this.quaternion.premultiply( _q1 ); + + return this; + + } + + /** + * Rotates the 3D object around its X axis in local space. + * + * @param {number} angle - The angle in radians. + * @return {Object3D} A reference to this instance. + */ + rotateX( angle ) { + + return this.rotateOnAxis( _xAxis, angle ); + + } + + /** + * Rotates the 3D object around its Y axis in local space. + * + * @param {number} angle - The angle in radians. + * @return {Object3D} A reference to this instance. + */ + rotateY( angle ) { + + return this.rotateOnAxis( _yAxis, angle ); + + } + + /** + * Rotates the 3D object around its Z axis in local space. + * + * @param {number} angle - The angle in radians. + * @return {Object3D} A reference to this instance. + */ + rotateZ( angle ) { + + return this.rotateOnAxis( _zAxis, angle ); + + } + + /** + * Translate the 3D object by a distance along the given axis in local space. + * + * @param {Vector3} axis - The (normalized) axis vector. + * @param {number} distance - The distance in world units. + * @return {Object3D} A reference to this instance. + */ + translateOnAxis( axis, distance ) { + + // translate object by distance along axis in object space + // axis is assumed to be normalized + + _v1$6.copy( axis ).applyQuaternion( this.quaternion ); + + this.position.add( _v1$6.multiplyScalar( distance ) ); + + return this; + + } + + /** + * Translate the 3D object by a distance along its X-axis in local space. + * + * @param {number} distance - The distance in world units. + * @return {Object3D} A reference to this instance. + */ + translateX( distance ) { + + return this.translateOnAxis( _xAxis, distance ); + + } + + /** + * Translate the 3D object by a distance along its Y-axis in local space. + * + * @param {number} distance - The distance in world units. + * @return {Object3D} A reference to this instance. + */ + translateY( distance ) { + + return this.translateOnAxis( _yAxis, distance ); + + } + + /** + * Translate the 3D object by a distance along its Z-axis in local space. + * + * @param {number} distance - The distance in world units. + * @return {Object3D} A reference to this instance. + */ + translateZ( distance ) { + + return this.translateOnAxis( _zAxis, distance ); + + } + + /** + * Converts the given vector from this 3D object's local space to world space. + * + * @param {Vector3} vector - The vector to convert. + * @return {Vector3} The converted vector. + */ + localToWorld( vector ) { + + this.updateWorldMatrix( true, false ); + + return vector.applyMatrix4( this.matrixWorld ); + + } + + /** + * Converts the given vector from this 3D object's world space to local space. + * + * @param {Vector3} vector - The vector to convert. + * @return {Vector3} The converted vector. + */ + worldToLocal( vector ) { + + this.updateWorldMatrix( true, false ); + + return vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() ); + + } + + /** + * Rotates the object to face a point in world space. + * + * This method does not support objects having non-uniformly-scaled parent(s). + * + * @param {number|Vector3} x - The x coordinate in world space. Alternatively, a vector representing a position in world space + * @param {number} [y] - The y coordinate in world space. + * @param {number} [z] - The z coordinate in world space. + */ + lookAt( x, y, z ) { + + // This method does not support objects having non-uniformly-scaled parent(s) + + if ( x.isVector3 ) { + + _target.copy( x ); + + } else { + + _target.set( x, y, z ); + + } + + const parent = this.parent; + + this.updateWorldMatrix( true, false ); + + _position$4.setFromMatrixPosition( this.matrixWorld ); + + if ( this.isCamera || this.isLight ) { + + _m1$1.lookAt( _position$4, _target, this.up ); + + } else { + + _m1$1.lookAt( _target, _position$4, this.up ); + + } + + this.quaternion.setFromRotationMatrix( _m1$1 ); + + if ( parent ) { + + _m1$1.extractRotation( parent.matrixWorld ); + _q1.setFromRotationMatrix( _m1$1 ); + this.quaternion.premultiply( _q1.invert() ); + + } + + } + + /** + * Adds the given 3D object as a child to this 3D object. An arbitrary number of + * objects may be added. Any current parent on an object passed in here will be + * removed, since an object can have at most one parent. + * + * @fires Object3D#added + * @fires Object3D#childadded + * @param {Object3D} object - The 3D object to add. + * @return {Object3D} A reference to this instance. + */ + add( object ) { + + if ( arguments.length > 1 ) { + + for ( let i = 0; i < arguments.length; i ++ ) { + + this.add( arguments[ i ] ); + + } + + return this; + + } + + if ( object === this ) { + + error( 'Object3D.add: object can\'t be added as a child of itself.', object ); + return this; + + } + + if ( object && object.isObject3D ) { + + object.removeFromParent(); + object.parent = this; + this.children.push( object ); + + object.dispatchEvent( _addedEvent ); + + _childaddedEvent.child = object; + this.dispatchEvent( _childaddedEvent ); + _childaddedEvent.child = null; + + } else { + + error( 'Object3D.add: object not an instance of THREE.Object3D.', object ); + + } + + return this; + + } + + /** + * Removes the given 3D object as child from this 3D object. + * An arbitrary number of objects may be removed. + * + * @fires Object3D#removed + * @fires Object3D#childremoved + * @param {Object3D} object - The 3D object to remove. + * @return {Object3D} A reference to this instance. + */ + remove( object ) { + + if ( arguments.length > 1 ) { + + for ( let i = 0; i < arguments.length; i ++ ) { + + this.remove( arguments[ i ] ); + + } + + return this; + + } + + const index = this.children.indexOf( object ); + + if ( index !== -1 ) { + + object.parent = null; + this.children.splice( index, 1 ); + + object.dispatchEvent( _removedEvent ); + + _childremovedEvent.child = object; + this.dispatchEvent( _childremovedEvent ); + _childremovedEvent.child = null; + + } + + return this; + + } + + /** + * Removes this 3D object from its current parent. + * + * @fires Object3D#removed + * @fires Object3D#childremoved + * @return {Object3D} A reference to this instance. + */ + removeFromParent() { + + const parent = this.parent; + + if ( parent !== null ) { + + parent.remove( this ); + + } + + return this; + + } + + /** + * Removes all child objects. + * + * @fires Object3D#removed + * @fires Object3D#childremoved + * @return {Object3D} A reference to this instance. + */ + clear() { + + return this.remove( ... this.children ); + + } + + /** + * Adds the given 3D object as a child of this 3D object, while maintaining the object's world + * transform. This method does not support scene graphs having non-uniformly-scaled nodes(s). + * + * @fires Object3D#added + * @fires Object3D#childadded + * @param {Object3D} object - The 3D object to attach. + * @return {Object3D} A reference to this instance. + */ + attach( object ) { + + // adds object as a child of this, while maintaining the object's world transform + + // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s) + + this.updateWorldMatrix( true, false ); + + _m1$1.copy( this.matrixWorld ).invert(); + + if ( object.parent !== null ) { + + object.parent.updateWorldMatrix( true, false ); + + _m1$1.multiply( object.parent.matrixWorld ); + + } + + object.applyMatrix4( _m1$1 ); + + object.removeFromParent(); + object.parent = this; + this.children.push( object ); + + object.updateWorldMatrix( false, true ); + + object.dispatchEvent( _addedEvent ); + + _childaddedEvent.child = object; + this.dispatchEvent( _childaddedEvent ); + _childaddedEvent.child = null; + + return this; + + } + + /** + * Searches through the 3D object and its children, starting with the 3D object + * itself, and returns the first with a matching ID. + * + * @param {number} id - The id. + * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found. + */ + getObjectById( id ) { + + return this.getObjectByProperty( 'id', id ); + + } + + /** + * Searches through the 3D object and its children, starting with the 3D object + * itself, and returns the first with a matching name. + * + * @param {string} name - The name. + * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found. + */ + getObjectByName( name ) { + + return this.getObjectByProperty( 'name', name ); + + } + + /** + * Searches through the 3D object and its children, starting with the 3D object + * itself, and returns the first with a matching property value. + * + * @param {string} name - The name of the property. + * @param {any} value - The value. + * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found. + */ + getObjectByProperty( name, value ) { + + if ( this[ name ] === value ) return this; + + for ( let i = 0, l = this.children.length; i < l; i ++ ) { + + const child = this.children[ i ]; + const object = child.getObjectByProperty( name, value ); + + if ( object !== undefined ) { + + return object; + + } + + } + + return undefined; + + } + + /** + * Searches through the 3D object and its children, starting with the 3D object + * itself, and returns all 3D objects with a matching property value. + * + * @param {string} name - The name of the property. + * @param {any} value - The value. + * @param {Array} result - The method stores the result in this array. + * @return {Array} The found 3D objects. + */ + getObjectsByProperty( name, value, result = [] ) { + + if ( this[ name ] === value ) result.push( this ); + + const children = this.children; + + for ( let i = 0, l = children.length; i < l; i ++ ) { + + children[ i ].getObjectsByProperty( name, value, result ); + + } + + return result; + + } + + /** + * Returns a vector representing the position of the 3D object in world space. + * + * @param {Vector3} target - The target vector the result is stored to. + * @return {Vector3} The 3D object's position in world space. + */ + getWorldPosition( target ) { + + this.updateWorldMatrix( true, false ); + + return target.setFromMatrixPosition( this.matrixWorld ); + + } + + /** + * Returns a Quaternion representing the position of the 3D object in world space. + * + * @param {Quaternion} target - The target Quaternion the result is stored to. + * @return {Quaternion} The 3D object's rotation in world space. + */ + getWorldQuaternion( target ) { + + this.updateWorldMatrix( true, false ); + + this.matrixWorld.decompose( _position$4, target, _scale$3 ); + + return target; + + } + + /** + * Returns a vector representing the scale of the 3D object in world space. + * + * @param {Vector3} target - The target vector the result is stored to. + * @return {Vector3} The 3D object's scale in world space. + */ + getWorldScale( target ) { + + this.updateWorldMatrix( true, false ); + + this.matrixWorld.decompose( _position$4, _quaternion$3, target ); + + return target; + + } + + /** + * Returns a vector representing the ("look") direction of the 3D object in world space. + * + * @param {Vector3} target - The target vector the result is stored to. + * @return {Vector3} The 3D object's direction in world space. + */ + getWorldDirection( target ) { + + this.updateWorldMatrix( true, false ); + + const e = this.matrixWorld.elements; + + return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize(); + + } + + /** + * Abstract method to get intersections between a casted ray and this + * 3D object. Renderable 3D objects such as {@link Mesh}, {@link Line} or {@link Points} + * implement this method in order to use raycasting. + * + * @abstract + * @param {Raycaster} raycaster - The raycaster. + * @param {Array} intersects - An array holding the result of the method. + */ + raycast( /* raycaster, intersects */ ) {} + + /** + * Abstract method to test whether this 3D object intersects the given frustum. + * Renderable 3D objects such as {@link Mesh}, {@link Line} or {@link Points} + * implement this method in order to use frustum culling. + * + * @abstract + * @param {Frustum|FrustumArray} frustum - The frustum to test. + * @return {boolean|undefined} Whether this 3D object intersects the given frustum or not. + */ + intersectsFrustum( /* frustum */ ) {} + + /** + * Executes the callback on this 3D object and all descendants. + * + * Note: Modifying the scene graph inside the callback is discouraged. + * + * @param {Function} callback - A callback function that allows to process the current 3D object. + */ + traverse( callback ) { + + callback( this ); + + const children = this.children; + + for ( let i = 0, l = children.length; i < l; i ++ ) { + + children[ i ].traverse( callback ); + + } + + } + + /** + * Like {@link Object3D#traverse}, but the callback will only be executed for visible 3D objects. + * Descendants of invisible 3D objects are not traversed. + * + * Note: Modifying the scene graph inside the callback is discouraged. + * + * @param {Function} callback - A callback function that allows to process the current 3D object. + */ + traverseVisible( callback ) { + + if ( this.visible === false ) return; + + callback( this ); + + const children = this.children; + + for ( let i = 0, l = children.length; i < l; i ++ ) { + + children[ i ].traverseVisible( callback ); + + } + + } + + /** + * Like {@link Object3D#traverse}, but the callback will only be executed for all ancestors. + * + * Note: Modifying the scene graph inside the callback is discouraged. + * + * @param {Function} callback - A callback function that allows to process the current 3D object. + */ + traverseAncestors( callback ) { + + const parent = this.parent; + + if ( parent !== null ) { + + callback( parent ); + + parent.traverseAncestors( callback ); + + } + + } + + /** + * Updates the transformation matrix in local space by computing it from the current + * position, rotation and scale values. + */ + updateMatrix() { + + this.matrix.compose( this.position, this.quaternion, this.scale ); + + const pivot = this.pivot; + + if ( pivot !== null ) { + + const px = pivot.x, py = pivot.y, pz = pivot.z; + const te = this.matrix.elements; + + te[ 12 ] += px - te[ 0 ] * px - te[ 4 ] * py - te[ 8 ] * pz; + te[ 13 ] += py - te[ 1 ] * px - te[ 5 ] * py - te[ 9 ] * pz; + te[ 14 ] += pz - te[ 2 ] * px - te[ 6 ] * py - te[ 10 ] * pz; + + } + + this.matrixWorldNeedsUpdate = true; + + } + + /** + * Updates the transformation matrix in world space of this 3D objects and its descendants. + * + * To ensure correct results, this method also recomputes the 3D object's transformation matrix in + * local space. The computation of the local and world matrix can be controlled with the + * {@link Object3D#matrixAutoUpdate} and {@link Object3D#matrixWorldAutoUpdate} flags which are both + * `true` by default. Set these flags to `false` if you need more control over the update matrix process. + * + * @param {boolean} [force=false] - When set to `true`, a recomputation of world matrices is forced even + * when {@link Object3D#matrixWorldNeedsUpdate} is `false`. + */ + updateMatrixWorld( force ) { + + if ( this.matrixAutoUpdate ) this.updateMatrix(); + + if ( this.matrixWorldNeedsUpdate || force ) { + + if ( this.matrixWorldAutoUpdate === true ) { + + if ( this.parent === null ) { + + this.matrixWorld.copy( this.matrix ); + + } else { + + this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix ); + + } + + } + + this.matrixWorldNeedsUpdate = false; + + force = true; + + } + + // make sure descendants are updated if required + + const children = this.children; + + for ( let i = 0, l = children.length; i < l; i ++ ) { + + const child = children[ i ]; + + child.updateMatrixWorld( force ); + + } + + } + + /** + * An alternative version of {@link Object3D#updateMatrixWorld} with more control over the + * update of ancestor and descendant nodes. + * + * @param {boolean} [updateParents=false] Whether ancestor nodes should be updated or not. + * @param {boolean} [updateChildren=false] Whether descendant nodes should be updated or not. + * @param {boolean} [force=false] - When set to `true`, a recomputation of world matrices is forced even + * when {@link Object3D#matrixWorldNeedsUpdate} is `false`. + */ + updateWorldMatrix( updateParents, updateChildren, force = false ) { + + const parent = this.parent; + + if ( updateParents === true && parent !== null ) { + + parent.updateWorldMatrix( true, false ); + + } + + if ( this.matrixAutoUpdate ) this.updateMatrix(); + + if ( this.matrixWorldNeedsUpdate || force ) { + + if ( this.matrixWorldAutoUpdate === true ) { + + if ( this.parent === null ) { + + this.matrixWorld.copy( this.matrix ); + + } else { + + this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix ); + + } + + } + + this.matrixWorldNeedsUpdate = false; + + force = true; + + } + + // make sure descendants are updated + + if ( updateChildren === true ) { + + const children = this.children; + + for ( let i = 0, l = children.length; i < l; i ++ ) { + + const child = children[ i ]; + + child.updateWorldMatrix( false, true, force ); + + } + + } + + } + + /** + * Serializes the 3D object into JSON. + * + * @param {?(Object|string)} meta - An optional value holding meta information about the serialization. + * @return {Object} A JSON object representing the serialized 3D object. + * @see {@link ObjectLoader#parse} + */ + toJSON( meta ) { + + // meta is a string when called from JSON.stringify + const isRootObject = ( meta === undefined || typeof meta === 'string' ); + + const output = {}; + + // meta is a hash used to collect geometries, materials. + // not providing it implies that this is the root object + // being serialized. + if ( isRootObject ) { + + // initialize meta obj + meta = { + geometries: {}, + materials: {}, + textures: {}, + images: {}, + shapes: {}, + skeletons: {}, + animations: {}, + nodes: {} + }; + + output.metadata = { + version: 4.7, + type: 'Object', + generator: 'Object3D.toJSON' + }; + + } + + // standard Object3D serialization + + const object = {}; + + object.uuid = this.uuid; + object.type = this.type; + + object.name = this.name; + object.castShadow = this.castShadow; + object.receiveShadow = this.receiveShadow; + object.visible = this.visible; + object.frustumCulled = this.frustumCulled; + object.renderOrder = this.renderOrder; + object.static = this.static; + object.matrixAutoUpdate = this.matrixAutoUpdate; + + if ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData; + + object.layers = this.layers.mask; + object.matrix = this.matrix.toArray(); + object.up = this.up.toArray(); + + if ( this.pivot !== null ) object.pivot = this.pivot.toArray(); + + if ( this.morphTargetDictionary !== undefined ) object.morphTargetDictionary = Object.assign( {}, this.morphTargetDictionary ); + if ( this.morphTargetInfluences !== undefined ) object.morphTargetInfluences = this.morphTargetInfluences.slice(); + + // object specific properties + + if ( this.isInstancedMesh ) { + + object.type = 'InstancedMesh'; + object.count = this.count; + object.instanceMatrix = this.instanceMatrix.toJSON(); + if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON(); + + } + + if ( this.isBatchedMesh ) { + + object.type = 'BatchedMesh'; + object.perObjectFrustumCulled = this.perObjectFrustumCulled; + object.sortObjects = this.sortObjects; + + object.drawRanges = this._drawRanges; + object.reservedRanges = this._reservedRanges; + + object.geometryInfo = this._geometryInfo.map( info => ( { + ...info, + boundingBox: info.boundingBox ? info.boundingBox.toJSON() : undefined, + boundingSphere: info.boundingSphere ? info.boundingSphere.toJSON() : undefined + } ) ); + object.instanceInfo = this._instanceInfo.map( info => ( { ...info } ) ); + + object.availableInstanceIds = this._availableInstanceIds.slice(); + object.availableGeometryIds = this._availableGeometryIds.slice(); + + object.nextIndexStart = this._nextIndexStart; + object.nextVertexStart = this._nextVertexStart; + object.geometryCount = this._geometryCount; + + object.maxInstanceCount = this._maxInstanceCount; + object.maxVertexCount = this._maxVertexCount; + object.maxIndexCount = this._maxIndexCount; + + object.geometryInitialized = this._geometryInitialized; + + object.matricesTexture = this._matricesTexture.toJSON( meta ); + + object.indirectTexture = this._indirectTexture.toJSON( meta ); + + if ( this._colorsTexture !== null ) { + + object.colorsTexture = this._colorsTexture.toJSON( meta ); + + } + + if ( this.boundingSphere !== null ) { + + object.boundingSphere = this.boundingSphere.toJSON(); + + } + + if ( this.boundingBox !== null ) { + + object.boundingBox = this.boundingBox.toJSON(); + + } + + } + + // + + function serialize( library, element ) { + + if ( library[ element.uuid ] === undefined ) { + + library[ element.uuid ] = element.toJSON( meta ); + + } + + return element.uuid; + + } + + if ( this.isScene ) { + + if ( this.background ) { + + if ( this.background.isColor ) { + + object.background = this.background.toJSON(); + + } else if ( this.background.isTexture ) { + + object.background = this.background.toJSON( meta ).uuid; + + } + + } + + if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) { + + object.environment = this.environment.toJSON( meta ).uuid; + + } + + } else if ( this.isMesh || this.isLine || this.isPoints ) { + + object.geometry = serialize( meta.geometries, this.geometry ); + + const parameters = this.geometry.parameters; + + if ( parameters !== undefined && parameters.shapes !== undefined ) { + + const shapes = parameters.shapes; + + if ( Array.isArray( shapes ) ) { + + for ( let i = 0, l = shapes.length; i < l; i ++ ) { + + const shape = shapes[ i ]; + + serialize( meta.shapes, shape ); + + } + + } else { + + serialize( meta.shapes, shapes ); + + } + + } + + } + + if ( this.isSkinnedMesh ) { + + object.bindMode = this.bindMode; + object.bindMatrix = this.bindMatrix.toArray(); + + if ( this.skeleton !== undefined ) { + + serialize( meta.skeletons, this.skeleton ); + + object.skeleton = this.skeleton.uuid; + + } + + } + + if ( this.material !== undefined ) { + + if ( Array.isArray( this.material ) ) { + + const uuids = []; + + for ( let i = 0, l = this.material.length; i < l; i ++ ) { + + uuids.push( serialize( meta.materials, this.material[ i ] ) ); + + } + + object.material = uuids; + + } else { + + object.material = serialize( meta.materials, this.material ); + + } + + } + + // + + if ( this.children.length > 0 ) { + + object.children = []; + + for ( let i = 0; i < this.children.length; i ++ ) { + + object.children.push( this.children[ i ].toJSON( meta ).object ); + + } + + } + + // + + if ( this.animations.length > 0 ) { + + object.animations = []; + + for ( let i = 0; i < this.animations.length; i ++ ) { + + const animation = this.animations[ i ]; + + object.animations.push( serialize( meta.animations, animation ) ); + + } + + } + + if ( isRootObject ) { + + const geometries = extractFromCache( meta.geometries ); + const materials = extractFromCache( meta.materials ); + const textures = extractFromCache( meta.textures ); + const images = extractFromCache( meta.images ); + const shapes = extractFromCache( meta.shapes ); + const skeletons = extractFromCache( meta.skeletons ); + const animations = extractFromCache( meta.animations ); + const nodes = extractFromCache( meta.nodes ); + + if ( geometries.length > 0 ) output.geometries = geometries; + if ( materials.length > 0 ) output.materials = materials; + if ( textures.length > 0 ) output.textures = textures; + if ( images.length > 0 ) output.images = images; + if ( shapes.length > 0 ) output.shapes = shapes; + if ( skeletons.length > 0 ) output.skeletons = skeletons; + if ( animations.length > 0 ) output.animations = animations; + if ( nodes.length > 0 ) output.nodes = nodes; + + } + + output.object = object; + + return output; + + // extract data from the cache hash + // remove metadata on each item + // and return as array + function extractFromCache( cache ) { + + const values = []; + for ( const key in cache ) { + + const data = cache[ key ]; + delete data.metadata; + values.push( data ); + + } + + return values; + + } + + } + + /** + * Returns a new 3D object with copied values from this instance. + * + * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are also cloned. + * @return {Object3D} A clone of this instance. + */ + clone( recursive ) { + + return new this.constructor().copy( this, recursive ); + + } + + /** + * Copies the values of the given 3D object to this instance. + * + * @param {Object3D} source - The 3D object to copy. + * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are cloned. + * @return {Object3D} A reference to this instance. + */ + copy( source, recursive = true ) { + + this.name = source.name; + + this.up.copy( source.up ); + + this.position.copy( source.position ); + this.rotation.order = source.rotation.order; + this.quaternion.copy( source.quaternion ); + this.scale.copy( source.scale ); + + this.pivot = ( source.pivot !== null ) ? source.pivot.clone() : null; + + this.matrix.copy( source.matrix ); + this.matrixWorld.copy( source.matrixWorld ); + + this.matrixAutoUpdate = source.matrixAutoUpdate; + + this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate; + this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate; + + this.layers.mask = source.layers.mask; + this.visible = source.visible; + + this.castShadow = source.castShadow; + this.receiveShadow = source.receiveShadow; + + this.frustumCulled = source.frustumCulled; + this.renderOrder = source.renderOrder; + + this.static = source.static; + + this.animations = source.animations.slice(); + + this.userData = JSON.parse( JSON.stringify( source.userData ) ); + + if ( recursive === true ) { + + for ( let i = 0; i < source.children.length; i ++ ) { + + const child = source.children[ i ]; + this.add( child.clone() ); + + } + + } + + return this; + + } + + /** + * Frees the GPU-related resources allocated by this instance. Call this + * method whenever this instance is no longer used in your app. + * + * Geometries, materials and textures are potentially shared with other + * 3D objects and must be disposed of separately. + * + * @fires Object3D#dispose + */ + dispose() { + + /** + * Fires when the 3D object has been disposed of. + * + * @event Object3D#dispose + * @type {Object} + */ + this.dispatchEvent( { type: 'dispose' } ); + + } + +} + +/** + * The default up direction for objects, also used as the default + * position for {@link DirectionalLight} and {@link HemisphereLight}. + * + * @static + * @type {Vector3} + * @default (0,1,0) + */ +Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 ); + +/** + * The default setting for {@link Object3D#matrixAutoUpdate} for + * newly created 3D objects. + * + * @static + * @type {boolean} + * @default true + */ +Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true; + +/** + * The default setting for {@link Object3D#matrixWorldAutoUpdate} for + * newly created 3D objects. + * + * @static + * @type {boolean} + * @default true + */ +Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true; + +/** + * This is almost identical to an {@link Object3D}. Its purpose is to + * make working with groups of objects syntactically clearer. + * + * ```js + * // Create a group and add the two cubes. + * // These cubes can now be rotated / scaled etc as a group. + * const group = new THREE.Group(); + * + * group.add( meshA ); + * group.add( meshB ); + * + * scene.add( group ); + * ``` + * + * @augments Object3D + */ +class Group extends Object3D { + + constructor() { + + super(); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isGroup = true; + + this.type = 'Group'; + + } + +} + +const _moveEvent = { type: 'move' }; + +/** + * Class for representing a XR controller with its + * different coordinate systems. + * + * @private + */ +class WebXRController { + + /** + * Constructs a new XR controller. + */ + constructor() { + + /** + * A group representing the target ray space + * of the XR controller. + * + * @private + * @type {?Group} + * @default null + */ + this._targetRay = null; + + /** + * A group representing the grip space + * of the XR controller. + * + * @private + * @type {?Group} + * @default null + */ + this._grip = null; + + /** + * A group representing the hand space + * of the XR controller. + * + * @private + * @type {?Group} + * @default null + */ + this._hand = null; + + } + + /** + * Returns a group representing the hand space of the XR controller. + * + * @return {Group} A group representing the hand space of the XR controller. + */ + getHandSpace() { + + if ( this._hand === null ) { + + this._hand = new Group(); + this._hand.matrixAutoUpdate = false; + this._hand.visible = false; + + this._hand.joints = {}; + this._hand.inputState = { pinching: false }; + + } + + return this._hand; + + } + + /** + * Returns a group representing the target ray space of the XR controller. + * + * @return {Group} A group representing the target ray space of the XR controller. + */ + getTargetRaySpace() { + + if ( this._targetRay === null ) { + + this._targetRay = new Group(); + this._targetRay.matrixAutoUpdate = false; + this._targetRay.visible = false; + this._targetRay.hasLinearVelocity = false; + this._targetRay.linearVelocity = new Vector3(); + this._targetRay.hasAngularVelocity = false; + this._targetRay.angularVelocity = new Vector3(); + + } + + return this._targetRay; + + } + + /** + * Returns a group representing the grip space of the XR controller. + * + * @return {Group} A group representing the grip space of the XR controller. + */ + getGripSpace() { + + if ( this._grip === null ) { + + this._grip = new Group(); + this._grip.matrixAutoUpdate = false; + this._grip.visible = false; + this._grip.hasLinearVelocity = false; + this._grip.linearVelocity = new Vector3(); + this._grip.hasAngularVelocity = false; + this._grip.angularVelocity = new Vector3(); + this._grip.eventsEnabled = false; + + } + + return this._grip; + + } + + /** + * Dispatches the given event to the groups representing + * the different coordinate spaces of the XR controller. + * + * @param {Object} event - The event to dispatch. + * @return {WebXRController} A reference to this instance. + */ + dispatchEvent( event ) { + + if ( this._targetRay !== null ) { + + this._targetRay.dispatchEvent( event ); + + } + + if ( this._grip !== null ) { + + this._grip.dispatchEvent( event ); + + } + + if ( this._hand !== null ) { + + this._hand.dispatchEvent( event ); + + } + + return this; + + } + + /** + * Connects the controller with the given XR input source. + * + * @param {XRInputSource} inputSource - The input source. + * @return {WebXRController} A reference to this instance. + */ + connect( inputSource ) { + + if ( inputSource && inputSource.hand ) { + + const hand = this._hand; + + if ( hand ) { + + for ( const inputjoint of inputSource.hand.values() ) { + + // Initialize hand with joints when connected + this._getHandJoint( hand, inputjoint ); + + } + + } + + } + + this.dispatchEvent( { type: 'connected', data: inputSource } ); + + return this; + + } + + /** + * Disconnects the controller from the given XR input source. + * + * @param {XRInputSource} inputSource - The input source. + * @return {WebXRController} A reference to this instance. + */ + disconnect( inputSource ) { + + this.dispatchEvent( { type: 'disconnected', data: inputSource } ); + + if ( this._targetRay !== null ) { + + this._targetRay.visible = false; + + } + + if ( this._grip !== null ) { + + this._grip.visible = false; + + } + + if ( this._hand !== null ) { + + this._hand.visible = false; + + } + + return this; + + } + + /** + * Updates the controller with the given input source, XR frame and reference space. + * This updates the transformations of the groups that represent the different + * coordinate systems of the controller. + * + * @param {XRInputSource} inputSource - The input source. + * @param {XRFrame} frame - The XR frame. + * @param {XRReferenceSpace} referenceSpace - The reference space. + * @return {WebXRController} A reference to this instance. + */ + update( inputSource, frame, referenceSpace ) { + + let inputPose = null; + let gripPose = null; + let handPose = null; + + const targetRay = this._targetRay; + const grip = this._grip; + const hand = this._hand; + + if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) { + + if ( hand && inputSource.hand ) { + + handPose = true; + + for ( const inputjoint of inputSource.hand.values() ) { + + // Update the joints groups with the XRJoint poses + const jointPose = frame.getJointPose( inputjoint, referenceSpace ); + + // The transform of this joint will be updated with the joint pose on each frame + const joint = this._getHandJoint( hand, inputjoint ); + + if ( jointPose !== null ) { + + joint.matrix.fromArray( jointPose.transform.matrix ); + joint.matrix.decompose( joint.position, joint.rotation, joint.scale ); + joint.matrixWorldNeedsUpdate = true; + joint.jointRadius = jointPose.radius; + + } + + joint.visible = jointPose !== null; + + } + + // Custom events + + // Check pinchz + const indexTip = hand.joints[ 'index-finger-tip' ]; + const thumbTip = hand.joints[ 'thumb-tip' ]; + const distance = indexTip.position.distanceTo( thumbTip.position ); + + const distanceToPinch = 0.02; + const threshold = 0.005; + + if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) { + + hand.inputState.pinching = false; + this.dispatchEvent( { + type: 'pinchend', + handedness: inputSource.handedness, + target: this + } ); + + } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) { + + hand.inputState.pinching = true; + this.dispatchEvent( { + type: 'pinchstart', + handedness: inputSource.handedness, + target: this + } ); + + } + + } else { + + if ( grip !== null && inputSource.gripSpace ) { + + gripPose = frame.getPose( inputSource.gripSpace, referenceSpace ); + + if ( gripPose !== null ) { + + grip.matrix.fromArray( gripPose.transform.matrix ); + grip.matrix.decompose( grip.position, grip.rotation, grip.scale ); + grip.matrixWorldNeedsUpdate = true; + + if ( gripPose.linearVelocity ) { + + grip.hasLinearVelocity = true; + grip.linearVelocity.copy( gripPose.linearVelocity ); + + } else { + + grip.hasLinearVelocity = false; + + } + + if ( gripPose.angularVelocity ) { + + grip.hasAngularVelocity = true; + grip.angularVelocity.copy( gripPose.angularVelocity ); + + } else { + + grip.hasAngularVelocity = false; + + } + + // grip update event if enabled + if ( grip.eventsEnabled ) { + + grip.dispatchEvent( { + type: 'gripUpdated', + data: inputSource, + target: this + } ); + + } + + } + + } + + } + + if ( targetRay !== null ) { + + inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace ); + + // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it + if ( inputPose === null && gripPose !== null ) { + + inputPose = gripPose; + + } + + if ( inputPose !== null ) { + + targetRay.matrix.fromArray( inputPose.transform.matrix ); + targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale ); + targetRay.matrixWorldNeedsUpdate = true; + + if ( inputPose.linearVelocity ) { + + targetRay.hasLinearVelocity = true; + targetRay.linearVelocity.copy( inputPose.linearVelocity ); + + } else { + + targetRay.hasLinearVelocity = false; + + } + + if ( inputPose.angularVelocity ) { + + targetRay.hasAngularVelocity = true; + targetRay.angularVelocity.copy( inputPose.angularVelocity ); + + } else { + + targetRay.hasAngularVelocity = false; + + } + + this.dispatchEvent( _moveEvent ); + + } + + } + + + } + + if ( targetRay !== null ) { + + targetRay.visible = ( inputPose !== null ); + + } + + if ( grip !== null ) { + + grip.visible = ( gripPose !== null ); + + } + + if ( hand !== null ) { + + hand.visible = ( handPose !== null ); + + } + + return this; + + } + + /** + * Returns a group representing the hand joint for the given input joint. + * + * @private + * @param {Group} hand - The group representing the hand space. + * @param {XRJointSpace} inputjoint - The hand joint data. + * @return {Group} A group representing the hand joint for the given input joint. + */ + _getHandJoint( hand, inputjoint ) { + + if ( hand.joints[ inputjoint.jointName ] === undefined ) { + + const joint = new Group(); + joint.matrixAutoUpdate = false; + joint.visible = false; + hand.joints[ inputjoint.jointName ] = joint; + + hand.add( joint ); + + } + + return hand.joints[ inputjoint.jointName ]; + + } + +} + +const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF, + 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2, + 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50, + 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B, + 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B, + 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F, + 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3, + 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222, + 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700, + 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4, + 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00, + 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3, + 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA, + 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32, + 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3, + 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC, + 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD, + 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6, + 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9, + 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F, + 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE, + 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA, + 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0, + 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 }; + +const _hslA = { h: 0, s: 0, l: 0 }; +const _hslB = { h: 0, s: 0, l: 0 }; + +function hue2rgb( p, q, t ) { + + if ( t < 0 ) t += 1; + if ( t > 1 ) t -= 1; + if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t; + if ( t < 1 / 2 ) return q; + if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t ); + return p; + +} + +/** + * A Color instance is represented by RGB components in the linear working + * color space, which defaults to `LinearSRGBColorSpace`. Inputs + * conventionally using `SRGBColorSpace` (such as hexadecimals and CSS + * strings) are converted to the working color space automatically. + * + * ```js + * // converted automatically from SRGBColorSpace to LinearSRGBColorSpace + * const color = new THREE.Color().setHex( 0x112233 ); + * ``` + * Source color spaces may be specified explicitly, to ensure correct conversions. + * ```js + * // assumed already LinearSRGBColorSpace; no conversion + * const color = new THREE.Color().setRGB( 0.5, 0.5, 0.5 ); + * + * // converted explicitly from SRGBColorSpace to LinearSRGBColorSpace + * const color = new THREE.Color().setRGB( 0.5, 0.5, 0.5, SRGBColorSpace ); + * ``` + * If THREE.ColorManagement is disabled, no conversions occur. For details, + * see Color management. Iterating through a Color instance will yield + * its components (r, g, b) in the corresponding order. A Color can be initialised + * in any of the following ways: + * ```js + * //empty constructor - will default white + * const color1 = new THREE.Color(); + * + * //Hexadecimal color (recommended) + * const color2 = new THREE.Color( 0xff0000 ); + * + * //RGB string + * const color3 = new THREE.Color("rgb(255, 0, 0)"); + * const color4 = new THREE.Color("rgb(100%, 0%, 0%)"); + * + * //X11 color name - all 140 color names are supported. + * //Note the lack of CamelCase in the name + * const color5 = new THREE.Color( 'skyblue' ); + * //HSL string + * const color6 = new THREE.Color("hsl(0, 100%, 50%)"); + * + * //Separate RGB values between 0 and 1 + * const color7 = new THREE.Color( 1, 0, 0 ); + * ``` + */ +class Color { + + /** + * Constructs a new color. + * + * Note that standard method of specifying color in three.js is with a hexadecimal triplet, + * and that method is used throughout the rest of the documentation. + * + * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are + * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance. + * @param {number} [g] - The green component. + * @param {number} [b] - The blue component. + */ + constructor( r, g, b ) { + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isColor = true; + + /** + * The red component. + * + * @type {number} + * @default 1 + */ + this.r = 1; + + /** + * The green component. + * + * @type {number} + * @default 1 + */ + this.g = 1; + + /** + * The blue component. + * + * @type {number} + * @default 1 + */ + this.b = 1; + + return this.set( r, g, b ); + + } + + /** + * Sets the colors's components from the given values. + * + * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are + * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance. + * @param {number} [g] - The green component. + * @param {number} [b] - The blue component. + * @return {Color} A reference to this color. + */ + set( r, g, b ) { + + if ( g === undefined && b === undefined ) { + + // r is THREE.Color, hex or string + + const value = r; + + if ( value && value.isColor ) { + + this.copy( value ); + + } else if ( typeof value === 'number' ) { + + this.setHex( value ); + + } else if ( typeof value === 'string' ) { + + this.setStyle( value ); + + } + + } else { + + this.setRGB( r, g, b ); + + } + + return this; + + } + + /** + * Sets the colors's components to the given scalar value. + * + * @param {number} scalar - The scalar value. + * @return {Color} A reference to this color. + */ + setScalar( scalar ) { + + this.r = scalar; + this.g = scalar; + this.b = scalar; + + return this; + + } + + /** + * Sets this color from a hexadecimal value. + * + * @param {number} hex - The hexadecimal value. + * @param {string} [colorSpace=SRGBColorSpace] - The color space. + * @return {Color} A reference to this color. + */ + setHex( hex, colorSpace = SRGBColorSpace ) { + + hex = Math.floor( hex ); + + this.r = ( hex >> 16 & 255 ) / 255; + this.g = ( hex >> 8 & 255 ) / 255; + this.b = ( hex & 255 ) / 255; + + ColorManagement.colorSpaceToWorking( this, colorSpace ); + + return this; + + } + + /** + * Sets this color from RGB values. + * + * @param {number} r - Red channel value between `0.0` and `1.0`. + * @param {number} g - Green channel value between `0.0` and `1.0`. + * @param {number} b - Blue channel value between `0.0` and `1.0`. + * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space. + * @return {Color} A reference to this color. + */ + setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) { + + this.r = r; + this.g = g; + this.b = b; + + ColorManagement.colorSpaceToWorking( this, colorSpace ); + + return this; + + } + + /** + * Sets this color from RGB values. + * + * @param {number} h - Hue value between `0.0` and `1.0`. + * @param {number} s - Saturation value between `0.0` and `1.0`. + * @param {number} l - Lightness value between `0.0` and `1.0`. + * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space. + * @return {Color} A reference to this color. + */ + setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) { + + // h,s,l ranges are in 0.0 - 1.0 + h = euclideanModulo( h, 1 ); + s = clamp( s, 0, 1 ); + l = clamp( l, 0, 1 ); + + if ( s === 0 ) { + + this.r = this.g = this.b = l; + + } else { + + const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s ); + const q = ( 2 * l ) - p; + + this.r = hue2rgb( q, p, h + 1 / 3 ); + this.g = hue2rgb( q, p, h ); + this.b = hue2rgb( q, p, h - 1 / 3 ); + + } + + ColorManagement.colorSpaceToWorking( this, colorSpace ); + + return this; + + } + + /** + * Sets this color from a CSS-style string. For example, `rgb(250, 0,0)`, + * `rgb(100%, 0%, 0%)`, `hsl(0, 100%, 50%)`, `#ff0000`, `#f00`, or `red` ( or + * any [X11 color name](https://en.wikipedia.org/wiki/X11_color_names#Color_name_chart) - + * all 140 color names are supported). + * + * @param {string} style - Color as a CSS-style string. + * @param {string} [colorSpace=SRGBColorSpace] - The color space. + * @return {Color} A reference to this color. + */ + setStyle( style, colorSpace = SRGBColorSpace ) { + + function handleAlpha( string ) { + + if ( string === undefined ) return; + + if ( parseFloat( string ) < 1 ) { + + warn( 'Color: Alpha component of ' + style + ' will be ignored.' ); + + } + + } + + + let m; + + if ( m = /^(\w+)\(([^\)]*)\)/.exec( style ) ) { + + // rgb / hsl + + let color; + const name = m[ 1 ]; + const components = m[ 2 ]; + + switch ( name ) { + + case 'rgb': + case 'rgba': + + if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) { + + // rgb(255,0,0) rgba(255,0,0,0.5) + + handleAlpha( color[ 4 ] ); + + return this.setRGB( + Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255, + Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255, + Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255, + colorSpace + ); + + } + + if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) { + + // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5) + + handleAlpha( color[ 4 ] ); + + return this.setRGB( + Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100, + Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100, + Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100, + colorSpace + ); + + } + + break; + + case 'hsl': + case 'hsla': + + if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) { + + // hsl(120,50%,50%) hsla(120,50%,50%,0.5) + + handleAlpha( color[ 4 ] ); + + return this.setHSL( + parseFloat( color[ 1 ] ) / 360, + parseFloat( color[ 2 ] ) / 100, + parseFloat( color[ 3 ] ) / 100, + colorSpace + ); + + } + + break; + + default: + + warn( 'Color: Unknown color model ' + style ); + + } + + } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) { + + // hex color + + const hex = m[ 1 ]; + const size = hex.length; + + if ( size === 3 ) { + + // #ff0 + return this.setRGB( + parseInt( hex.charAt( 0 ), 16 ) / 15, + parseInt( hex.charAt( 1 ), 16 ) / 15, + parseInt( hex.charAt( 2 ), 16 ) / 15, + colorSpace + ); + + } else if ( size === 6 ) { + + // #ff0000 + return this.setHex( parseInt( hex, 16 ), colorSpace ); + + } else { + + warn( 'Color: Invalid hex color ' + style ); + + } + + } else if ( style && style.length > 0 ) { + + return this.setColorName( style, colorSpace ); + + } + + return this; + + } + + /** + * Sets this color from a color name. Faster than {@link Color#setStyle} if + * you don't need the other CSS-style formats. + * + * For convenience, the list of names is exposed in `Color.NAMES` as a hash. + * ```js + * Color.NAMES.aliceblue // returns 0xF0F8FF + * ``` + * + * @param {string} style - The color name. + * @param {string} [colorSpace=SRGBColorSpace] - The color space. + * @return {Color} A reference to this color. + */ + setColorName( style, colorSpace = SRGBColorSpace ) { + + // color keywords + const hex = _colorKeywords[ style.toLowerCase() ]; + + if ( hex !== undefined ) { + + // red + this.setHex( hex, colorSpace ); + + } else { + + // unknown color + warn( 'Color: Unknown color ' + style ); + + } + + return this; + + } + + /** + * Returns a new color with copied values from this instance. + * + * @return {Color} A clone of this instance. + */ + clone() { + + return new this.constructor( this.r, this.g, this.b ); + + } + + /** + * Copies the values of the given color to this instance. + * + * @param {Color} color - The color to copy. + * @return {Color} A reference to this color. + */ + copy( color ) { + + this.r = color.r; + this.g = color.g; + this.b = color.b; + + return this; + + } + + /** + * Copies the given color into this color, and then converts this color from + * `SRGBColorSpace` to `LinearSRGBColorSpace`. + * + * @param {Color} color - The color to copy/convert. + * @return {Color} A reference to this color. + */ + copySRGBToLinear( color ) { + + this.r = SRGBToLinear( color.r ); + this.g = SRGBToLinear( color.g ); + this.b = SRGBToLinear( color.b ); + + return this; + + } + + /** + * Copies the given color into this color, and then converts this color from + * `LinearSRGBColorSpace` to `SRGBColorSpace`. + * + * @param {Color} color - The color to copy/convert. + * @return {Color} A reference to this color. + */ + copyLinearToSRGB( color ) { + + this.r = LinearToSRGB( color.r ); + this.g = LinearToSRGB( color.g ); + this.b = LinearToSRGB( color.b ); + + return this; + + } + + /** + * Converts this color from `SRGBColorSpace` to `LinearSRGBColorSpace`. + * + * @return {Color} A reference to this color. + */ + convertSRGBToLinear() { + + this.copySRGBToLinear( this ); + + return this; + + } + + /** + * Converts this color from `LinearSRGBColorSpace` to `SRGBColorSpace`. + * + * @return {Color} A reference to this color. + */ + convertLinearToSRGB() { + + this.copyLinearToSRGB( this ); + + return this; + + } + + /** + * Returns the hexadecimal value of this color. + * + * @param {string} [colorSpace=SRGBColorSpace] - The color space. + * @return {number} The hexadecimal value. + */ + getHex( colorSpace = SRGBColorSpace ) { + + ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace ); + + return Math.round( clamp( _color.r * 255, 0, 255 ) ) * 65536 + Math.round( clamp( _color.g * 255, 0, 255 ) ) * 256 + Math.round( clamp( _color.b * 255, 0, 255 ) ); + + } + + /** + * Returns the hexadecimal value of this color as a string (for example, 'FFFFFF'). + * + * @param {string} [colorSpace=SRGBColorSpace] - The color space. + * @return {string} The hexadecimal value as a string. + */ + getHexString( colorSpace = SRGBColorSpace ) { + + return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( -6 ); + + } + + /** + * Converts the colors RGB values into the HSL format and stores them into the + * given target object. + * + * @param {{h:number,s:number,l:number}} target - The target object that is used to store the method's result. + * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space. + * @return {{h:number,s:number,l:number}} The HSL representation of this color. + */ + getHSL( target, colorSpace = ColorManagement.workingColorSpace ) { + + // h,s,l ranges are in 0.0 - 1.0 + + ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace ); + + const r = _color.r, g = _color.g, b = _color.b; + + const max = Math.max( r, g, b ); + const min = Math.min( r, g, b ); + + let hue, saturation; + const lightness = ( min + max ) / 2.0; + + if ( min === max ) { + + hue = 0; + saturation = 0; + + } else { + + const delta = max - min; + + saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min ); + + switch ( max ) { + + case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break; + case g: hue = ( b - r ) / delta + 2; break; + case b: hue = ( r - g ) / delta + 4; break; + + } + + hue /= 6; + + } + + target.h = hue; + target.s = saturation; + target.l = lightness; + + return target; + + } + + /** + * Returns the RGB values of this color and stores them into the given target object. + * + * @param {Color} target - The target color that is used to store the method's result. + * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space. + * @return {Color} The RGB representation of this color. + */ + getRGB( target, colorSpace = ColorManagement.workingColorSpace ) { + + ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace ); + + target.r = _color.r; + target.g = _color.g; + target.b = _color.b; + + return target; + + } + + /** + * Returns the value of this color as a CSS style string. Example: `rgb(255,0,0)`. + * + * @param {string} [colorSpace=SRGBColorSpace] - The color space. + * @return {string} The CSS representation of this color. + */ + getStyle( colorSpace = SRGBColorSpace ) { + + ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace ); + + const r = _color.r, g = _color.g, b = _color.b; + + if ( colorSpace !== SRGBColorSpace ) { + + // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/). + return `color(${ colorSpace } ${ r.toFixed( 3 ) } ${ g.toFixed( 3 ) } ${ b.toFixed( 3 ) })`; + + } + + return `rgb(${ Math.round( r * 255 ) },${ Math.round( g * 255 ) },${ Math.round( b * 255 ) })`; + + } + + /** + * Adds the given HSL values to this color's values. + * Internally, this converts the color's RGB values to HSL, adds HSL + * and then converts the color back to RGB. + * + * @param {number} h - Hue value between `0.0` and `1.0`. + * @param {number} s - Saturation value between `0.0` and `1.0`. + * @param {number} l - Lightness value between `0.0` and `1.0`. + * @return {Color} A reference to this color. + */ + offsetHSL( h, s, l ) { + + this.getHSL( _hslA ); + + return this.setHSL( _hslA.h + h, _hslA.s + s, _hslA.l + l ); + + } + + /** + * Adds the RGB values of the given color to the RGB values of this color. + * + * @param {Color} color - The color to add. + * @return {Color} A reference to this color. + */ + add( color ) { + + this.r += color.r; + this.g += color.g; + this.b += color.b; + + return this; + + } + + /** + * Adds the RGB values of the given colors and stores the result in this instance. + * + * @param {Color} color1 - The first color. + * @param {Color} color2 - The second color. + * @return {Color} A reference to this color. + */ + addColors( color1, color2 ) { + + this.r = color1.r + color2.r; + this.g = color1.g + color2.g; + this.b = color1.b + color2.b; + + return this; + + } + + /** + * Adds the given scalar value to the RGB values of this color. + * + * @param {number} s - The scalar to add. + * @return {Color} A reference to this color. + */ + addScalar( s ) { + + this.r += s; + this.g += s; + this.b += s; + + return this; + + } + + /** + * Subtracts the RGB values of the given color from the RGB values of this color. + * + * @param {Color} color - The color to subtract. + * @return {Color} A reference to this color. + */ + sub( color ) { + + this.r = Math.max( 0, this.r - color.r ); + this.g = Math.max( 0, this.g - color.g ); + this.b = Math.max( 0, this.b - color.b ); + + return this; + + } + + /** + * Multiplies the RGB values of the given color with the RGB values of this color. + * + * @param {Color} color - The color to multiply. + * @return {Color} A reference to this color. + */ + multiply( color ) { + + this.r *= color.r; + this.g *= color.g; + this.b *= color.b; + + return this; + + } + + /** + * Multiplies the given scalar value with the RGB values of this color. + * + * @param {number} s - The scalar to multiply. + * @return {Color} A reference to this color. + */ + multiplyScalar( s ) { + + this.r *= s; + this.g *= s; + this.b *= s; + + return this; + + } + + /** + * Linearly interpolates this color's RGB values toward the RGB values of the + * given color. The alpha argument can be thought of as the ratio between + * the two colors, where `0.0` is this color and `1.0` is the first argument. + * + * @param {Color} color - The color to converge on. + * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`. + * @return {Color} A reference to this color. + */ + lerp( color, alpha ) { + + this.r += ( color.r - this.r ) * alpha; + this.g += ( color.g - this.g ) * alpha; + this.b += ( color.b - this.b ) * alpha; + + return this; + + } + + /** + * Linearly interpolates between the given colors and stores the result in this instance. + * The alpha argument can be thought of as the ratio between the two colors, where `0.0` + * is the first and `1.0` is the second color. + * + * @param {Color} color1 - The first color. + * @param {Color} color2 - The second color. + * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`. + * @return {Color} A reference to this color. + */ + lerpColors( color1, color2, alpha ) { + + this.r = color1.r + ( color2.r - color1.r ) * alpha; + this.g = color1.g + ( color2.g - color1.g ) * alpha; + this.b = color1.b + ( color2.b - color1.b ) * alpha; + + return this; + + } + + /** + * Linearly interpolates this color's HSL values toward the HSL values of the + * given color. It differs from {@link Color#lerp} by not interpolating straight + * from one color to the other, but instead going through all the hues in between + * those two colors. The alpha argument can be thought of as the ratio between + * the two colors, where 0.0 is this color and 1.0 is the first argument. + * + * @param {Color} color - The color to converge on. + * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`. + * @return {Color} A reference to this color. + */ + lerpHSL( color, alpha ) { + + this.getHSL( _hslA ); + color.getHSL( _hslB ); + + const h = lerp( _hslA.h, _hslB.h, alpha ); + const s = lerp( _hslA.s, _hslB.s, alpha ); + const l = lerp( _hslA.l, _hslB.l, alpha ); + + this.setHSL( h, s, l ); + + return this; + + } + + /** + * Sets the color's RGB components from the given 3D vector. + * + * @param {Vector3} v - The vector to set. + * @return {Color} A reference to this color. + */ + setFromVector3( v ) { + + this.r = v.x; + this.g = v.y; + this.b = v.z; + + return this; + + } + + /** + * Transforms this color with the given 3x3 matrix. + * + * @param {Matrix3} m - The matrix. + * @return {Color} A reference to this color. + */ + applyMatrix3( m ) { + + const r = this.r, g = this.g, b = this.b; + const e = m.elements; + + this.r = e[ 0 ] * r + e[ 3 ] * g + e[ 6 ] * b; + this.g = e[ 1 ] * r + e[ 4 ] * g + e[ 7 ] * b; + this.b = e[ 2 ] * r + e[ 5 ] * g + e[ 8 ] * b; + + return this; + + } + + /** + * Returns `true` if this color is equal with the given one. + * + * @param {Color} c - The color to test for equality. + * @return {boolean} Whether this bounding color is equal with the given one. + */ + equals( c ) { + + return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b ); + + } + + /** + * Sets this color's RGB components from the given array. + * + * @param {Array} array - An array holding the RGB values. + * @param {number} [offset=0] - The offset into the array. + * @return {Color} A reference to this color. + */ + fromArray( array, offset = 0 ) { + + this.r = array[ offset ]; + this.g = array[ offset + 1 ]; + this.b = array[ offset + 2 ]; + + return this; + + } + + /** + * Writes the RGB components of this color to the given array. If no array is provided, + * the method returns a new instance. + * + * @param {Array} [array=[]] - The target array holding the color components. + * @param {number} [offset=0] - Index of the first element in the array. + * @return {Array} The color components. + */ + toArray( array = [], offset = 0 ) { + + array[ offset ] = this.r; + array[ offset + 1 ] = this.g; + array[ offset + 2 ] = this.b; + + return array; + + } + + /** + * Sets the components of this color from the given buffer attribute. + * + * @param {BufferAttribute} attribute - The buffer attribute holding color data. + * @param {number} index - The index into the attribute. + * @return {Color} A reference to this color. + */ + fromBufferAttribute( attribute, index ) { + + this.r = attribute.getX( index ); + this.g = attribute.getY( index ); + this.b = attribute.getZ( index ); + + return this; + + } + + /** + * This methods defines the serialization result of this class. Returns the color + * as a hexadecimal value. + * + * @return {number} The hexadecimal value. + */ + toJSON() { + + return this.getHex(); + + } + + *[ Symbol.iterator ]() { + + yield this.r; + yield this.g; + yield this.b; + + } + +} + +const _color = /*@__PURE__*/ new Color(); + +/** + * A dictionary with X11 color names. + * + * Note that multiple words such as Dark Orange become the string 'darkorange'. + * + * @static + * @type {Object} + */ +Color.NAMES = _colorKeywords; + +/** + * This class can be used to define an exponential squared fog, + * which gives a clear view near the camera and a faster than exponentially + * densening fog farther from the camera. + * + * ```js + * const scene = new THREE.Scene(); + * scene.fog = new THREE.FogExp2( 0xcccccc, 0.002 ); + * ``` + */ +class FogExp2 { + + /** + * Constructs a new fog. + * + * @param {number|Color} color - The fog's color. + * @param {number} [density=0.00025] - Defines how fast the fog will grow dense. + */ + constructor( color, density = 0.00025 ) { + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isFogExp2 = true; + + /** + * The name of the fog. + * + * @type {string} + */ + this.name = ''; + + /** + * The fog's color. + * + * @type {Color} + */ + this.color = new Color( color ); + + /** + * Defines how fast the fog will grow dense. + * + * @type {number} + * @default 0.00025 + */ + this.density = density; + + } + + /** + * Returns a new fog with copied values from this instance. + * + * @return {FogExp2} A clone of this instance. + */ + clone() { + + return new FogExp2( this.color, this.density ); + + } + + /** + * Serializes the fog into JSON. + * + * @param {?(Object|string)} meta - An optional value holding meta information about the serialization. + * @return {Object} A JSON object representing the serialized fog + */ + toJSON( /* meta */ ) { + + return { + type: 'FogExp2', + name: this.name, + color: this.color.getHex(), + density: this.density + }; + + } + +} + +/** + * This class can be used to define a linear fog that grows linearly denser + * with the distance. + * + * ```js + * const scene = new THREE.Scene(); + * scene.fog = new THREE.Fog( 0xcccccc, 10, 15 ); + * ``` + */ +class Fog { + + /** + * Constructs a new fog. + * + * @param {number|Color} color - The fog's color. + * @param {number} [near=1] - The minimum distance to start applying fog. + * @param {number} [far=1000] - The maximum distance at which fog stops being calculated and applied. + */ + constructor( color, near = 1, far = 1000 ) { + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isFog = true; + + /** + * The name of the fog. + * + * @type {string} + */ + this.name = ''; + + /** + * The fog's color. + * + * @type {Color} + */ + this.color = new Color( color ); + + /** + * The minimum distance to start applying fog. Objects that are less than + * `near` units from the active camera won't be affected by fog. + * + * @type {number} + * @default 1 + */ + this.near = near; + + /** + * The maximum distance at which fog stops being calculated and applied. + * Objects that are more than `far` units away from the active camera won't + * be affected by fog. + * + * @type {number} + * @default 1000 + */ + this.far = far; + + } + + /** + * Returns a new fog with copied values from this instance. + * + * @return {Fog} A clone of this instance. + */ + clone() { + + return new Fog( this.color, this.near, this.far ); + + } + + /** + * Serializes the fog into JSON. + * + * @param {?(Object|string)} meta - An optional value holding meta information about the serialization. + * @return {Object} A JSON object representing the serialized fog + */ + toJSON( /* meta */ ) { + + return { + type: 'Fog', + name: this.name, + color: this.color.getHex(), + near: this.near, + far: this.far + }; + + } + +} + +/** + * Scenes allow you to set up what is to be rendered and where by three.js. + * This is where you place 3D objects like meshes, lines or lights. + * + * @augments Object3D + */ +class Scene extends Object3D { + + /** + * Constructs a new scene. + */ + constructor() { + + super(); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isScene = true; + + this.type = 'Scene'; + + /** + * Defines the background of the scene. Valid inputs are: + * + * - A color for defining a uniform colored background. + * - A texture for defining a (flat) textured background. + * - Cube textures or equirectangular textures for defining a skybox. + * + * @type {?(Color|Texture)} + * @default null + */ + this.background = null; + + /** + * Sets the environment map for all physical materials in the scene. However, + * it's not possible to overwrite an existing texture assigned to the `envMap` + * material property. + * + * @type {?Texture} + * @default null + */ + this.environment = null; + + /** + * A fog instance defining the type of fog that affects everything + * rendered in the scene. + * + * @type {?(Fog|FogExp2)} + * @default null + */ + this.fog = null; + + /** + * Sets the blurriness of the background. Only influences environment maps + * assigned to {@link Scene#background}. Valid input is a float between `0` + * and `1`. + * + * @type {number} + * @default 0 + */ + this.backgroundBlurriness = 0; + + /** + * Attenuates the color of the background. Only applies to background textures. + * + * @type {number} + * @default 1 + */ + this.backgroundIntensity = 1; + + /** + * The rotation of the background in radians. Only influences environment maps + * assigned to {@link Scene#background}. + * + * @type {Euler} + * @default (0,0,0) + */ + this.backgroundRotation = new Euler(); + + /** + * Attenuates the color of the environment. Only influences environment maps + * assigned to {@link Scene#environment}. + * + * @type {number} + * @default 1 + */ + this.environmentIntensity = 1; + + /** + * The rotation of the environment map in radians. Only influences physical materials + * in the scene when {@link Scene#environment} is used. + * + * @type {Euler} + * @default (0,0,0) + */ + this.environmentRotation = new Euler(); + + /** + * Forces everything in the scene to be rendered with the defined material. It is possible + * to exclude materials from override by setting {@link Material#allowOverride} to `false`. + * + * @type {?Material} + * @default null + */ + this.overrideMaterial = null; + + if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) { + + __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) ); + + } + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + if ( source.background !== null ) this.background = source.background.clone(); + if ( source.environment !== null ) this.environment = source.environment.clone(); + if ( source.fog !== null ) this.fog = source.fog.clone(); + + this.backgroundBlurriness = source.backgroundBlurriness; + this.backgroundIntensity = source.backgroundIntensity; + this.backgroundRotation.copy( source.backgroundRotation ); + + this.environmentIntensity = source.environmentIntensity; + this.environmentRotation.copy( source.environmentRotation ); + + if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone(); + + this.matrixAutoUpdate = source.matrixAutoUpdate; + + return this; + + } + + toJSON( meta ) { + + const data = super.toJSON( meta ); + + if ( this.fog !== null ) data.object.fog = this.fog.toJSON(); + + data.object.backgroundBlurriness = this.backgroundBlurriness; + data.object.backgroundIntensity = this.backgroundIntensity; + data.object.backgroundRotation = this.backgroundRotation.toArray(); + + data.object.environmentIntensity = this.environmentIntensity; + data.object.environmentRotation = this.environmentRotation.toArray(); + + return data; + + } + +} + +const _v0$2 = /*@__PURE__*/ new Vector3(); +const _v1$5 = /*@__PURE__*/ new Vector3(); +const _v2$4 = /*@__PURE__*/ new Vector3(); +const _v3$2 = /*@__PURE__*/ new Vector3(); + +const _vab = /*@__PURE__*/ new Vector3(); +const _vac = /*@__PURE__*/ new Vector3(); +const _vbc = /*@__PURE__*/ new Vector3(); +const _vap = /*@__PURE__*/ new Vector3(); +const _vbp = /*@__PURE__*/ new Vector3(); +const _vcp = /*@__PURE__*/ new Vector3(); + +const _v40 = /*@__PURE__*/ new Vector4(); +const _v41 = /*@__PURE__*/ new Vector4(); +const _v42 = /*@__PURE__*/ new Vector4(); + +/** + * A geometric triangle as defined by three vectors representing its three corners. + */ +class Triangle { + + /** + * Constructs a new triangle. + * + * @param {Vector3} [a=(0,0,0)] - The first corner of the triangle. + * @param {Vector3} [b=(0,0,0)] - The second corner of the triangle. + * @param {Vector3} [c=(0,0,0)] - The third corner of the triangle. + */ + constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) { + + /** + * The first corner of the triangle. + * + * @type {Vector3} + */ + this.a = a; + + /** + * The second corner of the triangle. + * + * @type {Vector3} + */ + this.b = b; + + /** + * The third corner of the triangle. + * + * @type {Vector3} + */ + this.c = c; + + } + + /** + * Computes the normal vector of a triangle. + * + * @param {Vector3} a - The first corner of the triangle. + * @param {Vector3} b - The second corner of the triangle. + * @param {Vector3} c - The third corner of the triangle. + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {Vector3} The triangle's normal. + */ + static getNormal( a, b, c, target ) { + + target.subVectors( c, b ); + _v0$2.subVectors( a, b ); + target.cross( _v0$2 ); + + const targetLengthSq = target.lengthSq(); + if ( targetLengthSq > 0 ) { + + return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) ); + + } + + return target.set( 0, 0, 0 ); + + } + + /** + * Computes a barycentric coordinates from the given vector. + * Returns `null` if the triangle is degenerate. + * + * @param {Vector3} point - A point in 3D space. + * @param {Vector3} a - The first corner of the triangle. + * @param {Vector3} b - The second corner of the triangle. + * @param {Vector3} c - The third corner of the triangle. + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {?Vector3} The barycentric coordinates for the given point + */ + static getBarycoord( point, a, b, c, target ) { + + _v0$2.subVectors( c, a ); + _v1$5.subVectors( b, a ); + _v2$4.subVectors( point, a ); + + const dot00 = _v0$2.dot( _v0$2 ); + const dot01 = _v0$2.dot( _v1$5 ); + const dot02 = _v0$2.dot( _v2$4 ); + const dot11 = _v1$5.dot( _v1$5 ); + const dot12 = _v1$5.dot( _v2$4 ); + + const denom = ( dot00 * dot11 - dot01 * dot01 ); + + // collinear or singular triangle + if ( denom === 0 ) { + + target.set( 0, 0, 0 ); + return null; + + } + + const invDenom = 1 / denom; + const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom; + const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom; + + // barycentric coordinates must always sum to 1 + return target.set( 1 - u - v, v, u ); + + } + + /** + * Returns `true` if the given point, when projected onto the plane of the + * triangle, lies within the triangle. + * + * @param {Vector3} point - The point in 3D space to test. + * @param {Vector3} a - The first corner of the triangle. + * @param {Vector3} b - The second corner of the triangle. + * @param {Vector3} c - The third corner of the triangle. + * @return {boolean} Whether the given point, when projected onto the plane of the + * triangle, lies within the triangle or not. + */ + static containsPoint( point, a, b, c ) { + + // if the triangle is degenerate then we can't contain a point + if ( this.getBarycoord( point, a, b, c, _v3$2 ) === null ) { + + return false; + + } + + return ( _v3$2.x >= 0 ) && ( _v3$2.y >= 0 ) && ( ( _v3$2.x + _v3$2.y ) <= 1 ); + + } + + /** + * Computes the value barycentrically interpolated for the given point on the + * triangle. Returns `null` if the triangle is degenerate. + * + * @param {Vector3} point - Position of interpolated point. + * @param {Vector3} p1 - The first corner of the triangle. + * @param {Vector3} p2 - The second corner of the triangle. + * @param {Vector3} p3 - The third corner of the triangle. + * @param {Vector3} v1 - Value to interpolate of first vertex. + * @param {Vector3} v2 - Value to interpolate of second vertex. + * @param {Vector3} v3 - Value to interpolate of third vertex. + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {?Vector3} The interpolated value. + */ + static getInterpolation( point, p1, p2, p3, v1, v2, v3, target ) { + + if ( this.getBarycoord( point, p1, p2, p3, _v3$2 ) === null ) { + + target.x = 0; + target.y = 0; + if ( 'z' in target ) target.z = 0; + if ( 'w' in target ) target.w = 0; + return null; + + } + + target.setScalar( 0 ); + target.addScaledVector( v1, _v3$2.x ); + target.addScaledVector( v2, _v3$2.y ); + target.addScaledVector( v3, _v3$2.z ); + + return target; + + } + + /** + * Computes the value barycentrically interpolated for the given attribute and indices. + * + * @param {BufferAttribute} attr - The attribute to interpolate. + * @param {number} i1 - Index of first vertex. + * @param {number} i2 - Index of second vertex. + * @param {number} i3 - Index of third vertex. + * @param {Vector3} barycoord - The barycoordinate value to use to interpolate. + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {Vector3} The interpolated attribute value. + */ + static getInterpolatedAttribute( attr, i1, i2, i3, barycoord, target ) { + + _v40.setScalar( 0 ); + _v41.setScalar( 0 ); + _v42.setScalar( 0 ); + + _v40.fromBufferAttribute( attr, i1 ); + _v41.fromBufferAttribute( attr, i2 ); + _v42.fromBufferAttribute( attr, i3 ); + + target.setScalar( 0 ); + target.addScaledVector( _v40, barycoord.x ); + target.addScaledVector( _v41, barycoord.y ); + target.addScaledVector( _v42, barycoord.z ); + + return target; + + } + + /** + * Returns `true` if the triangle is oriented towards the given direction. + * + * @param {Vector3} a - The first corner of the triangle. + * @param {Vector3} b - The second corner of the triangle. + * @param {Vector3} c - The third corner of the triangle. + * @param {Vector3} direction - The (normalized) direction vector. + * @return {boolean} Whether the triangle is oriented towards the given direction or not. + */ + static isFrontFacing( a, b, c, direction ) { + + _v0$2.subVectors( c, b ); + _v1$5.subVectors( a, b ); + + // strictly front facing + return _v0$2.cross( _v1$5 ).dot( direction ) < 0; + + } + + /** + * Sets the triangle's vertices by copying the given values. + * + * @param {Vector3} a - The first corner of the triangle. + * @param {Vector3} b - The second corner of the triangle. + * @param {Vector3} c - The third corner of the triangle. + * @return {Triangle} A reference to this triangle. + */ + set( a, b, c ) { + + this.a.copy( a ); + this.b.copy( b ); + this.c.copy( c ); + + return this; + + } + + /** + * Sets the triangle's vertices by copying the given array values. + * + * @param {Array} points - An array with 3D points. + * @param {number} i0 - The array index representing the first corner of the triangle. + * @param {number} i1 - The array index representing the second corner of the triangle. + * @param {number} i2 - The array index representing the third corner of the triangle. + * @return {Triangle} A reference to this triangle. + */ + setFromPointsAndIndices( points, i0, i1, i2 ) { + + this.a.copy( points[ i0 ] ); + this.b.copy( points[ i1 ] ); + this.c.copy( points[ i2 ] ); + + return this; + + } + + /** + * Sets the triangle's vertices by copying the given attribute values. + * + * @param {BufferAttribute} attribute - A buffer attribute with 3D points data. + * @param {number} i0 - The attribute index representing the first corner of the triangle. + * @param {number} i1 - The attribute index representing the second corner of the triangle. + * @param {number} i2 - The attribute index representing the third corner of the triangle. + * @return {Triangle} A reference to this triangle. + */ + setFromAttributeAndIndices( attribute, i0, i1, i2 ) { + + this.a.fromBufferAttribute( attribute, i0 ); + this.b.fromBufferAttribute( attribute, i1 ); + this.c.fromBufferAttribute( attribute, i2 ); + + return this; + + } + + /** + * Returns a new triangle with copied values from this instance. + * + * @return {Triangle} A clone of this instance. + */ + clone() { + + return new this.constructor().copy( this ); + + } + + /** + * Copies the values of the given triangle to this instance. + * + * @param {Triangle} triangle - The triangle to copy. + * @return {Triangle} A reference to this triangle. + */ + copy( triangle ) { + + this.a.copy( triangle.a ); + this.b.copy( triangle.b ); + this.c.copy( triangle.c ); + + return this; + + } + + /** + * Computes the area of the triangle. + * + * @return {number} The triangle's area. + */ + getArea() { + + _v0$2.subVectors( this.c, this.b ); + _v1$5.subVectors( this.a, this.b ); + + return _v0$2.cross( _v1$5 ).length() * 0.5; + + } + + /** + * Computes the midpoint of the triangle. + * + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {Vector3} The triangle's midpoint. + */ + getMidpoint( target ) { + + return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 ); + + } + + /** + * Computes the normal of the triangle. + * + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {Vector3} The triangle's normal. + */ + getNormal( target ) { + + return Triangle.getNormal( this.a, this.b, this.c, target ); + + } + + /** + * Computes a plane the triangle lies within. + * + * @param {Plane} target - The target vector that is used to store the method's result. + * @return {Plane} The plane the triangle lies within. + */ + getPlane( target ) { + + return target.setFromCoplanarPoints( this.a, this.b, this.c ); + + } + + /** + * Computes a barycentric coordinates from the given vector. + * Returns `null` if the triangle is degenerate. + * + * @param {Vector3} point - A point in 3D space. + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {?Vector3} The barycentric coordinates for the given point + */ + getBarycoord( point, target ) { + + return Triangle.getBarycoord( point, this.a, this.b, this.c, target ); + + } + + /** + * Computes the value barycentrically interpolated for the given point on the + * triangle. Returns `null` if the triangle is degenerate. + * + * @param {Vector3} point - Position of interpolated point. + * @param {Vector3} v1 - Value to interpolate of first vertex. + * @param {Vector3} v2 - Value to interpolate of second vertex. + * @param {Vector3} v3 - Value to interpolate of third vertex. + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {?Vector3} The interpolated value. + */ + getInterpolation( point, v1, v2, v3, target ) { + + return Triangle.getInterpolation( point, this.a, this.b, this.c, v1, v2, v3, target ); + + } + + /** + * Returns `true` if the given point, when projected onto the plane of the + * triangle, lies within the triangle. + * + * @param {Vector3} point - The point in 3D space to test. + * @return {boolean} Whether the given point, when projected onto the plane of the + * triangle, lies within the triangle or not. + */ + containsPoint( point ) { + + return Triangle.containsPoint( point, this.a, this.b, this.c ); + + } + + /** + * Returns `true` if the triangle is oriented towards the given direction. + * + * @param {Vector3} direction - The (normalized) direction vector. + * @return {boolean} Whether the triangle is oriented towards the given direction or not. + */ + isFrontFacing( direction ) { + + return Triangle.isFrontFacing( this.a, this.b, this.c, direction ); + + } + + /** + * Returns `true` if this triangle intersects with the given box. + * + * @param {Box3} box - The box to intersect. + * @return {boolean} Whether this triangle intersects with the given box or not. + */ + intersectsBox( box ) { + + return box.intersectsTriangle( this ); + + } + + /** + * Returns the closest point on the triangle to the given point. + * + * @param {Vector3} p - The point to compute the closest point for. + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {Vector3} The closest point on the triangle. + */ + closestPointToPoint( p, target ) { + + const a = this.a, b = this.b, c = this.c; + let v, w; + + // algorithm thanks to Real-Time Collision Detection by Christer Ericson, + // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc., + // under the accompanying license; see chapter 5.1.5 for detailed explanation. + // basically, we're distinguishing which of the voronoi regions of the triangle + // the point lies in with the minimum amount of redundant computation. + + _vab.subVectors( b, a ); + _vac.subVectors( c, a ); + _vap.subVectors( p, a ); + const d1 = _vab.dot( _vap ); + const d2 = _vac.dot( _vap ); + if ( d1 <= 0 && d2 <= 0 ) { + + // vertex region of A; barycentric coords (1, 0, 0) + return target.copy( a ); + + } + + _vbp.subVectors( p, b ); + const d3 = _vab.dot( _vbp ); + const d4 = _vac.dot( _vbp ); + if ( d3 >= 0 && d4 <= d3 ) { + + // vertex region of B; barycentric coords (0, 1, 0) + return target.copy( b ); + + } + + const vc = d1 * d4 - d3 * d2; + if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) { + + v = d1 / ( d1 - d3 ); + // edge region of AB; barycentric coords (1-v, v, 0) + return target.copy( a ).addScaledVector( _vab, v ); + + } + + _vcp.subVectors( p, c ); + const d5 = _vab.dot( _vcp ); + const d6 = _vac.dot( _vcp ); + if ( d6 >= 0 && d5 <= d6 ) { + + // vertex region of C; barycentric coords (0, 0, 1) + return target.copy( c ); + + } + + const vb = d5 * d2 - d1 * d6; + if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) { + + w = d2 / ( d2 - d6 ); + // edge region of AC; barycentric coords (1-w, 0, w) + return target.copy( a ).addScaledVector( _vac, w ); + + } + + const va = d3 * d6 - d5 * d4; + if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) { + + _vbc.subVectors( c, b ); + w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) ); + // edge region of BC; barycentric coords (0, 1-w, w) + return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC + + } + + // face region + const denom = 1 / ( va + vb + vc ); + // u = va * denom + v = vb * denom; + w = vc * denom; + + return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w ); + + } + + /** + * Returns `true` if this triangle is equal with the given one. + * + * @param {Triangle} triangle - The triangle to test for equality. + * @return {boolean} Whether this triangle is equal with the given one. + */ + equals( triangle ) { + + return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c ); + + } + +} + +/** + * Represents an axis-aligned bounding box (AABB) in 3D space. + */ +class Box3 { + + /** + * Constructs a new bounding box. + * + * @param {Vector3} [min=(Infinity,Infinity,Infinity)] - A vector representing the lower boundary of the box. + * @param {Vector3} [max=(-Infinity,-Infinity,-Infinity)] - A vector representing the upper boundary of the box. + */ + constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) { + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isBox3 = true; + + /** + * The lower boundary of the box. + * + * @type {Vector3} + */ + this.min = min; + + /** + * The upper boundary of the box. + * + * @type {Vector3} + */ + this.max = max; + + } + + /** + * Sets the lower and upper boundaries of this box. + * Please note that this method only copies the values from the given objects. + * + * @param {Vector3} min - The lower boundary of the box. + * @param {Vector3} max - The upper boundary of the box. + * @return {Box3} A reference to this bounding box. + */ + set( min, max ) { + + this.min.copy( min ); + this.max.copy( max ); + + return this; + + } + + /** + * Sets the upper and lower bounds of this box so it encloses the position data + * in the given array. + * + * @param {Array} array - An array holding 3D position data. + * @return {Box3} A reference to this bounding box. + */ + setFromArray( array ) { + + this.makeEmpty(); + + for ( let i = 0, il = array.length; i < il; i += 3 ) { + + this.expandByPoint( _vector$b.fromArray( array, i ) ); + + } + + return this; + + } + + /** + * Sets the upper and lower bounds of this box so it encloses the position data + * in the given buffer attribute. + * + * @param {BufferAttribute} attribute - A buffer attribute holding 3D position data. + * @return {Box3} A reference to this bounding box. + */ + setFromBufferAttribute( attribute ) { + + this.makeEmpty(); + + for ( let i = 0, il = attribute.count; i < il; i ++ ) { + + this.expandByPoint( _vector$b.fromBufferAttribute( attribute, i ) ); + + } + + return this; + + } + + /** + * Sets the upper and lower bounds of this box so it encloses the position data + * in the given array. + * + * @param {Array} points - An array holding 3D position data as instances of {@link Vector3}. + * @return {Box3} A reference to this bounding box. + */ + setFromPoints( points ) { + + this.makeEmpty(); + + for ( let i = 0, il = points.length; i < il; i ++ ) { + + this.expandByPoint( points[ i ] ); + + } + + return this; + + } + + /** + * Centers this box on the given center vector and sets this box's width, height and + * depth to the given size values. + * + * @param {Vector3} center - The center of the box. + * @param {Vector3} size - The x, y and z dimensions of the box. + * @return {Box3} A reference to this bounding box. + */ + setFromCenterAndSize( center, size ) { + + const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 ); + + this.min.copy( center ).sub( halfSize ); + this.max.copy( center ).add( halfSize ); + + return this; + + } + + /** + * Computes the world-axis-aligned bounding box for the given 3D object + * (including its children), accounting for the object's, and children's, + * world transforms. The function may result in a larger box than strictly necessary. + * + * Note: To compute the correct bounding box, make sure the given 3D object + * has an up-to-date world matrix that reflects the current transformation of its + * ancestor nodes. Call `object.updateWorldMatrix( true, false )` beforehand if + * you're unsure. + * + * @param {Object3D} object - The 3D object to compute the bounding box for. + * @param {boolean} [precise=false] - If set to `true`, the method computes the smallest + * world-axis-aligned bounding box at the expense of more computation. + * @return {Box3} A reference to this bounding box. + */ + setFromObject( object, precise = false ) { + + this.makeEmpty(); + + return this.expandByObject( object, precise ); + + } + + /** + * Returns a new box with copied values from this instance. + * + * @return {Box3} A clone of this instance. + */ + clone() { + + return new this.constructor().copy( this ); + + } + + /** + * Copies the values of the given box to this instance. + * + * @param {Box3} box - The box to copy. + * @return {Box3} A reference to this bounding box. + */ + copy( box ) { + + this.min.copy( box.min ); + this.max.copy( box.max ); + + return this; + + } + + /** + * Makes this box empty which means in encloses a zero space in 3D. + * + * @return {Box3} A reference to this bounding box. + */ + makeEmpty() { + + this.min.x = this.min.y = this.min.z = + Infinity; + this.max.x = this.max.y = this.max.z = - Infinity; + + return this; + + } + + /** + * Returns true if this box includes zero points within its bounds. + * Note that a box with equal lower and upper bounds still includes one + * point, the one both bounds share. + * + * @return {boolean} Whether this box is empty or not. + */ + isEmpty() { + + // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes + + return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z ); + + } + + /** + * Returns the center point of this box. + * + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {Vector3} The center point. + */ + getCenter( target ) { + + return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 ); + + } + + /** + * Returns the dimensions of this box. + * + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {Vector3} The size. + */ + getSize( target ) { + + return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min ); + + } + + /** + * Expands the boundaries of this box to include the given point. + * + * @param {Vector3} point - The point that should be included by the bounding box. + * @return {Box3} A reference to this bounding box. + */ + expandByPoint( point ) { + + this.min.min( point ); + this.max.max( point ); + + return this; + + } + + /** + * Expands this box equilaterally by the given vector. The width of this + * box will be expanded by the x component of the vector in both + * directions. The height of this box will be expanded by the y component of + * the vector in both directions. The depth of this box will be + * expanded by the z component of the vector in both directions. + * + * @param {Vector3} vector - The vector that should expand the bounding box. + * @return {Box3} A reference to this bounding box. + */ + expandByVector( vector ) { + + this.min.sub( vector ); + this.max.add( vector ); + + return this; + + } + + /** + * Expands each dimension of the box by the given scalar. If negative, the + * dimensions of the box will be contracted. + * + * @param {number} scalar - The scalar value that should expand the bounding box. + * @return {Box3} A reference to this bounding box. + */ + expandByScalar( scalar ) { + + this.min.addScalar( - scalar ); + this.max.addScalar( scalar ); + + return this; + + } + + /** + * Expands the boundaries of this box to include the given 3D object and + * its children, accounting for the object's, and children's, world + * transforms. The function may result in a larger box than strictly + * necessary (unless the precise parameter is set to true). + * + * @param {Object3D} object - The 3D object that should expand the bounding box. + * @param {boolean} precise - If set to `true`, the method expands the bounding box + * as little as necessary at the expense of more computation. + * @return {Box3} A reference to this bounding box. + */ + expandByObject( object, precise = false ) { + + // Computes the world-axis-aligned bounding box of an object (including its children), + // accounting for both the object's, and children's, world transforms + + object.updateWorldMatrix( false, false ); + + const geometry = object.geometry; + + if ( geometry !== undefined ) { + + const positionAttribute = geometry.getAttribute( 'position' ); + + // precise AABB computation based on vertex data requires at least a position attribute. + // instancing isn't supported so far and uses the normal (conservative) code path. + + if ( precise === true && positionAttribute !== undefined && object.isInstancedMesh !== true ) { + + for ( let i = 0, l = positionAttribute.count; i < l; i ++ ) { + + if ( object.isMesh === true ) { + + object.getVertexPosition( i, _vector$b ); + + } else { + + _vector$b.fromBufferAttribute( positionAttribute, i ); + + } + + _vector$b.applyMatrix4( object.matrixWorld ); + this.expandByPoint( _vector$b ); + + } + + } else { + + if ( object.boundingBox !== undefined ) { + + // object-level bounding box + + if ( object.boundingBox === null ) { + + object.computeBoundingBox(); + + } + + _box$4.copy( object.boundingBox ); + + + } else { + + // geometry-level bounding box + + if ( geometry.boundingBox === null ) { + + geometry.computeBoundingBox(); + + } + + _box$4.copy( geometry.boundingBox ); + + } + + _box$4.applyMatrix4( object.matrixWorld ); + + this.union( _box$4 ); + + } + + } + + const children = object.children; + + for ( let i = 0, l = children.length; i < l; i ++ ) { + + this.expandByObject( children[ i ], precise ); + + } + + return this; + + } + + /** + * Returns `true` if the given point lies within or on the boundaries of this box. + * + * @param {Vector3} point - The point to test. + * @return {boolean} Whether the bounding box contains the given point or not. + */ + containsPoint( point ) { + + return point.x >= this.min.x && point.x <= this.max.x && + point.y >= this.min.y && point.y <= this.max.y && + point.z >= this.min.z && point.z <= this.max.z; + + } + + /** + * Returns `true` if this bounding box includes the entirety of the given bounding box. + * If this box and the given one are identical, this function also returns `true`. + * + * @param {Box3} box - The bounding box to test. + * @return {boolean} Whether the bounding box contains the given bounding box or not. + */ + containsBox( box ) { + + return this.min.x <= box.min.x && box.max.x <= this.max.x && + this.min.y <= box.min.y && box.max.y <= this.max.y && + this.min.z <= box.min.z && box.max.z <= this.max.z; + + } + + /** + * Returns a point as a proportion of this box's width, height and depth. + * + * @param {Vector3} point - A point in 3D space. + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {Vector3} A point as a proportion of this box's width, height and depth. + */ + getParameter( point, target ) { + + // This can potentially have a divide by zero if the box + // has a size dimension of 0. + + return target.set( + ( point.x - this.min.x ) / ( this.max.x - this.min.x ), + ( point.y - this.min.y ) / ( this.max.y - this.min.y ), + ( point.z - this.min.z ) / ( this.max.z - this.min.z ) + ); + + } + + /** + * Returns `true` if the given bounding box intersects with this bounding box. + * + * @param {Box3} box - The bounding box to test. + * @return {boolean} Whether the given bounding box intersects with this bounding box. + */ + intersectsBox( box ) { + + // using 6 splitting planes to rule out intersections. + return box.max.x >= this.min.x && box.min.x <= this.max.x && + box.max.y >= this.min.y && box.min.y <= this.max.y && + box.max.z >= this.min.z && box.min.z <= this.max.z; + + } + + /** + * Returns `true` if the given bounding sphere intersects with this bounding box. + * + * @param {Sphere} sphere - The bounding sphere to test. + * @return {boolean} Whether the given bounding sphere intersects with this bounding box. + */ + intersectsSphere( sphere ) { + + // Find the point on the AABB closest to the sphere center. + this.clampPoint( sphere.center, _vector$b ); + + // If that point is inside the sphere, the AABB and sphere intersect. + return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius ); + + } + + /** + * Returns `true` if the given plane intersects with this bounding box. + * + * @param {Plane} plane - The plane to test. + * @return {boolean} Whether the given plane intersects with this bounding box. + */ + intersectsPlane( plane ) { + + // We compute the minimum and maximum dot product values. If those values + // are on the same side (back or front) of the plane, then there is no intersection. + + let min, max; + + if ( plane.normal.x > 0 ) { + + min = plane.normal.x * this.min.x; + max = plane.normal.x * this.max.x; + + } else { + + min = plane.normal.x * this.max.x; + max = plane.normal.x * this.min.x; + + } + + if ( plane.normal.y > 0 ) { + + min += plane.normal.y * this.min.y; + max += plane.normal.y * this.max.y; + + } else { + + min += plane.normal.y * this.max.y; + max += plane.normal.y * this.min.y; + + } + + if ( plane.normal.z > 0 ) { + + min += plane.normal.z * this.min.z; + max += plane.normal.z * this.max.z; + + } else { + + min += plane.normal.z * this.max.z; + max += plane.normal.z * this.min.z; + + } + + return ( min <= - plane.constant && max >= - plane.constant ); + + } + + /** + * Returns `true` if the given triangle intersects with this bounding box. + * + * @param {Triangle} triangle - The triangle to test. + * @return {boolean} Whether the given triangle intersects with this bounding box. + */ + intersectsTriangle( triangle ) { + + if ( this.isEmpty() ) { + + return false; + + } + + // compute box center and extents + this.getCenter( _center ); + _extents.subVectors( this.max, _center ); + + // translate triangle to aabb origin + _v0$1.subVectors( triangle.a, _center ); + _v1$4.subVectors( triangle.b, _center ); + _v2$3.subVectors( triangle.c, _center ); + + // compute edge vectors for triangle + _f0.subVectors( _v1$4, _v0$1 ); + _f1.subVectors( _v2$3, _v1$4 ); + _f2.subVectors( _v0$1, _v2$3 ); + + // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb + // make an axis testing of each of the 3 sides of the aabb against each of the 3 sides of the triangle = 9 axis of separation + // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned) + let axes = [ + 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y, + _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x, + - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0 + ]; + if ( ! satForAxes( axes, _v0$1, _v1$4, _v2$3, _extents ) ) { + + return false; + + } + + // test 3 face normals from the aabb + axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ]; + if ( ! satForAxes( axes, _v0$1, _v1$4, _v2$3, _extents ) ) { + + return false; + + } + + // finally testing the face normal of the triangle + // use already existing triangle edge vectors here + _triangleNormal.crossVectors( _f0, _f1 ); + axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ]; + + return satForAxes( axes, _v0$1, _v1$4, _v2$3, _extents ); + + } + + /** + * Clamps the given point within the bounds of this box. + * + * @param {Vector3} point - The point to clamp. + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {Vector3} The clamped point. + */ + clampPoint( point, target ) { + + return target.copy( point ).clamp( this.min, this.max ); + + } + + /** + * Returns the euclidean distance from any edge of this box to the specified point. If + * the given point lies inside of this box, the distance will be `0`. + * + * @param {Vector3} point - The point to compute the distance to. + * @return {number} The euclidean distance. + */ + distanceToPoint( point ) { + + return this.clampPoint( point, _vector$b ).distanceTo( point ); + + } + + /** + * Returns a bounding sphere that encloses this bounding box. + * + * @param {Sphere} target - The target sphere that is used to store the method's result. + * @return {Sphere} The bounding sphere that encloses this bounding box. + */ + getBoundingSphere( target ) { + + if ( this.isEmpty() ) { + + target.makeEmpty(); + + } else { + + this.getCenter( target.center ); + + target.radius = this.getSize( _vector$b ).length() * 0.5; + + } + + return target; + + } + + /** + * Computes the intersection of this bounding box and the given one, setting the upper + * bound of this box to the lesser of the two boxes' upper bounds and the + * lower bound of this box to the greater of the two boxes' lower bounds. If + * there's no overlap, makes this box empty. + * + * @param {Box3} box - The bounding box to intersect with. + * @return {Box3} A reference to this bounding box. + */ + intersect( box ) { + + this.min.max( box.min ); + this.max.min( box.max ); + + // ensure that if there is no overlap, the result is fully empty, not slightly empty with non-inf/+inf values that will cause subsequence intersects to erroneously return valid values. + if ( this.isEmpty() ) this.makeEmpty(); + + return this; + + } + + /** + * Computes the union of this box and another and the given one, setting the upper + * bound of this box to the greater of the two boxes' upper bounds and the + * lower bound of this box to the lesser of the two boxes' lower bounds. + * + * @param {Box3} box - The bounding box that will be unioned with this instance. + * @return {Box3} A reference to this bounding box. + */ + union( box ) { + + this.min.min( box.min ); + this.max.max( box.max ); + + return this; + + } + + /** + * Transforms this bounding box by the given 4x4 transformation matrix. + * + * @param {Matrix4} matrix - The transformation matrix. + * @return {Box3} A reference to this bounding box. + */ + applyMatrix4( matrix ) { + + // transform of empty box is an empty box. + if ( this.isEmpty() ) return this; + + // NOTE: I am using a binary pattern to specify all 2^3 combinations below + _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000 + _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001 + _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010 + _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011 + _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100 + _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101 + _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110 + _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111 + + this.setFromPoints( _points ); + + return this; + + } + + /** + * Adds the given offset to both the upper and lower bounds of this bounding box, + * effectively moving it in 3D space. + * + * @param {Vector3} offset - The offset that should be used to translate the bounding box. + * @return {Box3} A reference to this bounding box. + */ + translate( offset ) { + + this.min.add( offset ); + this.max.add( offset ); + + return this; + + } + + /** + * Returns `true` if this bounding box is equal with the given one. + * + * @param {Box3} box - The box to test for equality. + * @return {boolean} Whether this bounding box is equal with the given one. + */ + equals( box ) { + + return box.min.equals( this.min ) && box.max.equals( this.max ); + + } + + /** + * Returns a serialized structure of the bounding box. + * + * @return {Object} Serialized structure with fields representing the object state. + */ + toJSON() { + + return { + min: this.min.toArray(), + max: this.max.toArray() + }; + + } + + /** + * Returns a serialized structure of the bounding box. + * + * @param {Object} json - The serialized json to set the box from. + * @return {Box3} A reference to this bounding box. + */ + fromJSON( json ) { + + this.min.fromArray( json.min ); + this.max.fromArray( json.max ); + return this; + + } + +} + +const _points = [ + /*@__PURE__*/ new Vector3(), + /*@__PURE__*/ new Vector3(), + /*@__PURE__*/ new Vector3(), + /*@__PURE__*/ new Vector3(), + /*@__PURE__*/ new Vector3(), + /*@__PURE__*/ new Vector3(), + /*@__PURE__*/ new Vector3(), + /*@__PURE__*/ new Vector3() +]; + +const _vector$b = /*@__PURE__*/ new Vector3(); + +const _box$4 = /*@__PURE__*/ new Box3(); + +// triangle centered vertices + +const _v0$1 = /*@__PURE__*/ new Vector3(); +const _v1$4 = /*@__PURE__*/ new Vector3(); +const _v2$3 = /*@__PURE__*/ new Vector3(); + +// triangle edge vectors + +const _f0 = /*@__PURE__*/ new Vector3(); +const _f1 = /*@__PURE__*/ new Vector3(); +const _f2 = /*@__PURE__*/ new Vector3(); + +const _center = /*@__PURE__*/ new Vector3(); +const _extents = /*@__PURE__*/ new Vector3(); +const _triangleNormal = /*@__PURE__*/ new Vector3(); +const _testAxis = /*@__PURE__*/ new Vector3(); + +function satForAxes( axes, v0, v1, v2, extents ) { + + for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) { + + _testAxis.fromArray( axes, i ); + // project the aabb onto the separating axis + const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z ); + // project all 3 vertices of the triangle onto the separating axis + const p0 = v0.dot( _testAxis ); + const p1 = v1.dot( _testAxis ); + const p2 = v2.dot( _testAxis ); + // actual test, basically see if either of the most extreme of the triangle points intersects r + if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) { + + // points of the projected triangle are outside the projected half-length of the aabb + // the axis is separating and we can exit + return false; + + } + + } + + return true; + +} + +// Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf + +const _tables = /*@__PURE__*/ _generateTables(); + +function _generateTables() { + + // float32 to float16 helpers + + const buffer = new ArrayBuffer( 4 ); + const floatView = new Float32Array( buffer ); + const uint32View = new Uint32Array( buffer ); + + const baseTable = new Uint32Array( 512 ); + const shiftTable = new Uint32Array( 512 ); + + for ( let i = 0; i < 256; ++ i ) { + + const e = i - 127; + + // very small number (0, -0) + + if ( e < -27 ) { + + baseTable[ i ] = 0x0000; + baseTable[ i | 0x100 ] = 0x8000; + shiftTable[ i ] = 24; + shiftTable[ i | 0x100 ] = 24; + + // small number (denorm) + + } else if ( e < -14 ) { + + baseTable[ i ] = 0x0400 >> ( - e - 14 ); + baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000; + shiftTable[ i ] = - e - 1; + shiftTable[ i | 0x100 ] = - e - 1; + + // normal number + + } else if ( e <= 15 ) { + + baseTable[ i ] = ( e + 15 ) << 10; + baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000; + shiftTable[ i ] = 13; + shiftTable[ i | 0x100 ] = 13; + + // large number (Infinity, -Infinity) + + } else if ( e < 128 ) { + + baseTable[ i ] = 0x7c00; + baseTable[ i | 0x100 ] = 0xfc00; + shiftTable[ i ] = 24; + shiftTable[ i | 0x100 ] = 24; + + // stay (NaN, Infinity, -Infinity) + + } else { + + baseTable[ i ] = 0x7c00; + baseTable[ i | 0x100 ] = 0xfc00; + shiftTable[ i ] = 13; + shiftTable[ i | 0x100 ] = 13; + + } + + } + + // float16 to float32 helpers + + const mantissaTable = new Uint32Array( 2048 ); + const exponentTable = new Uint32Array( 64 ); + const offsetTable = new Uint32Array( 64 ); + + for ( let i = 1; i < 1024; ++ i ) { + + let m = i << 13; // zero pad mantissa bits + let e = 0; // zero exponent + + // normalized + while ( ( m & 0x00800000 ) === 0 ) { + + m <<= 1; + e -= 0x00800000; // decrement exponent + + } + + m &= -8388609; // clear leading 1 bit + e += 0x38800000; // adjust bias + + mantissaTable[ i ] = m | e; + + } + + for ( let i = 1024; i < 2048; ++ i ) { + + mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 ); + + } + + for ( let i = 1; i < 31; ++ i ) { + + exponentTable[ i ] = i << 23; + + } + + exponentTable[ 31 ] = 0x47800000; + exponentTable[ 32 ] = 0x80000000; + + for ( let i = 33; i < 63; ++ i ) { + + exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 ); + + } + + exponentTable[ 63 ] = 0xc7800000; + + for ( let i = 1; i < 64; ++ i ) { + + if ( i !== 32 ) { + + offsetTable[ i ] = 1024; + + } + + } + + return { + floatView: floatView, + uint32View: uint32View, + baseTable: baseTable, + shiftTable: shiftTable, + mantissaTable: mantissaTable, + exponentTable: exponentTable, + offsetTable: offsetTable + }; + +} + +/** + * Returns a half precision floating point value (FP16) from the given single + * precision floating point value (FP32). + * + * @param {number} val - A single precision floating point value. + * @return {number} The FP16 value. + */ +function toHalfFloat( val ) { + + if ( Math.abs( val ) > 65504 ) warn( 'DataUtils.toHalfFloat(): Value out of range.' ); + + val = clamp( val, -65504, 65504 ); + + _tables.floatView[ 0 ] = val; + const f = _tables.uint32View[ 0 ]; + const e = ( f >> 23 ) & 0x1ff; + return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] ); + +} + +/** + * Returns a single precision floating point value (FP32) from the given half + * precision floating point value (FP16). + * + * @param {number} val - A half precision floating point value. + * @return {number} The FP32 value. + */ +function fromHalfFloat( val ) { + + const m = val >> 10; + _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ]; + return _tables.floatView[ 0 ]; + +} + +/** + * A class containing utility functions for data. + * + * @hideconstructor + */ +class DataUtils { + + /** + * Returns a half precision floating point value (FP16) from the given single + * precision floating point value (FP32). + * + * @param {number} val - A single precision floating point value. + * @return {number} The FP16 value. + */ + static toHalfFloat( val ) { + + return toHalfFloat( val ); + + } + + /** + * Returns a single precision floating point value (FP32) from the given half + * precision floating point value (FP16). + * + * @param {number} val - A half precision floating point value. + * @return {number} The FP32 value. + */ + static fromHalfFloat( val ) { + + return fromHalfFloat( val ); + + } + +} + +const _vector$a = /*@__PURE__*/ new Vector3(); +const _vector2$1 = /*@__PURE__*/ new Vector2(); + +let _id$2 = 0; + +/** + * This class stores data for an attribute (such as vertex positions, face + * indices, normals, colors, UVs, and any custom attributes ) associated with + * a geometry, which allows for more efficient passing of data to the GPU. + * + * When working with vector-like data, the `fromBufferAttribute( attribute, index )` + * helper methods on vector and color class might be helpful. E.g. {@link Vector3#fromBufferAttribute}. + */ +class BufferAttribute extends EventDispatcher { + + /** + * Constructs a new buffer attribute. + * + * @param {TypedArray} array - The array holding the attribute data. + * @param {number} itemSize - The item size. + * @param {boolean} [normalized=false] - Whether the data are normalized or not. + */ + constructor( array, itemSize, normalized = false ) { + + super(); + + if ( Array.isArray( array ) ) { + + throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' ); + + } + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isBufferAttribute = true; + + /** + * The ID of the buffer attribute. + * + * @name BufferAttribute#id + * @type {number} + * @readonly + */ + Object.defineProperty( this, 'id', { value: _id$2 ++ } ); + + /** + * The name of the buffer attribute. + * + * @type {string} + */ + this.name = ''; + + /** + * The array holding the attribute data. It should have `itemSize * numVertices` + * elements, where `numVertices` is the number of vertices in the associated geometry. + * + * @type {TypedArray} + */ + this.array = array; + + /** + * The number of values of the array that should be associated with a particular vertex. + * For instance, if this attribute is storing a 3-component vector (such as a position, + * normal, or color), then the value should be `3`. + * + * @type {number} + */ + this.itemSize = itemSize; + + /** + * Represents the number of items this buffer attribute stores. It is internally computed + * by dividing the `array` length by the `itemSize`. + * + * @type {number} + * @readonly + */ + this.count = array !== undefined ? array.length / itemSize : 0; + + /** + * Applies to integer data only. Indicates how the underlying data in the buffer maps to + * the values in the GLSL code. For instance, if `array` is an instance of `UInt16Array`, + * and `normalized` is `true`, the values `0 - +65535` in the array data will be mapped to + * `0.0f - +1.0f` in the GLSL attribute. If `normalized` is `false`, the values will be converted + * to floats unmodified, i.e. `65535` becomes `65535.0f`. + * + * @type {boolean} + */ + this.normalized = normalized; + + /** + * Defines the intended usage pattern of the data store for optimization purposes. + * + * Note: After the initial use of a buffer, its usage cannot be changed. Instead, + * instantiate a new one and set the desired usage before the next render. + * + * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} + * @default StaticDrawUsage + */ + this.usage = StaticDrawUsage; + + /** + * This can be used to only update some components of stored vectors (for example, just the + * component related to color). Use the `addUpdateRange()` function to add ranges to this array. + * + * @type {Array} + */ + this.updateRanges = []; + + /** + * Configures the bound GPU type for use in shaders. + * + * Note: this only has an effect for integer arrays and is not configurable for float arrays. + * For lower precision float types, use `Float16BufferAttribute`. + * + * @type {(FloatType|IntType)} + * @default FloatType + */ + this.gpuType = FloatType; + + /** + * A version number, incremented every time the `needsUpdate` is set to `true`. + * + * @type {number} + */ + this.version = 0; + + } + + /** + * A callback function that is executed after the renderer has transferred the attribute + * array data to the GPU. + */ + onUploadCallback() {} + + /** + * Flag to indicate that this attribute has changed and should be re-sent to + * the GPU. Set this to `true` when you modify the value of the array. + * + * @type {number} + * @default false + * @param {boolean} value + */ + set needsUpdate( value ) { + + if ( value === true ) this.version ++; + + } + + /** + * Sets the usage of this buffer attribute. + * + * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set. + * @return {BufferAttribute} A reference to this buffer attribute. + */ + setUsage( value ) { + + this.usage = value; + + return this; + + } + + /** + * Adds a range of data in the data array to be updated on the GPU. + * + * @param {number} start - Position at which to start update. + * @param {number} count - The number of components to update. + */ + addUpdateRange( start, count ) { + + this.updateRanges.push( { start, count } ); + + } + + /** + * Clears the update ranges. + */ + clearUpdateRanges() { + + this.updateRanges.length = 0; + + } + + /** + * Copies the values of the given buffer attribute to this instance. + * + * @param {BufferAttribute} source - The buffer attribute to copy. + * @return {BufferAttribute} A reference to this instance. + */ + copy( source ) { + + this.name = source.name; + this.array = new source.array.constructor( source.array ); + this.itemSize = source.itemSize; + this.count = source.count; + this.normalized = source.normalized; + + this.usage = source.usage; + this.gpuType = source.gpuType; + + return this; + + } + + /** + * Copies a vector from the given buffer attribute to this one. The start + * and destination position in the attribute buffers are represented by the + * given indices. + * + * @param {number} index1 - The destination index into this buffer attribute. + * @param {BufferAttribute} attribute - The buffer attribute to copy from. + * @param {number} index2 - The source index into the given buffer attribute. + * @return {BufferAttribute} A reference to this instance. + */ + copyAt( index1, attribute, index2 ) { + + index1 *= this.itemSize; + index2 *= attribute.itemSize; + + for ( let i = 0, l = this.itemSize; i < l; i ++ ) { + + this.array[ index1 + i ] = attribute.array[ index2 + i ]; + + } + + return this; + + } + + /** + * Copies the given array data into this buffer attribute. + * + * @param {(TypedArray|Array)} array - The array to copy. + * @return {BufferAttribute} A reference to this instance. + */ + copyArray( array ) { + + this.array.set( array ); + + return this; + + } + + /** + * Applies the given 3x3 matrix to the given attribute. Works with + * item size `2` and `3`. + * + * @param {Matrix3} m - The matrix to apply. + * @return {BufferAttribute} A reference to this instance. + */ + applyMatrix3( m ) { + + if ( this.itemSize === 2 ) { + + for ( let i = 0, l = this.count; i < l; i ++ ) { + + _vector2$1.fromBufferAttribute( this, i ); + _vector2$1.applyMatrix3( m ); + + this.setXY( i, _vector2$1.x, _vector2$1.y ); + + } + + } else if ( this.itemSize === 3 ) { + + for ( let i = 0, l = this.count; i < l; i ++ ) { + + _vector$a.fromBufferAttribute( this, i ); + _vector$a.applyMatrix3( m ); + + this.setXYZ( i, _vector$a.x, _vector$a.y, _vector$a.z ); + + } + + } + + return this; + + } + + /** + * Applies the given 4x4 matrix to the given attribute. Only works with + * item size `3`. + * + * @param {Matrix4} m - The matrix to apply. + * @return {BufferAttribute} A reference to this instance. + */ + applyMatrix4( m ) { + + for ( let i = 0, l = this.count; i < l; i ++ ) { + + _vector$a.fromBufferAttribute( this, i ); + + _vector$a.applyMatrix4( m ); + + this.setXYZ( i, _vector$a.x, _vector$a.y, _vector$a.z ); + + } + + return this; + + } + + /** + * Applies the given 3x3 normal matrix to the given attribute. Only works with + * item size `3`. + * + * @param {Matrix3} m - The normal matrix to apply. + * @return {BufferAttribute} A reference to this instance. + */ + applyNormalMatrix( m ) { + + for ( let i = 0, l = this.count; i < l; i ++ ) { + + _vector$a.fromBufferAttribute( this, i ); + + _vector$a.applyNormalMatrix( m ); + + this.setXYZ( i, _vector$a.x, _vector$a.y, _vector$a.z ); + + } + + return this; + + } + + /** + * Applies the given 4x4 matrix to the given attribute. Only works with + * item size `3` and with direction vectors. + * + * @param {Matrix4} m - The matrix to apply. + * @return {BufferAttribute} A reference to this instance. + */ + transformDirection( m ) { + + for ( let i = 0, l = this.count; i < l; i ++ ) { + + _vector$a.fromBufferAttribute( this, i ); + + _vector$a.transformDirection( m ); + + this.setXYZ( i, _vector$a.x, _vector$a.y, _vector$a.z ); + + } + + return this; + + } + + /** + * Sets the given array data in the buffer attribute. + * + * @param {(TypedArray|Array)} value - The array data to set. + * @param {number} [offset=0] - The offset in this buffer attribute's array. + * @return {BufferAttribute} A reference to this instance. + */ + set( value, offset = 0 ) { + + // Matching BufferAttribute constructor, do not normalize the array. + this.array.set( value, offset ); + + return this; + + } + + /** + * Returns the given component of the vector at the given index. + * + * @param {number} index - The index into the buffer attribute. + * @param {number} component - The component index. + * @return {number} The returned value. + */ + getComponent( index, component ) { + + let value = this.array[ index * this.itemSize + component ]; + + if ( this.normalized ) value = denormalize( value, this.array ); + + return value; + + } + + /** + * Sets the given value to the given component of the vector at the given index. + * + * @param {number} index - The index into the buffer attribute. + * @param {number} component - The component index. + * @param {number} value - The value to set. + * @return {BufferAttribute} A reference to this instance. + */ + setComponent( index, component, value ) { + + if ( this.normalized ) value = normalize( value, this.array ); + + this.array[ index * this.itemSize + component ] = value; + + return this; + + } + + /** + * Returns the x component of the vector at the given index. + * + * @param {number} index - The index into the buffer attribute. + * @return {number} The x component. + */ + getX( index ) { + + let x = this.array[ index * this.itemSize ]; + + if ( this.normalized ) x = denormalize( x, this.array ); + + return x; + + } + + /** + * Sets the x component of the vector at the given index. + * + * @param {number} index - The index into the buffer attribute. + * @param {number} x - The value to set. + * @return {BufferAttribute} A reference to this instance. + */ + setX( index, x ) { + + if ( this.normalized ) x = normalize( x, this.array ); + + this.array[ index * this.itemSize ] = x; + + return this; + + } + + /** + * Returns the y component of the vector at the given index. + * + * @param {number} index - The index into the buffer attribute. + * @return {number} The y component. + */ + getY( index ) { + + let y = this.array[ index * this.itemSize + 1 ]; + + if ( this.normalized ) y = denormalize( y, this.array ); + + return y; + + } + + /** + * Sets the y component of the vector at the given index. + * + * @param {number} index - The index into the buffer attribute. + * @param {number} y - The value to set. + * @return {BufferAttribute} A reference to this instance. + */ + setY( index, y ) { + + if ( this.normalized ) y = normalize( y, this.array ); + + this.array[ index * this.itemSize + 1 ] = y; + + return this; + + } + + /** + * Returns the z component of the vector at the given index. + * + * @param {number} index - The index into the buffer attribute. + * @return {number} The z component. + */ + getZ( index ) { + + let z = this.array[ index * this.itemSize + 2 ]; + + if ( this.normalized ) z = denormalize( z, this.array ); + + return z; + + } + + /** + * Sets the z component of the vector at the given index. + * + * @param {number} index - The index into the buffer attribute. + * @param {number} z - The value to set. + * @return {BufferAttribute} A reference to this instance. + */ + setZ( index, z ) { + + if ( this.normalized ) z = normalize( z, this.array ); + + this.array[ index * this.itemSize + 2 ] = z; + + return this; + + } + + /** + * Returns the w component of the vector at the given index. + * + * @param {number} index - The index into the buffer attribute. + * @return {number} The w component. + */ + getW( index ) { + + let w = this.array[ index * this.itemSize + 3 ]; + + if ( this.normalized ) w = denormalize( w, this.array ); + + return w; + + } + + /** + * Sets the w component of the vector at the given index. + * + * @param {number} index - The index into the buffer attribute. + * @param {number} w - The value to set. + * @return {BufferAttribute} A reference to this instance. + */ + setW( index, w ) { + + if ( this.normalized ) w = normalize( w, this.array ); + + this.array[ index * this.itemSize + 3 ] = w; + + return this; + + } + + /** + * Sets the x and y component of the vector at the given index. + * + * @param {number} index - The index into the buffer attribute. + * @param {number} x - The value for the x component to set. + * @param {number} y - The value for the y component to set. + * @return {BufferAttribute} A reference to this instance. + */ + setXY( index, x, y ) { + + index *= this.itemSize; + + if ( this.normalized ) { + + x = normalize( x, this.array ); + y = normalize( y, this.array ); + + } + + this.array[ index + 0 ] = x; + this.array[ index + 1 ] = y; + + return this; + + } + + /** + * Sets the x, y and z component of the vector at the given index. + * + * @param {number} index - The index into the buffer attribute. + * @param {number} x - The value for the x component to set. + * @param {number} y - The value for the y component to set. + * @param {number} z - The value for the z component to set. + * @return {BufferAttribute} A reference to this instance. + */ + setXYZ( index, x, y, z ) { + + index *= this.itemSize; + + if ( this.normalized ) { + + x = normalize( x, this.array ); + y = normalize( y, this.array ); + z = normalize( z, this.array ); + + } + + this.array[ index + 0 ] = x; + this.array[ index + 1 ] = y; + this.array[ index + 2 ] = z; + + return this; + + } + + /** + * Sets the x, y, z and w component of the vector at the given index. + * + * @param {number} index - The index into the buffer attribute. + * @param {number} x - The value for the x component to set. + * @param {number} y - The value for the y component to set. + * @param {number} z - The value for the z component to set. + * @param {number} w - The value for the w component to set. + * @return {BufferAttribute} A reference to this instance. + */ + setXYZW( index, x, y, z, w ) { + + index *= this.itemSize; + + if ( this.normalized ) { + + x = normalize( x, this.array ); + y = normalize( y, this.array ); + z = normalize( z, this.array ); + w = normalize( w, this.array ); + + } + + this.array[ index + 0 ] = x; + this.array[ index + 1 ] = y; + this.array[ index + 2 ] = z; + this.array[ index + 3 ] = w; + + return this; + + } + + /** + * Sets the given callback function that is executed after the Renderer has transferred + * the attribute array data to the GPU. Can be used to perform clean-up operations after + * the upload when attribute data are not needed anymore on the CPU side. + * + * @param {Function} callback - The `onUpload()` callback. + * @return {BufferAttribute} A reference to this instance. + */ + onUpload( callback ) { + + this.onUploadCallback = callback; + + return this; + + } + + /** + * Returns a new buffer attribute with copied values from this instance. + * + * @return {BufferAttribute} A clone of this instance. + */ + clone() { + + return new this.constructor( this.array, this.itemSize ).copy( this ); + + } + + /** + * Serializes the buffer attribute into JSON. + * + * @return {Object} A JSON object representing the serialized buffer attribute. + */ + toJSON() { + + const data = { + itemSize: this.itemSize, + type: this.array.constructor.name, + array: Array.from( this.array ), + normalized: this.normalized + }; + + data.name = this.name; + data.usage = this.usage; + data.gpuType = this.gpuType; + + return data; + + } + + /** + * Disposes of the buffer attribute. Available only in {@link WebGPURenderer}. + */ + dispose() { + + this.dispatchEvent( { type: 'dispose' } ); + + } + +} + +/** + * Convenient class that can be used when creating a `Int8` buffer attribute with + * a plain `Array` instance. + * + * @augments BufferAttribute + */ +class Int8BufferAttribute extends BufferAttribute { + + /** + * Constructs a new buffer attribute. + * + * @param {(Array|Int8Array)} array - The array holding the attribute data. + * @param {number} itemSize - The item size. + * @param {boolean} [normalized=false] - Whether the data are normalized or not. + */ + constructor( array, itemSize, normalized ) { + + super( new Int8Array( array ), itemSize, normalized ); + + } + +} + +/** + * Convenient class that can be used when creating a `UInt8` buffer attribute with + * a plain `Array` instance. + * + * @augments BufferAttribute + */ +class Uint8BufferAttribute extends BufferAttribute { + + /** + * Constructs a new buffer attribute. + * + * @param {(Array|Uint8Array)} array - The array holding the attribute data. + * @param {number} itemSize - The item size. + * @param {boolean} [normalized=false] - Whether the data are normalized or not. + */ + constructor( array, itemSize, normalized ) { + + super( new Uint8Array( array ), itemSize, normalized ); + + } + +} + +/** + * Convenient class that can be used when creating a `UInt8Clamped` buffer attribute with + * a plain `Array` instance. + * + * @augments BufferAttribute + */ +class Uint8ClampedBufferAttribute extends BufferAttribute { + + /** + * Constructs a new buffer attribute. + * + * @param {(Array|Uint8ClampedArray)} array - The array holding the attribute data. + * @param {number} itemSize - The item size. + * @param {boolean} [normalized=false] - Whether the data are normalized or not. + */ + constructor( array, itemSize, normalized ) { + + super( new Uint8ClampedArray( array ), itemSize, normalized ); + + } + +} + +/** + * Convenient class that can be used when creating a `Int16` buffer attribute with + * a plain `Array` instance. + * + * @augments BufferAttribute + */ +class Int16BufferAttribute extends BufferAttribute { + + /** + * Constructs a new buffer attribute. + * + * @param {(Array|Int16Array)} array - The array holding the attribute data. + * @param {number} itemSize - The item size. + * @param {boolean} [normalized=false] - Whether the data are normalized or not. + */ + constructor( array, itemSize, normalized ) { + + super( new Int16Array( array ), itemSize, normalized ); + + } + +} + +/** + * Convenient class that can be used when creating a `UInt16` buffer attribute with + * a plain `Array` instance. + * + * @augments BufferAttribute + */ +class Uint16BufferAttribute extends BufferAttribute { + + /** + * Constructs a new buffer attribute. + * + * @param {(Array|Uint16Array)} array - The array holding the attribute data. + * @param {number} itemSize - The item size. + * @param {boolean} [normalized=false] - Whether the data are normalized or not. + */ + constructor( array, itemSize, normalized ) { + + super( new Uint16Array( array ), itemSize, normalized ); + + } + +} + +/** + * Convenient class that can be used when creating a `Int32` buffer attribute with + * a plain `Array` instance. + * + * @augments BufferAttribute + */ +class Int32BufferAttribute extends BufferAttribute { + + /** + * Constructs a new buffer attribute. + * + * @param {(Array|Int32Array)} array - The array holding the attribute data. + * @param {number} itemSize - The item size. + * @param {boolean} [normalized=false] - Whether the data are normalized or not. + */ + constructor( array, itemSize, normalized ) { + + super( new Int32Array( array ), itemSize, normalized ); + + } + +} + +/** + * Convenient class that can be used when creating a `UInt32` buffer attribute with + * a plain `Array` instance. + * + * @augments BufferAttribute + */ +class Uint32BufferAttribute extends BufferAttribute { + + /** + * Constructs a new buffer attribute. + * + * @param {(Array|Uint32Array)} array - The array holding the attribute data. + * @param {number} itemSize - The item size. + * @param {boolean} [normalized=false] - Whether the data are normalized or not. + */ + constructor( array, itemSize, normalized ) { + + super( new Uint32Array( array ), itemSize, normalized ); + + } + +} + +/** + * Convenient class that can be used when creating a `Float16` buffer attribute with + * a plain `Array` instance. + * + * This class automatically converts to and from FP16 via `Uint16Array` since `Float16Array` + * browser support is still problematic. + * + * @augments BufferAttribute + */ +class Float16BufferAttribute extends BufferAttribute { + + /** + * Constructs a new buffer attribute. + * + * @param {(Array|Uint16Array)} array - The array holding the attribute data. + * @param {number} itemSize - The item size. + * @param {boolean} [normalized=false] - Whether the data are normalized or not. + */ + constructor( array, itemSize, normalized ) { + + super( new Uint16Array( array ), itemSize, normalized ); + + this.isFloat16BufferAttribute = true; + + } + + getX( index ) { + + let x = fromHalfFloat( this.array[ index * this.itemSize ] ); + + if ( this.normalized ) x = denormalize( x, this.array ); + + return x; + + } + + setX( index, x ) { + + if ( this.normalized ) x = normalize( x, this.array ); + + this.array[ index * this.itemSize ] = toHalfFloat( x ); + + return this; + + } + + getY( index ) { + + let y = fromHalfFloat( this.array[ index * this.itemSize + 1 ] ); + + if ( this.normalized ) y = denormalize( y, this.array ); + + return y; + + } + + setY( index, y ) { + + if ( this.normalized ) y = normalize( y, this.array ); + + this.array[ index * this.itemSize + 1 ] = toHalfFloat( y ); + + return this; + + } + + getZ( index ) { + + let z = fromHalfFloat( this.array[ index * this.itemSize + 2 ] ); + + if ( this.normalized ) z = denormalize( z, this.array ); + + return z; + + } + + setZ( index, z ) { + + if ( this.normalized ) z = normalize( z, this.array ); + + this.array[ index * this.itemSize + 2 ] = toHalfFloat( z ); + + return this; + + } + + getW( index ) { + + let w = fromHalfFloat( this.array[ index * this.itemSize + 3 ] ); + + if ( this.normalized ) w = denormalize( w, this.array ); + + return w; + + } + + setW( index, w ) { + + if ( this.normalized ) w = normalize( w, this.array ); + + this.array[ index * this.itemSize + 3 ] = toHalfFloat( w ); + + return this; + + } + + setXY( index, x, y ) { + + index *= this.itemSize; + + if ( this.normalized ) { + + x = normalize( x, this.array ); + y = normalize( y, this.array ); + + } + + this.array[ index + 0 ] = toHalfFloat( x ); + this.array[ index + 1 ] = toHalfFloat( y ); + + return this; + + } + + setXYZ( index, x, y, z ) { + + index *= this.itemSize; + + if ( this.normalized ) { + + x = normalize( x, this.array ); + y = normalize( y, this.array ); + z = normalize( z, this.array ); + + } + + this.array[ index + 0 ] = toHalfFloat( x ); + this.array[ index + 1 ] = toHalfFloat( y ); + this.array[ index + 2 ] = toHalfFloat( z ); + + return this; + + } + + setXYZW( index, x, y, z, w ) { + + index *= this.itemSize; + + if ( this.normalized ) { + + x = normalize( x, this.array ); + y = normalize( y, this.array ); + z = normalize( z, this.array ); + w = normalize( w, this.array ); + + } + + this.array[ index + 0 ] = toHalfFloat( x ); + this.array[ index + 1 ] = toHalfFloat( y ); + this.array[ index + 2 ] = toHalfFloat( z ); + this.array[ index + 3 ] = toHalfFloat( w ); + + return this; + + } + +} + +/** + * Convenient class that can be used when creating a `Float32` buffer attribute with + * a plain `Array` instance. + * + * @augments BufferAttribute + */ +class Float32BufferAttribute extends BufferAttribute { + + /** + * Constructs a new buffer attribute. + * + * @param {(Array|Float32Array)} array - The array holding the attribute data. + * @param {number} itemSize - The item size. + * @param {boolean} [normalized=false] - Whether the data are normalized or not. + */ + constructor( array, itemSize, normalized ) { + + super( new Float32Array( array ), itemSize, normalized ); + + } + +} + +const _box$3 = /*@__PURE__*/ new Box3(); +const _v1$3 = /*@__PURE__*/ new Vector3(); +const _v2$2 = /*@__PURE__*/ new Vector3(); + +/** + * An analytical 3D sphere defined by a center and radius. This class is mainly + * used as a Bounding Sphere for 3D objects. + */ +class Sphere { + + /** + * Constructs a new sphere. + * + * @param {Vector3} [center=(0,0,0)] - The center of the sphere + * @param {number} [radius=-1] - The radius of the sphere. + */ + constructor( center = new Vector3(), radius = -1 ) { + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isSphere = true; + + /** + * The center of the sphere + * + * @type {Vector3} + */ + this.center = center; + + /** + * The radius of the sphere. + * + * @type {number} + */ + this.radius = radius; + + } + + /** + * Sets the sphere's components by copying the given values. + * + * @param {Vector3} center - The center. + * @param {number} radius - The radius. + * @return {Sphere} A reference to this sphere. + */ + set( center, radius ) { + + this.center.copy( center ); + this.radius = radius; + + return this; + + } + + /** + * Computes the minimum bounding sphere for list of points. + * If the optional center point is given, it is used as the sphere's + * center. Otherwise, the center of the axis-aligned bounding box + * encompassing the points is calculated. + * + * @param {Array} points - A list of points in 3D space. + * @param {Vector3} [optionalCenter] - The center of the sphere. + * @return {Sphere} A reference to this sphere. + */ + setFromPoints( points, optionalCenter ) { + + const center = this.center; + + if ( optionalCenter !== undefined ) { + + center.copy( optionalCenter ); + + } else { + + _box$3.setFromPoints( points ).getCenter( center ); + + } + + let maxRadiusSq = 0; + + for ( let i = 0, il = points.length; i < il; i ++ ) { + + maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) ); + + } + + this.radius = Math.sqrt( maxRadiusSq ); + + return this; + + } + + /** + * Copies the values of the given sphere to this instance. + * + * @param {Sphere} sphere - The sphere to copy. + * @return {Sphere} A reference to this sphere. + */ + copy( sphere ) { + + this.center.copy( sphere.center ); + this.radius = sphere.radius; + + return this; + + } + + /** + * Returns `true` if the sphere is empty (the radius set to a negative number). + * + * Spheres with a radius of `0` contain only their center point and are not + * considered to be empty. + * + * @return {boolean} Whether this sphere is empty or not. + */ + isEmpty() { + + return ( this.radius < 0 ); + + } + + /** + * Makes this sphere empty which means in encloses a zero space in 3D. + * + * @return {Sphere} A reference to this sphere. + */ + makeEmpty() { + + this.center.set( 0, 0, 0 ); + this.radius = -1; + + return this; + + } + + /** + * Returns `true` if this sphere contains the given point inclusive of + * the surface of the sphere. + * + * @param {Vector3} point - The point to check. + * @return {boolean} Whether this sphere contains the given point or not. + */ + containsPoint( point ) { + + return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) ); + + } + + /** + * Returns the closest distance from the boundary of the sphere to the + * given point. If the sphere contains the point, the distance will + * be negative. + * + * @param {Vector3} point - The point to compute the distance to. + * @return {number} The distance to the point. + */ + distanceToPoint( point ) { + + return ( point.distanceTo( this.center ) - this.radius ); + + } + + /** + * Returns `true` if this sphere intersects with the given one. + * + * @param {Sphere} sphere - The sphere to test. + * @return {boolean} Whether this sphere intersects with the given one or not. + */ + intersectsSphere( sphere ) { + + const radiusSum = this.radius + sphere.radius; + + return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum ); + + } + + /** + * Returns `true` if this sphere intersects with the given box. + * + * @param {Box3} box - The box to test. + * @return {boolean} Whether this sphere intersects with the given box or not. + */ + intersectsBox( box ) { + + return box.intersectsSphere( this ); + + } + + /** + * Returns `true` if this sphere intersects with the given plane. + * + * @param {Plane} plane - The plane to test. + * @return {boolean} Whether this sphere intersects with the given plane or not. + */ + intersectsPlane( plane ) { + + return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius; + + } + + /** + * Clamps a point within the sphere. If the point is outside the sphere, it + * will clamp it to the closest point on the edge of the sphere. Points + * already inside the sphere will not be affected. + * + * @param {Vector3} point - The plane to clamp. + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {Vector3} The clamped point. + */ + clampPoint( point, target ) { + + const deltaLengthSq = this.center.distanceToSquared( point ); + + target.copy( point ); + + if ( deltaLengthSq > ( this.radius * this.radius ) ) { + + target.sub( this.center ).normalize(); + target.multiplyScalar( this.radius ).add( this.center ); + + } + + return target; + + } + + /** + * Returns a bounding box that encloses this sphere. + * + * @param {Box3} target - The target box that is used to store the method's result. + * @return {Box3} The bounding box that encloses this sphere. + */ + getBoundingBox( target ) { + + if ( this.isEmpty() ) { + + // Empty sphere produces empty bounding box + target.makeEmpty(); + return target; + + } + + target.set( this.center, this.center ); + target.expandByScalar( this.radius ); + + return target; + + } + + /** + * Transforms this sphere with the given 4x4 transformation matrix. + * + * @param {Matrix4} matrix - The transformation matrix. + * @return {Sphere} A reference to this sphere. + */ + applyMatrix4( matrix ) { + + this.center.applyMatrix4( matrix ); + this.radius = this.radius * matrix.getMaxScaleOnAxis(); + + return this; + + } + + /** + * Translates the sphere's center by the given offset. + * + * @param {Vector3} offset - The offset. + * @return {Sphere} A reference to this sphere. + */ + translate( offset ) { + + this.center.add( offset ); + + return this; + + } + + /** + * Expands the boundaries of this sphere to include the given point. + * + * @param {Vector3} point - The point to include. + * @return {Sphere} A reference to this sphere. + */ + expandByPoint( point ) { + + if ( this.isEmpty() ) { + + this.center.copy( point ); + + this.radius = 0; + + return this; + + } + + _v1$3.subVectors( point, this.center ); + + const lengthSq = _v1$3.lengthSq(); + + if ( lengthSq > ( this.radius * this.radius ) ) { + + // calculate the minimal sphere + + const length = Math.sqrt( lengthSq ); + + const delta = ( length - this.radius ) * 0.5; + + this.center.addScaledVector( _v1$3, delta / length ); + + this.radius += delta; + + } + + return this; + + } + + /** + * Expands this sphere to enclose both the original sphere and the given sphere. + * + * @param {Sphere} sphere - The sphere to include. + * @return {Sphere} A reference to this sphere. + */ + union( sphere ) { + + if ( sphere.isEmpty() ) { + + return this; + + } + + if ( this.isEmpty() ) { + + this.copy( sphere ); + + return this; + + } + + if ( this.center.equals( sphere.center ) === true ) { + + this.radius = Math.max( this.radius, sphere.radius ); + + } else { + + _v2$2.subVectors( sphere.center, this.center ).setLength( sphere.radius ); + + this.expandByPoint( _v1$3.copy( sphere.center ).add( _v2$2 ) ); + + this.expandByPoint( _v1$3.copy( sphere.center ).sub( _v2$2 ) ); + + } + + return this; + + } + + /** + * Returns `true` if this sphere is equal with the given one. + * + * @param {Sphere} sphere - The sphere to test for equality. + * @return {boolean} Whether this bounding sphere is equal with the given one. + */ + equals( sphere ) { + + return sphere.center.equals( this.center ) && ( sphere.radius === this.radius ); + + } + + /** + * Returns a new sphere with copied values from this instance. + * + * @return {Sphere} A clone of this instance. + */ + clone() { + + return new this.constructor().copy( this ); + + } + + /** + * Returns a serialized structure of the bounding sphere. + * + * @return {Object} Serialized structure with fields representing the object state. + */ + toJSON() { + + return { + radius: this.radius, + center: this.center.toArray() + }; + + } + + /** + * Returns a serialized structure of the bounding sphere. + * + * @param {Object} json - The serialized json to set the sphere from. + * @return {Sphere} A reference to this bounding sphere. + */ + fromJSON( json ) { + + this.radius = json.radius; + this.center.fromArray( json.center ); + return this; + + } + +} + +let _id$1 = 0; + +const _m1 = /*@__PURE__*/ new Matrix4(); +const _obj = /*@__PURE__*/ new Object3D(); +const _offset = /*@__PURE__*/ new Vector3(); +const _box$2 = /*@__PURE__*/ new Box3(); +const _boxMorphTargets = /*@__PURE__*/ new Box3(); +const _vector$9 = /*@__PURE__*/ new Vector3(); + +/** + * A representation of mesh, line, or point geometry. Includes vertex + * positions, face indices, normals, colors, UVs, and custom attributes + * within buffers, reducing the cost of passing all this data to the GPU. + * + * ```js + * const geometry = new THREE.BufferGeometry(); + * // create a simple square shape. We duplicate the top left and bottom right + * // vertices because each vertex needs to appear once per triangle. + * const vertices = new Float32Array( [ + * -1.0, -1.0, 1.0, // v0 + * 1.0, -1.0, 1.0, // v1 + * 1.0, 1.0, 1.0, // v2 + * + * 1.0, 1.0, 1.0, // v3 + * -1.0, 1.0, 1.0, // v4 + * -1.0, -1.0, 1.0 // v5 + * ] ); + * // itemSize = 3 because there are 3 values (components) per vertex + * geometry.setAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) ); + * const material = new THREE.MeshBasicMaterial( { color: 0xff0000 } ); + * const mesh = new THREE.Mesh( geometry, material ); + * ``` + * + * @augments EventDispatcher + */ +class BufferGeometry extends EventDispatcher { + + /** + * Constructs a new geometry. + */ + constructor() { + + super(); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isBufferGeometry = true; + + /** + * The ID of the geometry. + * + * @name BufferGeometry#id + * @type {number} + * @readonly + */ + Object.defineProperty( this, 'id', { value: _id$1 ++ } ); + + /** + * The UUID of the geometry. + * + * @type {string} + * @readonly + */ + this.uuid = generateUUID(); + + /** + * The name of the geometry. + * + * @type {string} + */ + this.name = ''; + this.type = 'BufferGeometry'; + + /** + * Allows for vertices to be re-used across multiple triangles; this is + * called using "indexed triangles". Each triangle is associated with the + * indices of three vertices. This attribute therefore stores the index of + * each vertex for each triangular face. If this attribute is not set, the + * renderer assumes that each three contiguous positions represent a single triangle. + * + * @type {?BufferAttribute} + * @default null + */ + this.index = null; + + /** + * A (storage) buffer attribute which was generated with a compute shader and + * now defines indirect draw calls. + * + * Can only be used with {@link WebGPURenderer} and a WebGPU backend. + * + * @type {?BufferAttribute} + * @default null + */ + this.indirect = null; + + /** + * The offset, in bytes, into the indirect drawing buffer where the value data begins. If an array is provided, multiple indirect draw calls will be made for each offset. + * + * Can only be used with {@link WebGPURenderer} and a WebGPU backend. + * + * @type {number|Array} + * @default 0 + */ + this.indirectOffset = 0; + + /** + * This dictionary has as id the name of the attribute to be set and as value + * the buffer attribute to set it to. Rather than accessing this property directly, + * use `setAttribute()` and `getAttribute()` to access attributes of this geometry. + * + * @type {Object} + */ + this.attributes = {}; + + /** + * This dictionary holds the morph targets of the geometry. + * + * Note: Once the geometry has been rendered, the morph attribute data cannot + * be changed. You will have to call `dispose()`, and create a new geometry instance. + * + * @type {Object} + */ + this.morphAttributes = {}; + + /** + * Used to control the morph target behavior; when set to `true`, the morph + * target data is treated as relative offsets, rather than as absolute + * positions/normals. + * + * @type {boolean} + * @default false + */ + this.morphTargetsRelative = false; + + /** + * Split the geometry into groups, each of which will be rendered in a + * separate draw call. This allows an array of materials to be used with the geometry. + * + * Use `addGroup()` and `clearGroups()` to edit groups, rather than modifying this array directly. + * + * Every vertex and index must belong to exactly one group — groups must not share vertices or + * indices, and must not leave vertices or indices unused. + * + * @type {Array} + */ + this.groups = []; + + /** + * Bounding box for the geometry which can be calculated with `computeBoundingBox()`. + * + * @type {?Box3} + * @default null + */ + this.boundingBox = null; + + /** + * Bounding sphere for the geometry which can be calculated with `computeBoundingSphere()`. + * + * @type {?Sphere} + * @default null + */ + this.boundingSphere = null; + + /** + * Determines the part of the geometry to render. This should not be set directly, + * instead use `setDrawRange()`. + * + * @type {{start:number,count:number}} + */ + this.drawRange = { start: 0, count: Infinity }; + + /** + * An object that can be used to store custom data about the geometry. + * It should not hold references to functions as these will not be cloned. + * + * @type {Object} + */ + this.userData = {}; + + /** + * `true` when the geometry has been transformed since construction + * (e.g. via {@link BufferGeometry#applyMatrix4}). Only relevant for + * geometry generators (subclasses that populate `parameters`): when set, + * {@link BufferGeometry#toJSON} omits `parameters` since they no longer + * describe the geometry. + * + * @private + * @type {boolean} + * @default false + */ + this._transformed = false; + + } + + /** + * Returns the index of this geometry. + * + * @return {?BufferAttribute} The index. Returns `null` if no index is defined. + */ + getIndex() { + + return this.index; + + } + + /** + * Sets the given index to this geometry. + * + * @param {Array|BufferAttribute} index - The index to set. + * @return {BufferGeometry} A reference to this instance. + */ + setIndex( index ) { + + if ( Array.isArray( index ) ) { + + this.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 ); + + } else { + + this.index = index; + + } + + return this; + + } + + /** + * Sets the given indirect attribute to this geometry. + * + * @param {BufferAttribute} indirect - The attribute holding indirect draw calls. + * @param {number|Array} [indirectOffset=0] - The offset, in bytes, into the indirect drawing buffer where the value data begins. If an array is provided, multiple indirect draw calls will be made for each offset. + * @return {BufferGeometry} A reference to this instance. + */ + setIndirect( indirect, indirectOffset = 0 ) { + + this.indirect = indirect; + this.indirectOffset = indirectOffset; + + return this; + + } + + /** + * Returns the indirect attribute of this geometry. + * + * @return {?BufferAttribute} The indirect attribute. Returns `null` if no indirect attribute is defined. + */ + getIndirect() { + + return this.indirect; + + } + + /** + * Returns the buffer attribute for the given name. + * + * @param {string} name - The attribute name. + * @return {BufferAttribute|InterleavedBufferAttribute|undefined} The buffer attribute. + * Returns `undefined` if not attribute has been found. + */ + getAttribute( name ) { + + return this.attributes[ name ]; + + } + + /** + * Sets the given attribute for the given name. + * + * @param {string} name - The attribute name. + * @param {BufferAttribute|InterleavedBufferAttribute} attribute - The attribute to set. + * @return {BufferGeometry} A reference to this instance. + */ + setAttribute( name, attribute ) { + + this.attributes[ name ] = attribute; + + return this; + + } + + /** + * Deletes the attribute for the given name. + * + * @param {string} name - The attribute name to delete. + * @return {BufferGeometry} A reference to this instance. + */ + deleteAttribute( name ) { + + delete this.attributes[ name ]; + + return this; + + } + + /** + * Returns `true` if this geometry has an attribute for the given name. + * + * @param {string} name - The attribute name. + * @return {boolean} Whether this geometry has an attribute for the given name or not. + */ + hasAttribute( name ) { + + return this.attributes[ name ] !== undefined; + + } + + /** + * Adds a group to this geometry. + * + * @param {number} start - The first element in this draw call. That is the first + * vertex for non-indexed geometry, otherwise the first triangle index. + * @param {number} count - Specifies how many vertices (or indices) are part of this group. + * @param {number} [materialIndex=0] - The material array index to use. + */ + addGroup( start, count, materialIndex = 0 ) { + + this.groups.push( { + + start: start, + count: count, + materialIndex: materialIndex + + } ); + + } + + /** + * Clears all groups. + */ + clearGroups() { + + this.groups = []; + + } + + /** + * Sets the draw range for this geometry. + * + * @param {number} start - The first vertex for non-indexed geometry, otherwise the first triangle index. + * @param {number} count - For non-indexed BufferGeometry, `count` is the number of vertices to render. + * For indexed BufferGeometry, `count` is the number of indices to render. + */ + setDrawRange( start, count ) { + + this.drawRange.start = start; + this.drawRange.count = count; + + } + + /** + * Applies the given 4x4 transformation matrix to the geometry. + * + * @param {Matrix4} matrix - The matrix to apply. + * @return {BufferGeometry} A reference to this instance. + */ + applyMatrix4( matrix ) { + + const position = this.attributes.position; + + if ( position !== undefined ) { + + position.applyMatrix4( matrix ); + + position.needsUpdate = true; + + } + + const normal = this.attributes.normal; + + if ( normal !== undefined ) { + + const normalMatrix = new Matrix3().getNormalMatrix( matrix ); + + normal.applyNormalMatrix( normalMatrix ); + + normal.needsUpdate = true; + + } + + const tangent = this.attributes.tangent; + + if ( tangent !== undefined ) { + + tangent.transformDirection( matrix ); + + tangent.needsUpdate = true; + + } + + if ( this.boundingBox !== null ) { + + this.computeBoundingBox(); + + } + + if ( this.boundingSphere !== null ) { + + this.computeBoundingSphere(); + + } + + this._transformed = true; + + return this; + + } + + /** + * Applies the rotation represented by the Quaternion to the geometry. + * + * @param {Quaternion} q - The Quaternion to apply. + * @return {BufferGeometry} A reference to this instance. + */ + applyQuaternion( q ) { + + _m1.makeRotationFromQuaternion( q ); + + this.applyMatrix4( _m1 ); + + return this; + + } + + /** + * Rotates the geometry about the X axis. This is typically done as a one time + * operation, and not during a loop. Use {@link Object3D#rotation} for typical + * real-time mesh rotation. + * + * @param {number} angle - The angle in radians. + * @return {BufferGeometry} A reference to this instance. + */ + rotateX( angle ) { + + // rotate geometry around world x-axis + + _m1.makeRotationX( angle ); + + this.applyMatrix4( _m1 ); + + return this; + + } + + /** + * Rotates the geometry about the Y axis. This is typically done as a one time + * operation, and not during a loop. Use {@link Object3D#rotation} for typical + * real-time mesh rotation. + * + * @param {number} angle - The angle in radians. + * @return {BufferGeometry} A reference to this instance. + */ + rotateY( angle ) { + + // rotate geometry around world y-axis + + _m1.makeRotationY( angle ); + + this.applyMatrix4( _m1 ); + + return this; + + } + + /** + * Rotates the geometry about the Z axis. This is typically done as a one time + * operation, and not during a loop. Use {@link Object3D#rotation} for typical + * real-time mesh rotation. + * + * @param {number} angle - The angle in radians. + * @return {BufferGeometry} A reference to this instance. + */ + rotateZ( angle ) { + + // rotate geometry around world z-axis + + _m1.makeRotationZ( angle ); + + this.applyMatrix4( _m1 ); + + return this; + + } + + /** + * Translates the geometry. This is typically done as a one time + * operation, and not during a loop. Use {@link Object3D#position} for typical + * real-time mesh rotation. + * + * @param {number} x - The x offset. + * @param {number} y - The y offset. + * @param {number} z - The z offset. + * @return {BufferGeometry} A reference to this instance. + */ + translate( x, y, z ) { + + // translate geometry + + _m1.makeTranslation( x, y, z ); + + this.applyMatrix4( _m1 ); + + return this; + + } + + /** + * Scales the geometry. This is typically done as a one time + * operation, and not during a loop. Use {@link Object3D#scale} for typical + * real-time mesh rotation. + * + * @param {number} x - The x scale. + * @param {number} y - The y scale. + * @param {number} z - The z scale. + * @return {BufferGeometry} A reference to this instance. + */ + scale( x, y, z ) { + + // scale geometry + + _m1.makeScale( x, y, z ); + + this.applyMatrix4( _m1 ); + + return this; + + } + + /** + * Rotates the geometry to face a point in 3D space. This is typically done as a one time + * operation, and not during a loop. Use {@link Object3D#lookAt} for typical + * real-time mesh rotation. + * + * @param {Vector3} vector - The target point. + * @return {BufferGeometry} A reference to this instance. + */ + lookAt( vector ) { + + _obj.lookAt( vector ); + + _obj.updateMatrix(); + + this.applyMatrix4( _obj.matrix ); + + return this; + + } + + /** + * Center the geometry based on its bounding box. + * + * @return {BufferGeometry} A reference to this instance. + */ + center() { + + this.computeBoundingBox(); + + this.boundingBox.getCenter( _offset ).negate(); + + this.translate( _offset.x, _offset.y, _offset.z ); + + return this; + + } + + /** + * Defines a geometry by creating a `position` attribute based on the given array of points. The array + * can hold 2D or 3D vectors. When using two-dimensional data, the `z` coordinate for all vertices is + * set to `0`. + * + * If the method is used with an existing `position` attribute, the vertex data are overwritten with the + * data from the array. The length of the array must match the vertex count. + * + * @param {Array|Array} points - The points. + * @return {BufferGeometry} A reference to this instance. + */ + setFromPoints( points ) { + + const positionAttribute = this.getAttribute( 'position' ); + + if ( positionAttribute === undefined ) { + + const position = []; + + for ( let i = 0, l = points.length; i < l; i ++ ) { + + const point = points[ i ]; + position.push( point.x, point.y, point.z || 0 ); + + } + + this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) ); + + } else { + + const l = Math.min( points.length, positionAttribute.count ); // make sure data do not exceed buffer size + + for ( let i = 0; i < l; i ++ ) { + + const point = points[ i ]; + positionAttribute.setXYZ( i, point.x, point.y, point.z || 0 ); + + } + + if ( points.length > positionAttribute.count ) { + + warn( 'BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry.' ); + + } + + positionAttribute.needsUpdate = true; + + } + + return this; + + } + + /** + * Computes the bounding box of the geometry, and updates the `boundingBox` member. + * The bounding box is not computed by the engine; it must be computed by your app. + * You may need to recompute the bounding box if the geometry vertices are modified. + */ + computeBoundingBox() { + + if ( this.boundingBox === null ) { + + this.boundingBox = new Box3(); + + } + + const position = this.attributes.position; + const morphAttributesPosition = this.morphAttributes.position; + + if ( position && position.isGLBufferAttribute ) { + + error( 'BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.', this ); + + this.boundingBox.set( + new Vector3( - Infinity, - Infinity, - Infinity ), + new Vector3( + Infinity, + Infinity, + Infinity ) + ); + + return; + + } + + if ( position !== undefined ) { + + this.boundingBox.setFromBufferAttribute( position ); + + // process morph attributes if present + + if ( morphAttributesPosition ) { + + for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) { + + const morphAttribute = morphAttributesPosition[ i ]; + _box$2.setFromBufferAttribute( morphAttribute ); + + if ( this.morphTargetsRelative ) { + + _vector$9.addVectors( this.boundingBox.min, _box$2.min ); + this.boundingBox.expandByPoint( _vector$9 ); + + _vector$9.addVectors( this.boundingBox.max, _box$2.max ); + this.boundingBox.expandByPoint( _vector$9 ); + + } else { + + this.boundingBox.expandByPoint( _box$2.min ); + this.boundingBox.expandByPoint( _box$2.max ); + + } + + } + + } + + } else { + + this.boundingBox.makeEmpty(); + + } + + if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) { + + error( 'BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this ); + + } + + } + + /** + * Computes the bounding sphere of the geometry, and updates the `boundingSphere` member. + * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling. + * You may need to recompute the bounding sphere if the geometry vertices are modified. + */ + computeBoundingSphere() { + + if ( this.boundingSphere === null ) { + + this.boundingSphere = new Sphere(); + + } + + const position = this.attributes.position; + const morphAttributesPosition = this.morphAttributes.position; + + if ( position && position.isGLBufferAttribute ) { + + error( 'BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.', this ); + + this.boundingSphere.set( new Vector3(), Infinity ); + + return; + + } + + if ( position ) { + + // first, find the center of the bounding sphere + + const center = this.boundingSphere.center; + + _box$2.setFromBufferAttribute( position ); + + // process morph attributes if present + + if ( morphAttributesPosition ) { + + for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) { + + const morphAttribute = morphAttributesPosition[ i ]; + _boxMorphTargets.setFromBufferAttribute( morphAttribute ); + + if ( this.morphTargetsRelative ) { + + _vector$9.addVectors( _box$2.min, _boxMorphTargets.min ); + _box$2.expandByPoint( _vector$9 ); + + _vector$9.addVectors( _box$2.max, _boxMorphTargets.max ); + _box$2.expandByPoint( _vector$9 ); + + } else { + + _box$2.expandByPoint( _boxMorphTargets.min ); + _box$2.expandByPoint( _boxMorphTargets.max ); + + } + + } + + } + + _box$2.getCenter( center ); + + // second, try to find a boundingSphere with a radius smaller than the + // boundingSphere of the boundingBox: sqrt(3) smaller in the best case + + let maxRadiusSq = 0; + + for ( let i = 0, il = position.count; i < il; i ++ ) { + + _vector$9.fromBufferAttribute( position, i ); + + maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$9 ) ); + + } + + // process morph attributes if present + + if ( morphAttributesPosition ) { + + for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) { + + const morphAttribute = morphAttributesPosition[ i ]; + const morphTargetsRelative = this.morphTargetsRelative; + + for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) { + + _vector$9.fromBufferAttribute( morphAttribute, j ); + + if ( morphTargetsRelative ) { + + _offset.fromBufferAttribute( position, j ); + _vector$9.add( _offset ); + + } + + maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$9 ) ); + + } + + } + + } + + this.boundingSphere.radius = Math.sqrt( maxRadiusSq ); + + if ( isNaN( this.boundingSphere.radius ) ) { + + error( 'BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this ); + + } + + } + + } + + /** + * Calculates and adds a tangent attribute to this geometry. + * + * The computation is only supported for indexed geometries and if position, normal, and uv attributes + * are defined. When using a tangent space normal map, prefer the MikkTSpace algorithm provided by + * {@link BufferGeometryUtils#computeMikkTSpaceTangents} instead. + */ + computeTangents() { + + const index = this.index; + const attributes = this.attributes; + + // based on http://www.terathon.com/code/tangent.html + // (per vertex tangents) + + if ( index === null || + attributes.position === undefined || + attributes.normal === undefined || + attributes.uv === undefined ) { + + error( 'BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' ); + return; + + } + + const positionAttribute = attributes.position; + const normalAttribute = attributes.normal; + const uvAttribute = attributes.uv; + + let tangentAttribute = this.getAttribute( 'tangent' ); + + if ( tangentAttribute === undefined || tangentAttribute.count !== positionAttribute.count ) { + + tangentAttribute = new BufferAttribute( new Float32Array( 4 * positionAttribute.count ), 4 ); + this.setAttribute( 'tangent', tangentAttribute ); + + } + + const tan1 = [], tan2 = []; + + for ( let i = 0; i < positionAttribute.count; i ++ ) { + + tan1[ i ] = new Vector3(); + tan2[ i ] = new Vector3(); + + } + + const vA = new Vector3(), + vB = new Vector3(), + vC = new Vector3(), + + uvA = new Vector2(), + uvB = new Vector2(), + uvC = new Vector2(), + + sdir = new Vector3(), + tdir = new Vector3(); + + function handleTriangle( a, b, c ) { + + vA.fromBufferAttribute( positionAttribute, a ); + vB.fromBufferAttribute( positionAttribute, b ); + vC.fromBufferAttribute( positionAttribute, c ); + + uvA.fromBufferAttribute( uvAttribute, a ); + uvB.fromBufferAttribute( uvAttribute, b ); + uvC.fromBufferAttribute( uvAttribute, c ); + + vB.sub( vA ); + vC.sub( vA ); + + uvB.sub( uvA ); + uvC.sub( uvA ); + + const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y ); + + // silently ignore degenerate uv triangles having coincident or colinear vertices + + if ( ! isFinite( r ) ) return; + + sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r ); + tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r ); + + tan1[ a ].add( sdir ); + tan1[ b ].add( sdir ); + tan1[ c ].add( sdir ); + + tan2[ a ].add( tdir ); + tan2[ b ].add( tdir ); + tan2[ c ].add( tdir ); + + } + + let groups = this.groups; + + if ( groups.length === 0 ) { + + groups = [ { + start: 0, + count: index.count + } ]; + + } + + for ( let i = 0, il = groups.length; i < il; ++ i ) { + + const group = groups[ i ]; + + const start = group.start; + const count = group.count; + + for ( let j = start, jl = start + count; j < jl; j += 3 ) { + + handleTriangle( + index.getX( j + 0 ), + index.getX( j + 1 ), + index.getX( j + 2 ) + ); + + } + + } + + const tmp = new Vector3(), tmp2 = new Vector3(); + const n = new Vector3(), n2 = new Vector3(); + + function handleVertex( v ) { + + n.fromBufferAttribute( normalAttribute, v ); + n2.copy( n ); + + const t = tan1[ v ]; + + // Gram-Schmidt orthogonalize + + tmp.copy( t ); + tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize(); + + // Calculate handedness + + tmp2.crossVectors( n2, t ); + const test = tmp2.dot( tan2[ v ] ); + const w = ( test < 0.0 ) ? -1 : 1.0; + + tangentAttribute.setXYZW( v, tmp.x, tmp.y, tmp.z, w ); + + } + + for ( let i = 0, il = groups.length; i < il; ++ i ) { + + const group = groups[ i ]; + + const start = group.start; + const count = group.count; + + for ( let j = start, jl = start + count; j < jl; j += 3 ) { + + handleVertex( index.getX( j + 0 ) ); + handleVertex( index.getX( j + 1 ) ); + handleVertex( index.getX( j + 2 ) ); + + } + + } + + this._transformed = true; + + } + + /** + * Computes vertex normals for the given vertex data. For indexed geometries, the method sets + * each vertex normal to be the average of the face normals of the faces that share that vertex. + * For non-indexed geometries, vertices are not shared, and the method sets each vertex normal + * to be the same as the face normal. + */ + computeVertexNormals() { + + const index = this.index; + const positionAttribute = this.getAttribute( 'position' ); + + if ( positionAttribute !== undefined ) { + + let normalAttribute = this.getAttribute( 'normal' ); + + if ( normalAttribute === undefined || normalAttribute.count !== positionAttribute.count ) { + + normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 ); + this.setAttribute( 'normal', normalAttribute ); + + } else { + + // reset existing normals to zero + + for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) { + + normalAttribute.setXYZ( i, 0, 0, 0 ); + + } + + } + + const pA = new Vector3(), pB = new Vector3(), pC = new Vector3(); + const nA = new Vector3(), nB = new Vector3(), nC = new Vector3(); + const cb = new Vector3(), ab = new Vector3(); + + // indexed elements + + if ( index ) { + + for ( let i = 0, il = index.count; i < il; i += 3 ) { + + const vA = index.getX( i + 0 ); + const vB = index.getX( i + 1 ); + const vC = index.getX( i + 2 ); + + pA.fromBufferAttribute( positionAttribute, vA ); + pB.fromBufferAttribute( positionAttribute, vB ); + pC.fromBufferAttribute( positionAttribute, vC ); + + cb.subVectors( pC, pB ); + ab.subVectors( pA, pB ); + cb.cross( ab ); + + nA.fromBufferAttribute( normalAttribute, vA ); + nB.fromBufferAttribute( normalAttribute, vB ); + nC.fromBufferAttribute( normalAttribute, vC ); + + nA.add( cb ); + nB.add( cb ); + nC.add( cb ); + + normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z ); + normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z ); + normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z ); + + } + + } else { + + // non-indexed elements (unconnected triangle soup) + + for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) { + + pA.fromBufferAttribute( positionAttribute, i + 0 ); + pB.fromBufferAttribute( positionAttribute, i + 1 ); + pC.fromBufferAttribute( positionAttribute, i + 2 ); + + cb.subVectors( pC, pB ); + ab.subVectors( pA, pB ); + cb.cross( ab ); + + normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z ); + normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z ); + normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z ); + + } + + } + + this.normalizeNormals(); + + normalAttribute.needsUpdate = true; + + } + + } + + /** + * Ensures every normal vector in a geometry will have a magnitude of `1`. This will + * correct lighting on the geometry surfaces. + */ + normalizeNormals() { + + const normals = this.attributes.normal; + + for ( let i = 0, il = normals.count; i < il; i ++ ) { + + _vector$9.fromBufferAttribute( normals, i ); + + _vector$9.normalize(); + + normals.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z ); + + } + + } + + /** + * Return a new non-index version of this indexed geometry. If the geometry + * is already non-indexed, the method is a NOOP. + * + * @return {BufferGeometry} The non-indexed version of this indexed geometry. + */ + toNonIndexed() { + + function convertBufferAttribute( attribute, indices ) { + + const array = attribute.array; + const itemSize = attribute.itemSize; + const normalized = attribute.normalized; + + const array2 = new array.constructor( indices.length * itemSize ); + + let index = 0, index2 = 0; + + for ( let i = 0, l = indices.length; i < l; i ++ ) { + + if ( attribute.isInterleavedBufferAttribute ) { + + index = indices[ i ] * attribute.data.stride + attribute.offset; + + } else { + + index = indices[ i ] * itemSize; + + } + + for ( let j = 0; j < itemSize; j ++ ) { + + array2[ index2 ++ ] = array[ index ++ ]; + + } + + } + + return new BufferAttribute( array2, itemSize, normalized ); + + } + + // + + if ( this.index === null ) { + + warn( 'BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' ); + return this; + + } + + const geometry2 = new BufferGeometry(); + + const indices = this.index.array; + const attributes = this.attributes; + + // attributes + + for ( const name in attributes ) { + + const attribute = attributes[ name ]; + + const newAttribute = convertBufferAttribute( attribute, indices ); + + geometry2.setAttribute( name, newAttribute ); + + } + + // morph attributes + + const morphAttributes = this.morphAttributes; + + for ( const name in morphAttributes ) { + + const morphArray = []; + const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes + + for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) { + + const attribute = morphAttribute[ i ]; + + const newAttribute = convertBufferAttribute( attribute, indices ); + + morphArray.push( newAttribute ); + + } + + geometry2.morphAttributes[ name ] = morphArray; + + } + + geometry2.morphTargetsRelative = this.morphTargetsRelative; + + // groups + + const groups = this.groups; + + for ( let i = 0, l = groups.length; i < l; i ++ ) { + + const group = groups[ i ]; + geometry2.addGroup( group.start, group.count, group.materialIndex ); + + } + + return geometry2; + + } + + /** + * Serializes the geometry into JSON. + * + * @return {Object} A JSON object representing the serialized geometry. + */ + toJSON() { + + const data = { + metadata: { + version: 4.7, + type: 'BufferGeometry', + generator: 'BufferGeometry.toJSON' + } + }; + + // standard BufferGeometry serialization + + data.uuid = this.uuid; + data.type = ( this.parameters !== undefined && this._transformed === true ) ? 'BufferGeometry' : this.type; + data.name = this.name; + if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData; + + if ( this.parameters !== undefined && this._transformed !== true ) { + + const parameters = this.parameters; + + for ( const key in parameters ) { + + if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ]; + + } + + return data; + + } + + // for simplicity the code assumes attributes are not shared across geometries, see #15811 + + data.data = { attributes: {} }; + + const index = this.index; + + if ( index !== null ) { + + data.data.index = { + type: index.array.constructor.name, + array: Array.prototype.slice.call( index.array ) + }; + + } + + const attributes = this.attributes; + + for ( const key in attributes ) { + + const attribute = attributes[ key ]; + + data.data.attributes[ key ] = attribute.toJSON( data.data ); + + } + + const morphAttributes = {}; + let hasMorphAttributes = false; + + for ( const key in this.morphAttributes ) { + + const attributeArray = this.morphAttributes[ key ]; + + const array = []; + + for ( let i = 0, il = attributeArray.length; i < il; i ++ ) { + + const attribute = attributeArray[ i ]; + + array.push( attribute.toJSON( data.data ) ); + + } + + if ( array.length > 0 ) { + + morphAttributes[ key ] = array; + + hasMorphAttributes = true; + + } + + } + + if ( hasMorphAttributes ) { + + data.data.morphAttributes = morphAttributes; + data.data.morphTargetsRelative = this.morphTargetsRelative; + + } + + const groups = this.groups; + + if ( groups.length > 0 ) { + + data.data.groups = JSON.parse( JSON.stringify( groups ) ); + + } + + const boundingSphere = this.boundingSphere; + + if ( boundingSphere !== null ) { + + data.data.boundingSphere = boundingSphere.toJSON(); + + } + + return data; + + } + + /** + * Returns a new geometry with copied values from this instance. + * + * @return {BufferGeometry} A clone of this instance. + */ + clone() { + + return new this.constructor().copy( this ); + + } + + /** + * Copies the values of the given geometry to this instance. + * + * @param {BufferGeometry} source - The geometry to copy. + * @return {BufferGeometry} A reference to this instance. + */ + copy( source ) { + + // reset + + this.index = null; + this.attributes = {}; + this.morphAttributes = {}; + this.groups = []; + this.boundingBox = null; + this.boundingSphere = null; + + // used for storing cloned, shared data + + const data = {}; + + // name + + this.name = source.name; + + // index + + const index = source.index; + + if ( index !== null ) { + + this.setIndex( index.clone() ); + + } + + // attributes + + const attributes = source.attributes; + + for ( const name in attributes ) { + + const attribute = attributes[ name ]; + this.setAttribute( name, attribute.clone( data ) ); + + } + + // morph attributes + + const morphAttributes = source.morphAttributes; + + for ( const name in morphAttributes ) { + + const array = []; + const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes + + for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) { + + array.push( morphAttribute[ i ].clone( data ) ); + + } + + this.morphAttributes[ name ] = array; + + } + + this.morphTargetsRelative = source.morphTargetsRelative; + + // groups + + const groups = source.groups; + + for ( let i = 0, l = groups.length; i < l; i ++ ) { + + const group = groups[ i ]; + this.addGroup( group.start, group.count, group.materialIndex ); + + } + + // bounding box + + const boundingBox = source.boundingBox; + + if ( boundingBox !== null ) { + + this.boundingBox = boundingBox.clone(); + + } + + // bounding sphere + + const boundingSphere = source.boundingSphere; + + if ( boundingSphere !== null ) { + + this.boundingSphere = boundingSphere.clone(); + + } + + // draw range + + this.drawRange.start = source.drawRange.start; + this.drawRange.count = source.drawRange.count; + + // user data + + this.userData = source.userData; + + // transformed flag + + this._transformed = source._transformed; + + return this; + + } + + /** + * Frees the GPU-related resources allocated by this instance. Call this + * method whenever this instance is no longer used in your app. + * + * @fires BufferGeometry#dispose + */ + dispose() { + + this.dispatchEvent( { type: 'dispose' } ); + + } + +} + +/** + * "Interleaved" means that multiple attributes, possibly of different types, + * (e.g., position, normal, uv, color) are packed into a single array buffer. + * + * An introduction into interleaved arrays can be found here: [Interleaved array basics](https://blog.tojicode.com/2011/05/interleaved-array-basics.html) + */ +class InterleavedBuffer { + + /** + * Constructs a new interleaved buffer. + * + * @param {TypedArray} array - A typed array with a shared buffer storing attribute data. + * @param {number} stride - The number of typed-array elements per vertex. + */ + constructor( array, stride ) { + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isInterleavedBuffer = true; + + /** + * A typed array with a shared buffer storing attribute data. + * + * @type {TypedArray} + */ + this.array = array; + + /** + * The number of typed-array elements per vertex. + * + * @type {number} + */ + this.stride = stride; + + /** + * The total number of elements in the array + * + * @type {number} + * @readonly + */ + this.count = array !== undefined ? array.length / stride : 0; + + /** + * Defines the intended usage pattern of the data store for optimization purposes. + * + * Note: After the initial use of a buffer, its usage cannot be changed. Instead, + * instantiate a new one and set the desired usage before the next render. + * + * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} + * @default StaticDrawUsage + */ + this.usage = StaticDrawUsage; + + /** + * This can be used to only update some components of stored vectors (for example, just the + * component related to color). Use the `addUpdateRange()` function to add ranges to this array. + * + * @type {Array} + */ + this.updateRanges = []; + + /** + * A version number, incremented every time the `needsUpdate` is set to `true`. + * + * @type {number} + */ + this.version = 0; + + /** + * The UUID of the interleaved buffer. + * + * @type {string} + * @readonly + */ + this.uuid = generateUUID(); + + } + + /** + * A callback function that is executed after the renderer has transferred the attribute array + * data to the GPU. + */ + onUploadCallback() {} + + /** + * Flag to indicate that this attribute has changed and should be re-sent to + * the GPU. Set this to `true` when you modify the value of the array. + * + * @type {number} + * @default false + * @param {boolean} value + */ + set needsUpdate( value ) { + + if ( value === true ) this.version ++; + + } + + /** + * Sets the usage of this interleaved buffer. + * + * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set. + * @return {InterleavedBuffer} A reference to this interleaved buffer. + */ + setUsage( value ) { + + this.usage = value; + + return this; + + } + + /** + * Adds a range of data in the data array to be updated on the GPU. + * + * @param {number} start - Position at which to start update. + * @param {number} count - The number of components to update. + */ + addUpdateRange( start, count ) { + + this.updateRanges.push( { start, count } ); + + } + + /** + * Clears the update ranges. + */ + clearUpdateRanges() { + + this.updateRanges.length = 0; + + } + + /** + * Copies the values of the given interleaved buffer to this instance. + * + * @param {InterleavedBuffer} source - The interleaved buffer to copy. + * @return {InterleavedBuffer} A reference to this instance. + */ + copy( source ) { + + this.array = new source.array.constructor( source.array ); + this.count = source.count; + this.stride = source.stride; + this.usage = source.usage; + + return this; + + } + + /** + * Copies a vector from the given interleaved buffer to this one. The start + * and destination position in the attribute buffers are represented by the + * given indices. + * + * @param {number} index1 - The destination index into this interleaved buffer. + * @param {InterleavedBuffer} interleavedBuffer - The interleaved buffer to copy from. + * @param {number} index2 - The source index into the given interleaved buffer. + * @return {InterleavedBuffer} A reference to this instance. + */ + copyAt( index1, interleavedBuffer, index2 ) { + + index1 *= this.stride; + index2 *= interleavedBuffer.stride; + + for ( let i = 0, l = this.stride; i < l; i ++ ) { + + this.array[ index1 + i ] = interleavedBuffer.array[ index2 + i ]; + + } + + return this; + + } + + /** + * Sets the given array data in the interleaved buffer. + * + * @param {(TypedArray|Array)} value - The array data to set. + * @param {number} [offset=0] - The offset in this interleaved buffer's array. + * @return {InterleavedBuffer} A reference to this instance. + */ + set( value, offset = 0 ) { + + this.array.set( value, offset ); + + return this; + + } + + /** + * Returns a new interleaved buffer with copied values from this instance. + * + * @param {Object} [data] - An object with shared array buffers that allows to retain shared structures. + * @return {InterleavedBuffer} A clone of this instance. + */ + clone( data ) { + + if ( data.arrayBuffers === undefined ) { + + data.arrayBuffers = {}; + + } + + if ( this.array.buffer._uuid === undefined ) { + + this.array.buffer._uuid = generateUUID(); + + } + + if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) { + + data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer; + + } + + const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] ); + + const ib = new this.constructor( array, this.stride ); + ib.setUsage( this.usage ); + + return ib; + + } + + /** + * Sets the given callback function that is executed after the Renderer has transferred + * the array data to the GPU. Can be used to perform clean-up operations after + * the upload when data are not needed anymore on the CPU side. + * + * @param {Function} callback - The `onUpload()` callback. + * @return {InterleavedBuffer} A reference to this instance. + */ + onUpload( callback ) { + + this.onUploadCallback = callback; + + return this; + + } + + /** + * Serializes the interleaved buffer into JSON. + * + * @param {Object} [data] - An optional value holding meta information about the serialization. + * @return {Object} A JSON object representing the serialized interleaved buffer. + */ + toJSON( data ) { + + if ( data.arrayBuffers === undefined ) { + + data.arrayBuffers = {}; + + } + + // generate UUID for array buffer if necessary + + if ( this.array.buffer._uuid === undefined ) { + + this.array.buffer._uuid = generateUUID(); + + } + + if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) { + + data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) ); + + } + + // + + const json = { + uuid: this.uuid, + buffer: this.array.buffer._uuid, + type: this.array.constructor.name, + stride: this.stride + }; + + json.usage = this.usage; + + return json; + + } + +} + +const _vector$8 = /*@__PURE__*/ new Vector3(); + +/** + * An alternative version of a buffer attribute with interleaved data. Interleaved + * attributes share a common interleaved data storage ({@link InterleavedBuffer}) and refer with + * different offsets into the buffer. + */ +class InterleavedBufferAttribute { + + /** + * Constructs a new interleaved buffer attribute. + * + * @param {InterleavedBuffer} interleavedBuffer - The buffer holding the interleaved data. + * @param {number} itemSize - The item size. + * @param {number} offset - The attribute offset into the buffer. + * @param {boolean} [normalized=false] - Whether the data are normalized or not. + */ + constructor( interleavedBuffer, itemSize, offset, normalized = false ) { + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isInterleavedBufferAttribute = true; + + /** + * The name of the buffer attribute. + * + * @type {string} + */ + this.name = ''; + + /** + * The buffer holding the interleaved data. + * + * @type {InterleavedBuffer} + */ + this.data = interleavedBuffer; + + /** + * The item size, see {@link BufferAttribute#itemSize}. + * + * @type {number} + */ + this.itemSize = itemSize; + + /** + * The attribute offset into the buffer. + * + * @type {number} + */ + this.offset = offset; + + /** + * Whether the data are normalized or not, see {@link BufferAttribute#normalized} + * + * @type {InterleavedBuffer} + */ + this.normalized = normalized; + + } + + /** + * The item count of this buffer attribute. + * + * @type {number} + * @readonly + */ + get count() { + + return this.data.count; + + } + + /** + * The array holding the interleaved buffer attribute data. + * + * @type {TypedArray} + */ + get array() { + + return this.data.array; + + } + + /** + * Flag to indicate that this attribute has changed and should be re-sent to + * the GPU. Set this to `true` when you modify the value of the array. + * + * @type {number} + * @default false + * @param {boolean} value + */ + set needsUpdate( value ) { + + this.data.needsUpdate = value; + + } + + /** + * Applies the given 4x4 matrix to the given attribute. Only works with + * item size `3`. + * + * @param {Matrix4} m - The matrix to apply. + * @return {InterleavedBufferAttribute} A reference to this instance. + */ + applyMatrix4( m ) { + + for ( let i = 0, l = this.data.count; i < l; i ++ ) { + + _vector$8.fromBufferAttribute( this, i ); + + _vector$8.applyMatrix4( m ); + + this.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z ); + + } + + return this; + + } + + /** + * Applies the given 3x3 normal matrix to the given attribute. Only works with + * item size `3`. + * + * @param {Matrix3} m - The normal matrix to apply. + * @return {InterleavedBufferAttribute} A reference to this instance. + */ + applyNormalMatrix( m ) { + + for ( let i = 0, l = this.count; i < l; i ++ ) { + + _vector$8.fromBufferAttribute( this, i ); + + _vector$8.applyNormalMatrix( m ); + + this.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z ); + + } + + return this; + + } + + /** + * Applies the given 4x4 matrix to the given attribute. Only works with + * item size `3` and with direction vectors. + * + * @param {Matrix4} m - The matrix to apply. + * @return {InterleavedBufferAttribute} A reference to this instance. + */ + transformDirection( m ) { + + for ( let i = 0, l = this.count; i < l; i ++ ) { + + _vector$8.fromBufferAttribute( this, i ); + + _vector$8.transformDirection( m ); + + this.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z ); + + } + + return this; + + } + + /** + * Returns the given component of the vector at the given index. + * + * @param {number} index - The index into the buffer attribute. + * @param {number} component - The component index. + * @return {number} The returned value. + */ + getComponent( index, component ) { + + let value = this.array[ index * this.data.stride + this.offset + component ]; + + if ( this.normalized ) value = denormalize( value, this.array ); + + return value; + + } + + /** + * Sets the given value to the given component of the vector at the given index. + * + * @param {number} index - The index into the buffer attribute. + * @param {number} component - The component index. + * @param {number} value - The value to set. + * @return {InterleavedBufferAttribute} A reference to this instance. + */ + setComponent( index, component, value ) { + + if ( this.normalized ) value = normalize( value, this.array ); + + this.data.array[ index * this.data.stride + this.offset + component ] = value; + + return this; + + } + + /** + * Sets the x component of the vector at the given index. + * + * @param {number} index - The index into the buffer attribute. + * @param {number} x - The value to set. + * @return {InterleavedBufferAttribute} A reference to this instance. + */ + setX( index, x ) { + + if ( this.normalized ) x = normalize( x, this.array ); + + this.data.array[ index * this.data.stride + this.offset ] = x; + + return this; + + } + + /** + * Sets the y component of the vector at the given index. + * + * @param {number} index - The index into the buffer attribute. + * @param {number} y - The value to set. + * @return {InterleavedBufferAttribute} A reference to this instance. + */ + setY( index, y ) { + + if ( this.normalized ) y = normalize( y, this.array ); + + this.data.array[ index * this.data.stride + this.offset + 1 ] = y; + + return this; + + } + + /** + * Sets the z component of the vector at the given index. + * + * @param {number} index - The index into the buffer attribute. + * @param {number} z - The value to set. + * @return {InterleavedBufferAttribute} A reference to this instance. + */ + setZ( index, z ) { + + if ( this.normalized ) z = normalize( z, this.array ); + + this.data.array[ index * this.data.stride + this.offset + 2 ] = z; + + return this; + + } + + /** + * Sets the w component of the vector at the given index. + * + * @param {number} index - The index into the buffer attribute. + * @param {number} w - The value to set. + * @return {InterleavedBufferAttribute} A reference to this instance. + */ + setW( index, w ) { + + if ( this.normalized ) w = normalize( w, this.array ); + + this.data.array[ index * this.data.stride + this.offset + 3 ] = w; + + return this; + + } + + /** + * Returns the x component of the vector at the given index. + * + * @param {number} index - The index into the buffer attribute. + * @return {number} The x component. + */ + getX( index ) { + + let x = this.data.array[ index * this.data.stride + this.offset ]; + + if ( this.normalized ) x = denormalize( x, this.array ); + + return x; + + } + + /** + * Returns the y component of the vector at the given index. + * + * @param {number} index - The index into the buffer attribute. + * @return {number} The y component. + */ + getY( index ) { + + let y = this.data.array[ index * this.data.stride + this.offset + 1 ]; + + if ( this.normalized ) y = denormalize( y, this.array ); + + return y; + + } + + /** + * Returns the z component of the vector at the given index. + * + * @param {number} index - The index into the buffer attribute. + * @return {number} The z component. + */ + getZ( index ) { + + let z = this.data.array[ index * this.data.stride + this.offset + 2 ]; + + if ( this.normalized ) z = denormalize( z, this.array ); + + return z; + + } + + /** + * Returns the w component of the vector at the given index. + * + * @param {number} index - The index into the buffer attribute. + * @return {number} The w component. + */ + getW( index ) { + + let w = this.data.array[ index * this.data.stride + this.offset + 3 ]; + + if ( this.normalized ) w = denormalize( w, this.array ); + + return w; + + } + + /** + * Sets the x and y component of the vector at the given index. + * + * @param {number} index - The index into the buffer attribute. + * @param {number} x - The value for the x component to set. + * @param {number} y - The value for the y component to set. + * @return {InterleavedBufferAttribute} A reference to this instance. + */ + setXY( index, x, y ) { + + index = index * this.data.stride + this.offset; + + if ( this.normalized ) { + + x = normalize( x, this.array ); + y = normalize( y, this.array ); + + } + + this.data.array[ index + 0 ] = x; + this.data.array[ index + 1 ] = y; + + return this; + + } + + /** + * Sets the x, y and z component of the vector at the given index. + * + * @param {number} index - The index into the buffer attribute. + * @param {number} x - The value for the x component to set. + * @param {number} y - The value for the y component to set. + * @param {number} z - The value for the z component to set. + * @return {InterleavedBufferAttribute} A reference to this instance. + */ + setXYZ( index, x, y, z ) { + + index = index * this.data.stride + this.offset; + + if ( this.normalized ) { + + x = normalize( x, this.array ); + y = normalize( y, this.array ); + z = normalize( z, this.array ); + + } + + this.data.array[ index + 0 ] = x; + this.data.array[ index + 1 ] = y; + this.data.array[ index + 2 ] = z; + + return this; + + } + + /** + * Sets the x, y, z and w component of the vector at the given index. + * + * @param {number} index - The index into the buffer attribute. + * @param {number} x - The value for the x component to set. + * @param {number} y - The value for the y component to set. + * @param {number} z - The value for the z component to set. + * @param {number} w - The value for the w component to set. + * @return {InterleavedBufferAttribute} A reference to this instance. + */ + setXYZW( index, x, y, z, w ) { + + index = index * this.data.stride + this.offset; + + if ( this.normalized ) { + + x = normalize( x, this.array ); + y = normalize( y, this.array ); + z = normalize( z, this.array ); + w = normalize( w, this.array ); + + } + + this.data.array[ index + 0 ] = x; + this.data.array[ index + 1 ] = y; + this.data.array[ index + 2 ] = z; + this.data.array[ index + 3 ] = w; + + return this; + + } + + /** + * Returns a new buffer attribute with copied values from this instance. + * + * If no parameter is provided, cloning an interleaved buffer attribute will de-interleave buffer data. + * + * @param {Object} [data] - An object with interleaved buffers that allows to retain the interleaved property. + * @return {BufferAttribute|InterleavedBufferAttribute} A clone of this instance. + */ + clone( data ) { + + if ( data === undefined ) { + + log( 'InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' ); + + const array = []; + + for ( let i = 0; i < this.count; i ++ ) { + + const index = i * this.data.stride + this.offset; + + for ( let j = 0; j < this.itemSize; j ++ ) { + + array.push( this.data.array[ index + j ] ); + + } + + } + + return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized ); + + } else { + + if ( data.interleavedBuffers === undefined ) { + + data.interleavedBuffers = {}; + + } + + if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) { + + data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data ); + + } + + return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized ); + + } + + } + + /** + * Serializes the buffer attribute into JSON. + * + * If no parameter is provided, cloning an interleaved buffer attribute will de-interleave buffer data. + * + * @param {Object} [data] - An optional value holding meta information about the serialization. + * @return {Object} A JSON object representing the serialized buffer attribute. + */ + toJSON( data ) { + + if ( data === undefined ) { + + log( 'InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' ); + + const array = []; + + for ( let i = 0; i < this.count; i ++ ) { + + const index = i * this.data.stride + this.offset; + + for ( let j = 0; j < this.itemSize; j ++ ) { + + array.push( this.data.array[ index + j ] ); + + } + + } + + // de-interleave data and save it as an ordinary buffer attribute for now + + return { + itemSize: this.itemSize, + type: this.array.constructor.name, + array: array, + normalized: this.normalized + }; + + } else { + + // save as true interleaved attribute + + if ( data.interleavedBuffers === undefined ) { + + data.interleavedBuffers = {}; + + } + + if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) { + + data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data ); + + } + + return { + isInterleavedBufferAttribute: true, + itemSize: this.itemSize, + data: this.data.uuid, + offset: this.offset, + normalized: this.normalized + }; + + } + + } + +} + +const _vector1 = /*@__PURE__*/ new Vector3(); +const _vector2 = /*@__PURE__*/ new Vector3(); +const _normalMatrix = /*@__PURE__*/ new Matrix3(); + +/** + * A two dimensional surface that extends infinitely in 3D space, represented + * in [Hessian normal form](https://mathworld.wolfram.com/HessianNormalForm.html) + * by a unit length normal vector and a constant. + */ +class Plane { + + /** + * Constructs a new plane. + * + * @param {Vector3} [normal=(1,0,0)] - A unit length vector defining the normal of the plane. + * @param {number} [constant=0] - The signed distance from the origin to the plane. + */ + constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) { + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isPlane = true; + + /** + * A unit length vector defining the normal of the plane. + * + * @type {Vector3} + */ + this.normal = normal; + + /** + * The signed distance from the origin to the plane. + * + * @type {number} + * @default 0 + */ + this.constant = constant; + + } + + /** + * Sets the plane components by copying the given values. + * + * @param {Vector3} normal - The normal. + * @param {number} constant - The constant. + * @return {Plane} A reference to this plane. + */ + set( normal, constant ) { + + this.normal.copy( normal ); + this.constant = constant; + + return this; + + } + + /** + * Sets the plane components by defining `x`, `y`, `z` as the + * plane normal and `w` as the constant. + * + * @param {number} x - The value for the normal's x component. + * @param {number} y - The value for the normal's y component. + * @param {number} z - The value for the normal's z component. + * @param {number} w - The constant value. + * @return {Plane} A reference to this plane. + */ + setComponents( x, y, z, w ) { + + this.normal.set( x, y, z ); + this.constant = w; + + return this; + + } + + /** + * Sets the plane from the given normal and coplanar point (that is a point + * that lies onto the plane). + * + * @param {Vector3} normal - The normal. + * @param {Vector3} point - A coplanar point. + * @return {Plane} A reference to this plane. + */ + setFromNormalAndCoplanarPoint( normal, point ) { + + this.normal.copy( normal ); + this.constant = - point.dot( this.normal ); + + return this; + + } + + /** + * Sets the plane from three coplanar points. The winding order is + * assumed to be counter-clockwise, and determines the direction of + * the plane normal. + * + * @param {Vector3} a - The first coplanar point. + * @param {Vector3} b - The second coplanar point. + * @param {Vector3} c - The third coplanar point. + * @return {Plane} A reference to this plane. + */ + setFromCoplanarPoints( a, b, c ) { + + const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize(); + + // Q: should an error be thrown if normal is zero (e.g. degenerate plane)? + + this.setFromNormalAndCoplanarPoint( normal, a ); + + return this; + + } + + /** + * Copies the values of the given plane to this instance. + * + * @param {Plane} plane - The plane to copy. + * @return {Plane} A reference to this plane. + */ + copy( plane ) { + + this.normal.copy( plane.normal ); + this.constant = plane.constant; + + return this; + + } + + /** + * Normalizes the plane normal and adjusts the constant accordingly. + * + * @return {Plane} A reference to this plane. + */ + normalize() { + + // Note: will lead to a divide by zero if the plane is invalid. + + const inverseNormalLength = 1.0 / this.normal.length(); + this.normal.multiplyScalar( inverseNormalLength ); + this.constant *= inverseNormalLength; + + return this; + + } + + /** + * Negates both the plane normal and the constant. + * + * @return {Plane} A reference to this plane. + */ + negate() { + + this.constant *= -1; + this.normal.negate(); + + return this; + + } + + /** + * Returns the signed distance from the given point to this plane. + * + * @param {Vector3} point - The point to compute the distance for. + * @return {number} The signed distance. + */ + distanceToPoint( point ) { + + return this.normal.dot( point ) + this.constant; + + } + + /** + * Returns the signed distance from the given sphere to this plane. + * + * @param {Sphere} sphere - The sphere to compute the distance for. + * @return {number} The signed distance. + */ + distanceToSphere( sphere ) { + + return this.distanceToPoint( sphere.center ) - sphere.radius; + + } + + /** + * Projects a the given point onto the plane. + * + * @param {Vector3} point - The point to project. + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {Vector3} The projected point on the plane. + */ + projectPoint( point, target ) { + + return target.copy( point ).addScaledVector( this.normal, - this.distanceToPoint( point ) ); + + } + + /** + * Returns the intersection point of the passed line and the plane. Returns + * `null` if the line does not intersect. Returns the line's starting point if + * the line is coplanar with the plane. + * + * @param {Line3} line - The line to compute the intersection for. + * @param {Vector3} target - The target vector that is used to store the method's result. + * @param {boolean} [clampToLine=true] - Whether to clamp the intersection to the line segment. + * @return {?Vector3} The intersection point. Returns `null` if no intersection is detected. + */ + intersectLine( line, target, clampToLine = true ) { + + const direction = line.delta( _vector1 ); + + const denominator = this.normal.dot( direction ); + + if ( denominator === 0 ) { + + // line is coplanar, return origin + if ( this.distanceToPoint( line.start ) === 0 ) { + + return target.copy( line.start ); + + } + + // Unsure if this is the correct method to handle this case. + return null; + + } + + const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator; + + if ( ( clampToLine === true ) && ( t < 0 || t > 1 ) ) { + + return null; + + } + + return target.copy( line.start ).addScaledVector( direction, t ); + + } + + /** + * Returns `true` if the given line segment intersects with (passes through) the plane. + * + * @param {Line3} line - The line to test. + * @return {boolean} Whether the given line segment intersects with the plane or not. + */ + intersectsLine( line ) { + + // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it. + + const startSign = this.distanceToPoint( line.start ); + const endSign = this.distanceToPoint( line.end ); + + return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 ); + + } + + /** + * Returns `true` if the given bounding box intersects with the plane. + * + * @param {Box3} box - The bounding box to test. + * @return {boolean} Whether the given bounding box intersects with the plane or not. + */ + intersectsBox( box ) { + + return box.intersectsPlane( this ); + + } + + /** + * Returns `true` if the given bounding sphere intersects with the plane. + * + * @param {Sphere} sphere - The bounding sphere to test. + * @return {boolean} Whether the given bounding sphere intersects with the plane or not. + */ + intersectsSphere( sphere ) { + + return sphere.intersectsPlane( this ); + + } + + /** + * Returns a coplanar vector to the plane, by calculating the + * projection of the normal at the origin onto the plane. + * + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {Vector3} The coplanar point. + */ + coplanarPoint( target ) { + + return target.copy( this.normal ).multiplyScalar( - this.constant ); + + } + + /** + * Apply a 4x4 matrix to the plane. The matrix must be an affine, homogeneous transform. + * + * The optional normal matrix can be pre-computed like so: + * ```js + * const optionalNormalMatrix = new THREE.Matrix3().getNormalMatrix( matrix ); + * ``` + * + * @param {Matrix4} matrix - The transformation matrix. + * @param {Matrix4} [optionalNormalMatrix] - A pre-computed normal matrix. + * @return {Plane} A reference to this plane. + */ + applyMatrix4( matrix, optionalNormalMatrix ) { + + const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix ); + + const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix ); + + const normal = this.normal.applyMatrix3( normalMatrix ).normalize(); + + this.constant = - referencePoint.dot( normal ); + + return this; + + } + + /** + * Translates the plane by the distance defined by the given offset vector. + * Note that this only affects the plane constant and will not affect the normal vector. + * + * @param {Vector3} offset - The offset vector. + * @return {Plane} A reference to this plane. + */ + translate( offset ) { + + this.constant -= offset.dot( this.normal ); + + return this; + + } + + /** + * Returns `true` if this plane is equal with the given one. + * + * @param {Plane} plane - The plane to test for equality. + * @return {boolean} Whether this plane is equal with the given one. + */ + equals( plane ) { + + return plane.normal.equals( this.normal ) && ( plane.constant === this.constant ); + + } + + /** + * Returns a new plane with copied values from this instance. + * + * @return {Plane} A clone of this instance. + */ + clone() { + + return new this.constructor().copy( this ); + + } + + /** + * Returns a serialized structure of the plane. + * + * @return {Object} Serialized structure with fields representing the object state. + */ + toJSON() { + + return { + normal: this.normal.toArray(), + constant: this.constant + }; + + } + + /** + * Sets the plane properties from the given JSON. + * + * @param {Object} json - The serialized json to set the plane from. + * @return {Plane} A reference to this plane. + */ + fromJSON( json ) { + + this.normal.fromArray( json.normal ); + this.constant = json.constant; + + return this; + + } + +} + +let _materialId = 0; + +/** + * Abstract base class for materials. + * + * Materials define the appearance of renderable 3D objects. + * + * @abstract + * @augments EventDispatcher + */ +class Material extends EventDispatcher { + + /** + * Constructs a new material. + */ + constructor() { + + super(); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isMaterial = true; + + /** + * The ID of the material. + * + * @name Material#id + * @type {number} + * @readonly + */ + Object.defineProperty( this, 'id', { value: _materialId ++ } ); + + /** + * The UUID of the material. + * + * @type {string} + * @readonly + */ + this.uuid = generateUUID(); + + /** + * The name of the material. + * + * @type {string} + */ + this.name = ''; + + /** + * The type property is used for detecting the object type + * in context of serialization/deserialization. + * + * @type {string} + * @readonly + */ + this.type = 'Material'; + + /** + * Defines the blending type of the material. + * + * It must be set to `CustomBlending` if custom blending properties like + * {@link Material#blendSrc}, {@link Material#blendDst} or {@link Material#blendEquation} + * should have any effect. + * + * @type {(NoBlending|NormalBlending|AdditiveBlending|SubtractiveBlending|MultiplyBlending|CustomBlending)} + * @default NormalBlending + */ + this.blending = NormalBlending; + + /** + * Defines which side of faces will be rendered - front, back or both. + * + * @type {(FrontSide|BackSide|DoubleSide)} + * @default FrontSide + */ + this.side = FrontSide; + + /** + * If set to `true`, vertex colors should be used. + * + * The engine supports RGB and RGBA vertex colors depending on whether a three (RGB) or + * four (RGBA) component color buffer attribute is used. + * + * @type {boolean} + * @default false + */ + this.vertexColors = false; + + /** + * Defines how transparent the material is. + * A value of `0.0` indicates fully transparent, `1.0` is fully opaque. + * + * If the {@link Material#transparent} is not set to `true`, + * the material will remain fully opaque and this value will only affect its color. + * + * @type {number} + * @default 1 + */ + this.opacity = 1; + + /** + * Defines whether this material is transparent. This has an effect on + * rendering as transparent objects need special treatment and are rendered + * after non-transparent objects. + * + * When set to true, the extent to which the material is transparent is + * controlled by {@link Material#opacity}. + * + * @type {boolean} + * @default false + */ + this.transparent = false; + + /** + * Enables alpha hashed transparency, an alternative to {@link Material#transparent} or + * {@link Material#alphaTest}. The material will not be rendered if opacity is lower than + * a random threshold. Randomization introduces some grain or noise, but approximates alpha + * blending without the associated problems of sorting. Using TAA can reduce the resulting noise. + * + * @type {boolean} + * @default false + */ + this.alphaHash = false; + + /** + * Defines the blending source factor. + * + * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)} + * @default SrcAlphaFactor + */ + this.blendSrc = SrcAlphaFactor; + + /** + * Defines the blending destination factor. + * + * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)} + * @default OneMinusSrcAlphaFactor + */ + this.blendDst = OneMinusSrcAlphaFactor; + + /** + * Defines the blending equation. + * + * @type {(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)} + * @default AddEquation + */ + this.blendEquation = AddEquation; + + /** + * Defines the blending source alpha factor. + * + * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)} + * @default null + */ + this.blendSrcAlpha = null; + + /** + * Defines the blending destination alpha factor. + * + * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)} + * @default null + */ + this.blendDstAlpha = null; + + /** + * Defines the blending equation of the alpha channel. + * + * @type {?(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)} + * @default null + */ + this.blendEquationAlpha = null; + + /** + * Represents the RGB values of the constant blend color. + * + * This property has only an effect when using custom blending with `ConstantColor` or `OneMinusConstantColor`. + * + * @type {Color} + * @default (0,0,0) + */ + this.blendColor = new Color( 0, 0, 0 ); + + /** + * Represents the alpha value of the constant blend color. + * + * This property has only an effect when using custom blending with `ConstantAlpha` or `OneMinusConstantAlpha`. + * + * @type {number} + * @default 0 + */ + this.blendAlpha = 0; + + /** + * Defines the depth function. + * + * @type {(NeverDepth|AlwaysDepth|LessDepth|LessEqualDepth|EqualDepth|GreaterEqualDepth|GreaterDepth|NotEqualDepth)} + * @default LessEqualDepth + */ + this.depthFunc = LessEqualDepth; + + /** + * Whether to have depth test enabled when rendering this material. + * When the depth test is disabled, the depth write will also be implicitly disabled. + * + * @type {boolean} + * @default true + */ + this.depthTest = true; + + /** + * Whether rendering this material has any effect on the depth buffer. + * + * When drawing 2D overlays it can be useful to disable the depth writing in + * order to layer several things together without creating z-index artifacts. + * + * @type {boolean} + * @default true + */ + this.depthWrite = true; + + /** + * The bit mask to use when writing to the stencil buffer. + * + * @type {number} + * @default 0xff + */ + this.stencilWriteMask = 0xff; + + /** + * The stencil comparison function to use. + * + * @type {NeverStencilFunc|LessStencilFunc|EqualStencilFunc|LessEqualStencilFunc|GreaterStencilFunc|NotEqualStencilFunc|GreaterEqualStencilFunc|AlwaysStencilFunc} + * @default AlwaysStencilFunc + */ + this.stencilFunc = AlwaysStencilFunc; + + /** + * The value to use when performing stencil comparisons or stencil operations. + * + * @type {number} + * @default 0 + */ + this.stencilRef = 0; + + /** + * The bit mask to use when comparing against the stencil buffer. + * + * @type {number} + * @default 0xff + */ + this.stencilFuncMask = 0xff; + + /** + * Which stencil operation to perform when the comparison function returns `false`. + * + * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp} + * @default KeepStencilOp + */ + this.stencilFail = KeepStencilOp; + + /** + * Which stencil operation to perform when the comparison function returns + * `true` but the depth test fails. + * + * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp} + * @default KeepStencilOp + */ + this.stencilZFail = KeepStencilOp; + + /** + * Which stencil operation to perform when the comparison function returns + * `true` and the depth test passes. + * + * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp} + * @default KeepStencilOp + */ + this.stencilZPass = KeepStencilOp; + + /** + * Whether stencil operations are performed against the stencil buffer. In + * order to perform writes or comparisons against the stencil buffer this + * value must be `true`. + * + * @type {boolean} + * @default false + */ + this.stencilWrite = false; + + /** + * User-defined clipping planes specified as THREE.Plane objects in world + * space. These planes apply to the objects this material is attached to. + * Points in space whose signed distance to the plane is negative are clipped + * (not rendered). This requires {@link WebGLRenderer#localClippingEnabled} to + * be `true`. + * + * @type {?Array} + * @default null + */ + this.clippingPlanes = null; + + /** + * Changes the behavior of clipping planes so that only their intersection is + * clipped, rather than their union. + * + * @type {boolean} + * @default false + */ + this.clipIntersection = false; + + /** + * Defines whether to clip shadows according to the clipping planes specified + * on this material. + * + * @type {boolean} + * @default false + */ + this.clipShadows = false; + + /** + * Defines which side of faces cast shadows. If `null`, the side casting shadows + * is determined as follows: + * + * - When {@link Material#side} is set to `FrontSide`, the back side cast shadows. + * - When {@link Material#side} is set to `BackSide`, the front side cast shadows. + * - When {@link Material#side} is set to `DoubleSide`, both sides cast shadows. + * + * @type {?(FrontSide|BackSide|DoubleSide)} + * @default null + */ + this.shadowSide = null; + + /** + * Whether to render the material's color. + * + * This can be used in conjunction with {@link Object3D#renderOder} to create invisible + * objects that occlude other objects. + * + * @type {boolean} + * @default true + */ + this.colorWrite = true; + + /** + * Override the renderer's default precision for this material. + * + * @type {?('highp'|'mediump'|'lowp')} + * @default null + */ + this.precision = null; + + /** + * Whether to use polygon offset or not. When enabled, each fragment's depth value will + * be offset after it is interpolated from the depth values of the appropriate vertices. + * The offset is added before the depth test is performed and before the value is written + * into the depth buffer. + * + * Can be useful for rendering hidden-line images, for applying decals to surfaces, and for + * rendering solids with highlighted edges. + * + * @type {boolean} + * @default false + */ + this.polygonOffset = false; + + /** + * Specifies a scale factor that is used to create a variable depth offset for each polygon. + * + * @type {number} + * @default 0 + */ + this.polygonOffsetFactor = 0; + + /** + * Is multiplied by an implementation-specific value to create a constant depth offset. + * + * @type {number} + * @default 0 + */ + this.polygonOffsetUnits = 0; + + /** + * Whether to apply dithering to the color to remove the appearance of banding. + * + * @type {boolean} + * @default false + */ + this.dithering = false; + + /** + * Whether alpha to coverage should be enabled or not. Can only be used with MSAA-enabled contexts + * (meaning when the renderer was created with *antialias* parameter set to `true`). Enabling this + * will smooth aliasing on clip plane edges and alphaTest-clipped edges. + * + * @type {boolean} + * @default false + */ + this.alphaToCoverage = false; + + /** + * Whether to premultiply the alpha (transparency) value. + * + * @type {boolean} + * @default false + */ + this.premultipliedAlpha = false; + + /** + * Whether double-sided, transparent objects should be rendered with a single pass or not. + * + * The engine renders double-sided, transparent objects with two draw calls (back faces first, + * then front faces) to mitigate transparency artifacts. There are scenarios however where this + * approach produces no quality gains but still doubles draw calls e.g. when rendering flat + * vegetation like grass sprites. In these cases, set the `forceSinglePass` flag to `true` to + * disable the two pass rendering to avoid performance issues. + * + * @type {boolean} + * @default false + */ + this.forceSinglePass = false; + + /** + * Whether it's possible to override the material with {@link Scene#overrideMaterial} or not. + * + * @type {boolean} + * @default true + */ + this.allowOverride = true; + + /** + * Defines whether 3D objects using this material are visible. + * + * @type {boolean} + * @default true + */ + this.visible = true; + + /** + * Defines whether this material is tone mapped according to the renderer's tone mapping setting. + * + * It is ignored when rendering to a render target or using post processing or when using + * `WebGPURenderer`. In all these cases, all materials are honored by tone mapping. + * + * @type {boolean} + * @default true + */ + this.toneMapped = true; + + /** + * An object that can be used to store custom data about the Material. It + * should not hold references to functions as these will not be cloned. + * + * @type {Object} + */ + this.userData = {}; + + /** + * This starts at `0` and counts how many times {@link Material#needsUpdate} is set to `true`. + * + * @type {number} + * @readonly + * @default 0 + */ + this.version = 0; + + this._alphaTest = 0; + + } + + /** + * Sets the alpha value to be used when running an alpha test. The material + * will not be rendered if the opacity is lower than this value. + * + * @type {number} + * @readonly + * @default 0 + */ + get alphaTest() { + + return this._alphaTest; + + } + + set alphaTest( value ) { + + if ( this._alphaTest > 0 !== value > 0 ) { + + this.version ++; + + } + + this._alphaTest = value; + + } + + /** + * An optional callback that is executed immediately before the material is used to render a 3D object. + * + * This method can only be used when rendering with {@link WebGLRenderer}. + * + * @param {WebGLRenderer} renderer - The renderer. + * @param {Scene} scene - The scene. + * @param {Camera} camera - The camera that is used to render the scene. + * @param {BufferGeometry} geometry - The 3D object's geometry. + * @param {Object3D} object - The 3D object. + * @param {Object} group - The geometry group data. + */ + onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {} + + /** + * An optional callback that is executed immediately before the shader + * program is compiled. This function is called with the shader source code + * as a parameter. Useful for the modification of built-in materials. + * + * This method can only be used when rendering with {@link WebGLRenderer}. The + * recommended approach when customizing materials is to use `WebGPURenderer` with the new + * Node Material system and [TSL](https://github.com/mrdoob/three.js/wiki/Three.js-Shading-Language). + * + * @param {{vertexShader:string,fragmentShader:string,uniforms:Object}} shaderobject - The object holds the uniforms and the vertex and fragment shader source. + * @param {WebGLRenderer} renderer - A reference to the renderer. + */ + onBeforeCompile( /* shaderobject, renderer */ ) {} + + /** + * In case {@link Material#onBeforeCompile} is used, this callback can be used to identify + * values of settings used in `onBeforeCompile()`, so three.js can reuse a cached + * shader or recompile the shader for this material as needed. + * + * This method can only be used when rendering with {@link WebGLRenderer}. + * + * @return {string} The custom program cache key. + */ + customProgramCacheKey() { + + return this.onBeforeCompile.toString(); + + } + + /** + * This method can be used to set default values from parameter objects. + * It is a generic implementation so it can be used with different types + * of materials. + * + * @param {Object} [values] - The material values to set. + */ + setValues( values ) { + + if ( values === undefined ) return; + + for ( const key in values ) { + + const newValue = values[ key ]; + + if ( newValue === undefined ) { + + warn( `Material: parameter '${ key }' has value of undefined.` ); + continue; + + } + + const currentValue = this[ key ]; + + if ( currentValue === undefined ) { + + warn( `Material: '${ key }' is not a property of THREE.${ this.type }.` ); + continue; + + } + + if ( currentValue && currentValue.isColor ) { + + currentValue.set( newValue ); + + } else if ( + ( ( currentValue && currentValue.isVector2 ) && ( newValue && newValue.isVector2 ) ) || + ( ( currentValue && currentValue.isEuler ) && ( newValue && newValue.isEuler ) ) || + ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) + ) { + + currentValue.copy( newValue ); + + } else { + + this[ key ] = newValue; + + } + + } + + } + + /** + * Serializes the material into JSON. + * + * @param {?(Object|string)} meta - An optional value holding meta information about the serialization. + * @return {Object} A JSON object representing the serialized material. + * @see {@link ObjectLoader#parse} + */ + toJSON( meta ) { + + const isRootObject = ( meta === undefined || typeof meta === 'string' ); + + if ( isRootObject ) { + + meta = { + textures: {}, + images: {} + }; + + } + + const data = { + metadata: { + version: 4.7, + type: 'Material', + generator: 'Material.toJSON' + } + }; + + // standard Material serialization + + data.uuid = this.uuid; + data.type = this.type; + + data.blending = this.blending; + data.side = this.side; + data.shadowSide = this.shadowSide; + data.vertexColors = this.vertexColors; + + data.opacity = this.opacity; + data.transparent = this.transparent; + + data.blendSrc = this.blendSrc; + data.blendDst = this.blendDst; + data.blendEquation = this.blendEquation; + data.blendSrcAlpha = this.blendSrcAlpha; + data.blendDstAlpha = this.blendDstAlpha; + data.blendEquationAlpha = this.blendEquationAlpha; + data.blendColor = this.blendColor.getHex(); + data.blendAlpha = this.blendAlpha; + + data.depthFunc = this.depthFunc; + data.depthTest = this.depthTest; + data.depthWrite = this.depthWrite; + data.colorWrite = this.colorWrite; + + data.clipIntersection = this.clipIntersection; + data.clipShadows = this.clipShadows; + + data.stencilWriteMask = this.stencilWriteMask; + data.stencilFunc = this.stencilFunc; + data.stencilRef = this.stencilRef; + data.stencilFuncMask = this.stencilFuncMask; + data.stencilFail = this.stencilFail; + data.stencilZFail = this.stencilZFail; + data.stencilZPass = this.stencilZPass; + data.stencilWrite = this.stencilWrite; + + data.polygonOffset = this.polygonOffset; + data.polygonOffsetFactor = this.polygonOffsetFactor; + data.polygonOffsetUnits = this.polygonOffsetUnits; + + data.dithering = this.dithering; + + data.alphaTest = this.alphaTest; + data.alphaHash = this.alphaHash; + data.alphaToCoverage = this.alphaToCoverage; + data.premultipliedAlpha = this.premultipliedAlpha; + data.forceSinglePass = this.forceSinglePass; + data.allowOverride = this.allowOverride; + + data.visible = this.visible; + data.toneMapped = this.toneMapped; + + data.name = this.name; + + if ( this.color && this.color.isColor ) data.color = this.color.getHex(); + + if ( this.roughness !== undefined ) data.roughness = this.roughness; + if ( this.metalness !== undefined ) data.metalness = this.metalness; + + if ( this.sheen !== undefined ) data.sheen = this.sheen; + if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex(); + if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness; + if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex(); + if ( this.emissiveIntensity !== undefined ) data.emissiveIntensity = this.emissiveIntensity; + + if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex(); + if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity; + if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex(); + if ( this.shininess !== undefined ) data.shininess = this.shininess; + if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat; + if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness; + + if ( this.clearcoatMap && this.clearcoatMap.isTexture ) { + + data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid; + + } + + if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) { + + data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid; + + } + + if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) { + + data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid; + data.clearcoatNormalScale = this.clearcoatNormalScale.toArray(); + + } + + if ( this.sheenColorMap && this.sheenColorMap.isTexture ) { + + data.sheenColorMap = this.sheenColorMap.toJSON( meta ).uuid; + + } + + if ( this.sheenRoughnessMap && this.sheenRoughnessMap.isTexture ) { + + data.sheenRoughnessMap = this.sheenRoughnessMap.toJSON( meta ).uuid; + + } + + if ( this.dispersion !== undefined ) data.dispersion = this.dispersion; + if ( this.retroreflectivity !== undefined ) data.retroreflectivity = this.retroreflectivity; + + if ( this.iridescence !== undefined ) data.iridescence = this.iridescence; + if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR; + if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange; + + if ( this.iridescenceMap && this.iridescenceMap.isTexture ) { + + data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid; + + } + + if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) { + + data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid; + + } + + if ( this.anisotropy !== undefined ) data.anisotropy = this.anisotropy; + if ( this.anisotropyRotation !== undefined ) data.anisotropyRotation = this.anisotropyRotation; + + if ( this.anisotropyMap && this.anisotropyMap.isTexture ) { + + data.anisotropyMap = this.anisotropyMap.toJSON( meta ).uuid; + + } + + if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid; + if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid; + if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid; + + if ( this.lightMap && this.lightMap.isTexture ) { + + data.lightMap = this.lightMap.toJSON( meta ).uuid; + data.lightMapIntensity = this.lightMapIntensity; + + } + + if ( this.aoMap && this.aoMap.isTexture ) { + + data.aoMap = this.aoMap.toJSON( meta ).uuid; + data.aoMapIntensity = this.aoMapIntensity; + + } + + if ( this.bumpMap && this.bumpMap.isTexture ) { + + data.bumpMap = this.bumpMap.toJSON( meta ).uuid; + data.bumpScale = this.bumpScale; + + } + + if ( this.normalMap && this.normalMap.isTexture ) { + + data.normalMap = this.normalMap.toJSON( meta ).uuid; + data.normalMapType = this.normalMapType; + data.normalScale = this.normalScale.toArray(); + + } + + if ( this.displacementMap && this.displacementMap.isTexture ) { + + data.displacementMap = this.displacementMap.toJSON( meta ).uuid; + data.displacementScale = this.displacementScale; + data.displacementBias = this.displacementBias; + + } + + if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid; + if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid; + + if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid; + if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid; + if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid; + if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid; + + if ( this.envMap && this.envMap.isTexture ) { + + data.envMap = this.envMap.toJSON( meta ).uuid; + + if ( this.combine !== undefined ) data.combine = this.combine; + + } + + if ( this.envMapRotation !== undefined ) data.envMapRotation = this.envMapRotation.toArray(); + if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity; + if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity; + if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio; + + if ( this.gradientMap && this.gradientMap.isTexture ) { + + data.gradientMap = this.gradientMap.toJSON( meta ).uuid; + + } + + if ( this.transmission !== undefined ) data.transmission = this.transmission; + if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid; + if ( this.thickness !== undefined ) data.thickness = this.thickness; + if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid; + if ( this.attenuationDistance !== undefined ) data.attenuationDistance = this.attenuationDistance; + if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex(); + + if ( this.size !== undefined ) data.size = this.size; + if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation; + + if ( Array.isArray( this.clippingPlanes ) && this.clippingPlanes.length > 0 ) { + + data.clippingPlanes = this.clippingPlanes.map( plane => plane.toJSON() ); + + } + + // rotation (SpriteMaterial) + if ( this.rotation !== undefined ) data.rotation = this.rotation; + + // depthPacking (MeshDepthMaterial) + if ( this.depthPacking !== undefined ) data.depthPacking = this.depthPacking; + + if ( this.linewidth !== undefined ) data.linewidth = this.linewidth; + if ( this.linecap !== undefined ) data.linecap = this.linecap; + if ( this.linejoin !== undefined ) data.linejoin = this.linejoin; + if ( this.dashSize !== undefined ) data.dashSize = this.dashSize; + if ( this.gapSize !== undefined ) data.gapSize = this.gapSize; + if ( this.scale !== undefined ) data.scale = this.scale; + + if ( this.wireframe !== undefined ) data.wireframe = this.wireframe; + if ( this.wireframeLinewidth !== undefined ) data.wireframeLinewidth = this.wireframeLinewidth; + if ( this.wireframeLinecap !== undefined ) data.wireframeLinecap = this.wireframeLinecap; + if ( this.wireframeLinejoin !== undefined ) data.wireframeLinejoin = this.wireframeLinejoin; + + if ( this.flatShading !== undefined ) data.flatShading = this.flatShading; + + if ( this.fog !== undefined ) data.fog = this.fog; + + if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData; + + // TODO: Copied from Object3D.toJSON + + function extractFromCache( cache ) { + + const values = []; + + for ( const key in cache ) { + + const data = cache[ key ]; + delete data.metadata; + values.push( data ); + + } + + return values; + + } + + if ( isRootObject ) { + + const textures = extractFromCache( meta.textures ); + const images = extractFromCache( meta.images ); + + if ( textures.length > 0 ) data.textures = textures; + if ( images.length > 0 ) data.images = images; + + } + + return data; + + } + + /** + * Deserializes the material from the given JSON. + * + * @param {Object} json - The JSON holding the serialized material. + * @param {Object} textures - A dictionary holding textures referenced by the material. + * @return {Material} A reference to this material. + */ + fromJSON( json, textures ) { + + if ( json.uuid !== undefined ) this.uuid = json.uuid; + if ( json.name !== undefined ) this.name = json.name; + if ( json.color !== undefined && this.color !== undefined ) this.color.setHex( json.color ); + if ( json.roughness !== undefined ) this.roughness = json.roughness; + if ( json.metalness !== undefined ) this.metalness = json.metalness; + if ( json.sheen !== undefined ) this.sheen = json.sheen; + if ( json.sheenColor !== undefined ) this.sheenColor = new Color().setHex( json.sheenColor ); + if ( json.sheenRoughness !== undefined ) this.sheenRoughness = json.sheenRoughness; + if ( json.emissive !== undefined && this.emissive !== undefined ) this.emissive.setHex( json.emissive ); + if ( json.specular !== undefined && this.specular !== undefined ) this.specular.setHex( json.specular ); + if ( json.specularIntensity !== undefined ) this.specularIntensity = json.specularIntensity; + if ( json.specularColor !== undefined && this.specularColor !== undefined ) this.specularColor.setHex( json.specularColor ); + if ( json.shininess !== undefined ) this.shininess = json.shininess; + if ( json.clearcoat !== undefined ) this.clearcoat = json.clearcoat; + if ( json.clearcoatRoughness !== undefined ) this.clearcoatRoughness = json.clearcoatRoughness; + if ( json.dispersion !== undefined ) this.dispersion = json.dispersion; + if ( json.retroreflectivity !== undefined ) this.retroreflectivity = json.retroreflectivity; + if ( json.iridescence !== undefined ) this.iridescence = json.iridescence; + if ( json.iridescenceIOR !== undefined ) this.iridescenceIOR = json.iridescenceIOR; + if ( json.iridescenceThicknessRange !== undefined ) this.iridescenceThicknessRange = json.iridescenceThicknessRange; + if ( json.transmission !== undefined ) this.transmission = json.transmission; + if ( json.thickness !== undefined ) this.thickness = json.thickness; + if ( json.attenuationDistance !== undefined ) this.attenuationDistance = json.attenuationDistance; + if ( json.attenuationColor !== undefined && this.attenuationColor !== undefined ) this.attenuationColor.setHex( json.attenuationColor ); + if ( json.anisotropy !== undefined ) this.anisotropy = json.anisotropy; + if ( json.anisotropyRotation !== undefined ) this.anisotropyRotation = json.anisotropyRotation; + if ( json.fog !== undefined ) this.fog = json.fog; + if ( json.flatShading !== undefined ) this.flatShading = json.flatShading; + if ( json.blending !== undefined ) this.blending = json.blending; + if ( json.combine !== undefined ) this.combine = json.combine; + if ( json.side !== undefined ) this.side = json.side; + if ( json.shadowSide !== undefined ) this.shadowSide = json.shadowSide; + if ( json.opacity !== undefined ) this.opacity = json.opacity; + if ( json.transparent !== undefined ) this.transparent = json.transparent; + if ( json.alphaTest !== undefined ) this.alphaTest = json.alphaTest; + if ( json.alphaHash !== undefined ) this.alphaHash = json.alphaHash; + if ( json.depthFunc !== undefined ) this.depthFunc = json.depthFunc; + if ( json.depthTest !== undefined ) this.depthTest = json.depthTest; + if ( json.depthWrite !== undefined ) this.depthWrite = json.depthWrite; + if ( json.colorWrite !== undefined ) this.colorWrite = json.colorWrite; + if ( json.clippingPlanes !== undefined ) this.clippingPlanes = json.clippingPlanes.map( plane => new Plane().fromJSON( plane ) ); + if ( json.clipIntersection !== undefined ) this.clipIntersection = json.clipIntersection; + if ( json.clipShadows !== undefined ) this.clipShadows = json.clipShadows; + if ( json.depthPacking !== undefined ) this.depthPacking = json.depthPacking; + if ( json.blendSrc !== undefined ) this.blendSrc = json.blendSrc; + if ( json.blendDst !== undefined ) this.blendDst = json.blendDst; + if ( json.blendEquation !== undefined ) this.blendEquation = json.blendEquation; + if ( json.blendSrcAlpha !== undefined ) this.blendSrcAlpha = json.blendSrcAlpha; + if ( json.blendDstAlpha !== undefined ) this.blendDstAlpha = json.blendDstAlpha; + if ( json.blendEquationAlpha !== undefined ) this.blendEquationAlpha = json.blendEquationAlpha; + if ( json.blendColor !== undefined && this.blendColor !== undefined ) this.blendColor.setHex( json.blendColor ); + if ( json.blendAlpha !== undefined ) this.blendAlpha = json.blendAlpha; + if ( json.stencilWriteMask !== undefined ) this.stencilWriteMask = json.stencilWriteMask; + if ( json.stencilFunc !== undefined ) this.stencilFunc = json.stencilFunc; + if ( json.stencilRef !== undefined ) this.stencilRef = json.stencilRef; + if ( json.stencilFuncMask !== undefined ) this.stencilFuncMask = json.stencilFuncMask; + if ( json.stencilFail !== undefined ) this.stencilFail = json.stencilFail; + if ( json.stencilZFail !== undefined ) this.stencilZFail = json.stencilZFail; + if ( json.stencilZPass !== undefined ) this.stencilZPass = json.stencilZPass; + if ( json.stencilWrite !== undefined ) this.stencilWrite = json.stencilWrite; + + if ( json.wireframe !== undefined ) this.wireframe = json.wireframe; + if ( json.wireframeLinewidth !== undefined ) this.wireframeLinewidth = json.wireframeLinewidth; + if ( json.wireframeLinecap !== undefined ) this.wireframeLinecap = json.wireframeLinecap; + if ( json.wireframeLinejoin !== undefined ) this.wireframeLinejoin = json.wireframeLinejoin; + + if ( json.rotation !== undefined ) this.rotation = json.rotation; + + if ( json.linewidth !== undefined ) this.linewidth = json.linewidth; + if ( json.linecap !== undefined ) this.linecap = json.linecap; + if ( json.linejoin !== undefined ) this.linejoin = json.linejoin; + if ( json.dashSize !== undefined ) this.dashSize = json.dashSize; + if ( json.gapSize !== undefined ) this.gapSize = json.gapSize; + if ( json.scale !== undefined ) this.scale = json.scale; + + if ( json.polygonOffset !== undefined ) this.polygonOffset = json.polygonOffset; + if ( json.polygonOffsetFactor !== undefined ) this.polygonOffsetFactor = json.polygonOffsetFactor; + if ( json.polygonOffsetUnits !== undefined ) this.polygonOffsetUnits = json.polygonOffsetUnits; + + if ( json.dithering !== undefined ) this.dithering = json.dithering; + + if ( json.alphaToCoverage !== undefined ) this.alphaToCoverage = json.alphaToCoverage; + if ( json.premultipliedAlpha !== undefined ) this.premultipliedAlpha = json.premultipliedAlpha; + if ( json.forceSinglePass !== undefined ) this.forceSinglePass = json.forceSinglePass; + if ( json.allowOverride !== undefined ) this.allowOverride = json.allowOverride; + + if ( json.visible !== undefined ) this.visible = json.visible; + + if ( json.toneMapped !== undefined ) this.toneMapped = json.toneMapped; + + if ( json.userData !== undefined ) this.userData = json.userData; + + if ( json.vertexColors !== undefined ) { + + if ( typeof json.vertexColors === 'number' ) { + + this.vertexColors = json.vertexColors > 0; + + } else { + + this.vertexColors = json.vertexColors; + + } + + } + + // for PointsMaterial + + if ( json.size !== undefined ) this.size = json.size; + if ( json.sizeAttenuation !== undefined ) this.sizeAttenuation = json.sizeAttenuation; + + // maps + + if ( json.map !== undefined ) this.map = textures[ json.map ] || null; + if ( json.matcap !== undefined ) this.matcap = textures[ json.matcap ] || null; + + if ( json.alphaMap !== undefined ) this.alphaMap = textures[ json.alphaMap ] || null; + + if ( json.bumpMap !== undefined ) this.bumpMap = textures[ json.bumpMap ] || null; + if ( json.bumpScale !== undefined ) this.bumpScale = json.bumpScale; + + if ( json.normalMap !== undefined ) this.normalMap = textures[ json.normalMap ] || null; + if ( json.normalMapType !== undefined ) this.normalMapType = json.normalMapType; + if ( json.normalScale !== undefined ) { + + let normalScale = json.normalScale; + + if ( Array.isArray( normalScale ) === false ) { + + // Blender exporter used to export a scalar. See #7459 + + normalScale = [ normalScale, normalScale ]; + + } + + this.normalScale = new Vector2().fromArray( normalScale ); + + } + + if ( json.displacementMap !== undefined ) this.displacementMap = textures[ json.displacementMap ] || null; + if ( json.displacementScale !== undefined ) this.displacementScale = json.displacementScale; + if ( json.displacementBias !== undefined ) this.displacementBias = json.displacementBias; + + if ( json.roughnessMap !== undefined ) this.roughnessMap = textures[ json.roughnessMap ] || null; + if ( json.metalnessMap !== undefined ) this.metalnessMap = textures[ json.metalnessMap ] || null; + + if ( json.emissiveMap !== undefined ) this.emissiveMap = textures[ json.emissiveMap ] || null; + if ( json.emissiveIntensity !== undefined ) this.emissiveIntensity = json.emissiveIntensity; + + if ( json.specularMap !== undefined ) this.specularMap = textures[ json.specularMap ] || null; + if ( json.specularIntensityMap !== undefined ) this.specularIntensityMap = textures[ json.specularIntensityMap ] || null; + if ( json.specularColorMap !== undefined ) this.specularColorMap = textures[ json.specularColorMap ] || null; + + if ( json.envMap !== undefined ) this.envMap = textures[ json.envMap ] || null; + if ( json.envMapRotation !== undefined ) this.envMapRotation.fromArray( json.envMapRotation ); + if ( json.envMapIntensity !== undefined ) this.envMapIntensity = json.envMapIntensity; + + if ( json.reflectivity !== undefined ) this.reflectivity = json.reflectivity; + if ( json.refractionRatio !== undefined ) this.refractionRatio = json.refractionRatio; + + if ( json.lightMap !== undefined ) this.lightMap = textures[ json.lightMap ] || null; + if ( json.lightMapIntensity !== undefined ) this.lightMapIntensity = json.lightMapIntensity; + + if ( json.aoMap !== undefined ) this.aoMap = textures[ json.aoMap ] || null; + if ( json.aoMapIntensity !== undefined ) this.aoMapIntensity = json.aoMapIntensity; + + if ( json.gradientMap !== undefined ) this.gradientMap = textures[ json.gradientMap ] || null; + + if ( json.clearcoatMap !== undefined ) this.clearcoatMap = textures[ json.clearcoatMap ] || null; + if ( json.clearcoatRoughnessMap !== undefined ) this.clearcoatRoughnessMap = textures[ json.clearcoatRoughnessMap ] || null; + if ( json.clearcoatNormalMap !== undefined ) this.clearcoatNormalMap = textures[ json.clearcoatNormalMap ] || null; + if ( json.clearcoatNormalScale !== undefined ) this.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale ); + + if ( json.iridescenceMap !== undefined ) this.iridescenceMap = textures[ json.iridescenceMap ] || null; + if ( json.iridescenceThicknessMap !== undefined ) this.iridescenceThicknessMap = textures[ json.iridescenceThicknessMap ] || null; + + if ( json.transmissionMap !== undefined ) this.transmissionMap = textures[ json.transmissionMap ] || null; + if ( json.thicknessMap !== undefined ) this.thicknessMap = textures[ json.thicknessMap ] || null; + + if ( json.anisotropyMap !== undefined ) this.anisotropyMap = textures[ json.anisotropyMap ] || null; + + if ( json.sheenColorMap !== undefined ) this.sheenColorMap = textures[ json.sheenColorMap ] || null; + if ( json.sheenRoughnessMap !== undefined ) this.sheenRoughnessMap = textures[ json.sheenRoughnessMap ] || null; + + return this; + + } + + /** + * Returns a new material with copied values from this instance. + * + * @return {Material} A clone of this instance. + */ + clone() { + + return new this.constructor().copy( this ); + + } + + /** + * Copies the values of the given material to this instance. + * + * @param {Material} source - The material to copy. + * @return {Material} A reference to this instance. + */ + copy( source ) { + + this.name = source.name; + + this.blending = source.blending; + this.side = source.side; + this.vertexColors = source.vertexColors; + + this.opacity = source.opacity; + this.transparent = source.transparent; + + this.blendSrc = source.blendSrc; + this.blendDst = source.blendDst; + this.blendEquation = source.blendEquation; + this.blendSrcAlpha = source.blendSrcAlpha; + this.blendDstAlpha = source.blendDstAlpha; + this.blendEquationAlpha = source.blendEquationAlpha; + this.blendColor.copy( source.blendColor ); + this.blendAlpha = source.blendAlpha; + + this.depthFunc = source.depthFunc; + this.depthTest = source.depthTest; + this.depthWrite = source.depthWrite; + + this.stencilWriteMask = source.stencilWriteMask; + this.stencilFunc = source.stencilFunc; + this.stencilRef = source.stencilRef; + this.stencilFuncMask = source.stencilFuncMask; + this.stencilFail = source.stencilFail; + this.stencilZFail = source.stencilZFail; + this.stencilZPass = source.stencilZPass; + this.stencilWrite = source.stencilWrite; + + const srcPlanes = source.clippingPlanes; + let dstPlanes = null; + + if ( srcPlanes !== null ) { + + const n = srcPlanes.length; + dstPlanes = new Array( n ); + + for ( let i = 0; i !== n; ++ i ) { + + dstPlanes[ i ] = srcPlanes[ i ].clone(); + + } + + } + + this.clippingPlanes = dstPlanes; + this.clipIntersection = source.clipIntersection; + this.clipShadows = source.clipShadows; + + this.shadowSide = source.shadowSide; + + this.colorWrite = source.colorWrite; + + this.precision = source.precision; + + this.polygonOffset = source.polygonOffset; + this.polygonOffsetFactor = source.polygonOffsetFactor; + this.polygonOffsetUnits = source.polygonOffsetUnits; + + this.dithering = source.dithering; + + this.alphaTest = source.alphaTest; + this.alphaHash = source.alphaHash; + this.alphaToCoverage = source.alphaToCoverage; + this.premultipliedAlpha = source.premultipliedAlpha; + this.forceSinglePass = source.forceSinglePass; + this.allowOverride = source.allowOverride; + + this.visible = source.visible; + + this.toneMapped = source.toneMapped; + + this.userData = JSON.parse( JSON.stringify( source.userData ) ); + + return this; + + } + + /** + * Frees the GPU-related resources allocated by this instance. Call this + * method whenever this instance is no longer used in your app. + * + * @fires Material#dispose + */ + dispose() { + + /** + * Fires when the material has been disposed of. + * + * @event Material#dispose + * @type {Object} + */ + this.dispatchEvent( { type: 'dispose' } ); + + } + + /** + * Setting this property to `true` indicates the engine the material + * needs to be recompiled. + * + * @type {boolean} + * @default false + * @param {boolean} value + */ + set needsUpdate( value ) { + + if ( value === true ) this.version ++; + + } + +} + +/** + * A material for rendering instances of {@link Sprite}. + * + * ```js + * const map = new THREE.TextureLoader().load( 'textures/sprite.png' ); + * const material = new THREE.SpriteMaterial( { map: map, color: 0xffffff } ); + * + * const sprite = new THREE.Sprite( material ); + * sprite.scale.set(200, 200, 1) + * scene.add( sprite ); + * ``` + * + * @augments Material + */ +class SpriteMaterial extends Material { + + /** + * Constructs a new sprite material. + * + * @param {Object} [parameters] - An object with one or more properties + * defining the material's appearance. Any property of the material + * (including any property from inherited materials) can be passed + * in here. Color values can be passed any type of value accepted + * by {@link Color#set}. + */ + constructor( parameters ) { + + super(); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isSpriteMaterial = true; + + this.type = 'SpriteMaterial'; + + /** + * Color of the material. + * + * @type {Color} + * @default (1,1,1) + */ + this.color = new Color( 0xffffff ); + + /** + * The color map. May optionally include an alpha channel, typically combined + * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map + * color is modulated by the diffuse `color`. + * + * `map` represents color data, and the texture must be assigned a + * {@link Texture#colorSpace}. Most `map` textures set + * `texture.colorSpace = SRGBColorSpace`. + * + * @type {?Texture} + * @default null + */ + this.map = null; + + /** + * The alpha map is a grayscale texture that controls the opacity across the + * surface (black: fully transparent; white: fully opaque). + * + * Only the color of the texture is used, ignoring the alpha channel if one + * exists. For RGB and RGBA textures, the renderer will use the green channel + * when sampling this texture due to the extra bit of precision provided for + * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and + * luminance/alpha textures will also still work as expected. + * + * `alphaMap` represents non-color data. Any texture assigned must have + * `texture.colorSpace = NoColorSpace` (default). + * + * @type {?Texture} + * @default null + */ + this.alphaMap = null; + + /** + * The rotation of the sprite in radians. + * + * @type {number} + * @default 0 + */ + this.rotation = 0; + + /** + * Specifies whether size of the sprite is attenuated by the camera depth (perspective camera only). + * + * @type {boolean} + * @default true + */ + this.sizeAttenuation = true; + + /** + * Overwritten since sprite materials are transparent + * by default. + * + * @type {boolean} + * @default true + */ + this.transparent = true; + + /** + * Whether the material is affected by fog or not. + * + * @type {boolean} + * @default true + */ + this.fog = true; + + this.setValues( parameters ); + + } + + copy( source ) { + + super.copy( source ); + + this.color.copy( source.color ); + + this.map = source.map; + + this.alphaMap = source.alphaMap; + + this.rotation = source.rotation; + + this.sizeAttenuation = source.sizeAttenuation; + + this.fog = source.fog; + + return this; + + } + +} + +let _geometry; + +const _intersectPoint = /*@__PURE__*/ new Vector3(); +const _worldScale = /*@__PURE__*/ new Vector3(); +const _mvPosition = /*@__PURE__*/ new Vector3(); + +const _alignedPosition = /*@__PURE__*/ new Vector2(); +const _rotatedPosition = /*@__PURE__*/ new Vector2(); +const _viewWorldMatrix = /*@__PURE__*/ new Matrix4(); + +const _vA$1 = /*@__PURE__*/ new Vector3(); +const _vB$1 = /*@__PURE__*/ new Vector3(); +const _vC$1 = /*@__PURE__*/ new Vector3(); + +const _uvA = /*@__PURE__*/ new Vector2(); +const _uvB = /*@__PURE__*/ new Vector2(); +const _uvC = /*@__PURE__*/ new Vector2(); + +/** + * A sprite is a plane that always faces towards the camera, generally with a + * partially transparent texture applied. + * + * Sprites do not cast shadows, setting {@link Object3D#castShadow} to `true` will + * have no effect. + * + * ```js + * const map = new THREE.TextureLoader().load( 'sprite.png' ); + * const material = new THREE.SpriteMaterial( { map: map } ); + * + * const sprite = new THREE.Sprite( material ); + * scene.add( sprite ); + * ``` + * + * @augments Object3D + */ +class Sprite extends Object3D { + + /** + * Constructs a new sprite. + * + * @param {(SpriteMaterial|SpriteNodeMaterial)} [material] - The sprite material. + */ + constructor( material = new SpriteMaterial() ) { + + super(); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isSprite = true; + + this.type = 'Sprite'; + + if ( _geometry === undefined ) { + + _geometry = new BufferGeometry(); + + const float32Array = new Float32Array( [ + -0.5, -0.5, 0, 0, 0, + 0.5, -0.5, 0, 1, 0, + 0.5, 0.5, 0, 1, 1, + -0.5, 0.5, 0, 0, 1 + ] ); + + const interleavedBuffer = new InterleavedBuffer( float32Array, 5 ); + + _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] ); + _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) ); + _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) ); + + } + + /** + * The sprite geometry. + * + * @type {BufferGeometry} + */ + this.geometry = _geometry; + + /** + * The sprite material. + * + * @type {(SpriteMaterial|SpriteNodeMaterial)} + */ + this.material = material; + + /** + * The sprite's anchor point, and the point around which the sprite rotates. + * A value of `(0.5, 0.5)` corresponds to the midpoint of the sprite. A value + * of `(0, 0)` corresponds to the lower left corner of the sprite. + * + * @type {Vector2} + * @default (0.5,0.5) + */ + this.center = new Vector2( 0.5, 0.5 ); + + /** + * The number of instances of this sprite. + * Can only be used with {@link WebGPURenderer}. + * + * @type {number} + * @default 1 + */ + this.count = 1; + + } + + /** + * Returns `true` if this sprite intersects the given frustum. + * + * @param {Frustum|FrustumArray} frustum - The frustum to test. + * @return {boolean} Whether this sprite intersects the given frustum or not. + */ + intersectsFrustum( frustum ) { + + return frustum.intersectsSprite( this ); + + } + + /** + * Computes intersection points between a casted ray and this sprite. + * + * @param {Raycaster} raycaster - The raycaster. + * @param {Array} intersects - The target array that holds the intersection points. + */ + raycast( raycaster, intersects ) { + + if ( raycaster.camera === null ) { + + error( 'Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' ); + + } + + _worldScale.setFromMatrixScale( this.matrixWorld ); + + _viewWorldMatrix.copy( raycaster.camera.matrixWorld ); + this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld ); + + _mvPosition.setFromMatrixPosition( this.modelViewMatrix ); + + if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) { + + _worldScale.multiplyScalar( - _mvPosition.z ); + + } + + const rotation = this.material.rotation; + let sin, cos; + + if ( rotation !== 0 ) { + + cos = Math.cos( rotation ); + sin = Math.sin( rotation ); + + } + + const center = this.center; + + transformVertex( _vA$1.set( -0.5, -0.5, 0 ), _mvPosition, center, _worldScale, sin, cos ); + transformVertex( _vB$1.set( 0.5, -0.5, 0 ), _mvPosition, center, _worldScale, sin, cos ); + transformVertex( _vC$1.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos ); + + _uvA.set( 0, 0 ); + _uvB.set( 1, 0 ); + _uvC.set( 1, 1 ); + + // check first triangle + let intersect = raycaster.ray.intersectTriangle( _vA$1, _vB$1, _vC$1, false, _intersectPoint ); + + if ( intersect === null ) { + + // check second triangle + transformVertex( _vB$1.set( -0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos ); + _uvB.set( 0, 1 ); + + intersect = raycaster.ray.intersectTriangle( _vA$1, _vC$1, _vB$1, false, _intersectPoint ); + if ( intersect === null ) { + + return; + + } + + } + + const distance = raycaster.ray.origin.distanceTo( _intersectPoint ); + + if ( distance < raycaster.near || distance > raycaster.far ) return; + + intersects.push( { + + distance: distance, + point: _intersectPoint.clone(), + uv: Triangle.getInterpolation( _intersectPoint, _vA$1, _vB$1, _vC$1, _uvA, _uvB, _uvC, new Vector2() ), + face: null, + object: this + + } ); + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + if ( source.center !== undefined ) this.center.copy( source.center ); + + this.material = source.material; + + return this; + + } + +} + +function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) { + + // compute position in camera space + _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale ); + + // to check if rotation is not zero + if ( sin !== undefined ) { + + _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y ); + _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y ); + + } else { + + _rotatedPosition.copy( _alignedPosition ); + + } + + + vertexPosition.copy( mvPosition ); + vertexPosition.x += _rotatedPosition.x; + vertexPosition.y += _rotatedPosition.y; + + // transform to world space + vertexPosition.applyMatrix4( _viewWorldMatrix ); + +} + +const _v1$2 = /*@__PURE__*/ new Vector3(); +const _v2$1 = /*@__PURE__*/ new Vector3(); + +/** + * A component for providing a basic Level of Detail (LOD) mechanism. + * + * Every LOD level is associated with an object, and rendering can be switched + * between them at the distances specified. Typically you would create, say, + * three meshes, one for far away (low detail), one for mid range (medium + * detail) and one for close up (high detail). + * + * ```js + * const lod = new THREE.LOD(); + * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } ); + * + * //Create spheres with 3 levels of detail and create new LOD levels for them + * for( let i = 0; i < 3; i++ ) { + * + * const geometry = new THREE.IcosahedronGeometry( 10, 3 - i ); + * const mesh = new THREE.Mesh( geometry, material ); + * lod.addLevel( mesh, i * 75 ); + * + * } + * + * scene.add( lod ); + * ``` + * + * @augments Object3D + */ +class LOD extends Object3D { + + /** + * Constructs a new LOD. + */ + constructor() { + + super(); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isLOD = true; + + /** + * The current LOD index. + * + * @private + * @type {number} + * @default 0 + */ + this._currentLevel = 0; + + this.type = 'LOD'; + + Object.defineProperties( this, { + /** + * This array holds the LOD levels. + * + * @name LOD#levels + * @type {Array<{object:Object3D,distance:number,hysteresis:number}>} + */ + levels: { + enumerable: true, + value: [] + } + } ); + + /** + * Whether the LOD object is updated automatically by the renderer per frame + * or not. If set to `false`, you have to call {@link LOD#update} in the + * render loop by yourself. + * + * @type {boolean} + * @default true + */ + this.autoUpdate = true; + + } + + copy( source ) { + + super.copy( source, false ); + + const levels = source.levels; + + for ( let i = 0, l = levels.length; i < l; i ++ ) { + + const level = levels[ i ]; + + this.addLevel( level.object.clone(), level.distance, level.hysteresis ); + + } + + this.autoUpdate = source.autoUpdate; + + return this; + + } + + /** + * Adds a mesh that will display at a certain distance and greater. Typically + * the further away the distance, the lower the detail on the mesh. + * + * @param {Object3D} object - The 3D object to display at this level. + * @param {number} [distance=0] - The distance at which to display this level of detail. + * @param {number} [hysteresis=0] - Threshold used to avoid flickering at LOD boundaries, as a fraction of distance. + * @return {LOD} A reference to this instance. + */ + addLevel( object, distance = 0, hysteresis = 0 ) { + + distance = Math.abs( distance ); + + const levels = this.levels; + + let l; + + for ( l = 0; l < levels.length; l ++ ) { + + if ( distance < levels[ l ].distance ) { + + break; + + } + + } + + levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } ); + + this.add( object ); + + return this; + + } + + /** + * Removes an existing level, based on the distance from the camera. + * Returns `true` when the level has been removed. Otherwise `false`. + * + * @param {number} distance - Distance of the level to remove. + * @return {boolean} Whether the level has been removed or not. + */ + removeLevel( distance ) { + + const levels = this.levels; + + for ( let i = 0; i < levels.length; i ++ ) { + + if ( levels[ i ].distance === distance ) { + + const removedElements = levels.splice( i, 1 ); + this.remove( removedElements[ 0 ].object ); + + return true; + + } + + } + + return false; + + } + + /** + * Returns the currently active LOD level index. + * + * @return {number} The current active LOD level index. + */ + getCurrentLevel() { + + return this._currentLevel; + + } + + /** + * Returns a reference to the first 3D object that is greater than + * the given distance. + * + * @param {number} distance - The LOD distance. + * @return {?Object3D} The found 3D object. `null` if no 3D object has been found. + */ + getObjectForDistance( distance ) { + + const levels = this.levels; + + if ( levels.length > 0 ) { + + let i, l; + + for ( i = 1, l = levels.length; i < l; i ++ ) { + + let levelDistance = levels[ i ].distance; + + if ( levels[ i ].object.visible ) { + + levelDistance -= levelDistance * levels[ i ].hysteresis; + + } + + if ( distance < levelDistance ) { + + break; + + } + + } + + return levels[ i - 1 ].object; + + } + + return null; + + } + + /** + * Computes intersection points between a casted ray and this LOD. + * + * @param {Raycaster} raycaster - The raycaster. + * @param {Array} intersects - The target array that holds the intersection points. + */ + raycast( raycaster, intersects ) { + + const levels = this.levels; + + if ( levels.length > 0 ) { + + _v1$2.setFromMatrixPosition( this.matrixWorld ); + + const distance = raycaster.ray.origin.distanceTo( _v1$2 ); + + this.getObjectForDistance( distance ).raycast( raycaster, intersects ); + + } + + } + + /** + * Updates the LOD by computing which LOD level should be visible according + * to the current distance of the given camera. + * + * @param {Camera} camera - The camera the scene is rendered with. + */ + update( camera ) { + + const levels = this.levels; + + if ( levels.length > 1 ) { + + _v1$2.setFromMatrixPosition( camera.matrixWorld ); + _v2$1.setFromMatrixPosition( this.matrixWorld ); + + const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom; + + levels[ 0 ].object.visible = true; + + let i, l; + + for ( i = 1, l = levels.length; i < l; i ++ ) { + + let levelDistance = levels[ i ].distance; + + if ( levels[ i ].object.visible ) { + + levelDistance -= levelDistance * levels[ i ].hysteresis; + + } + + if ( distance >= levelDistance ) { + + levels[ i - 1 ].object.visible = false; + levels[ i ].object.visible = true; + + } else { + + break; + + } + + } + + this._currentLevel = i - 1; + + for ( ; i < l; i ++ ) { + + levels[ i ].object.visible = false; + + } + + } + + } + + toJSON( meta ) { + + const data = super.toJSON( meta ); + + data.object.autoUpdate = this.autoUpdate; + + data.object.levels = []; + + const levels = this.levels; + + for ( let i = 0, l = levels.length; i < l; i ++ ) { + + const level = levels[ i ]; + + data.object.levels.push( { + object: level.object.uuid, + distance: level.distance, + hysteresis: level.hysteresis + } ); + + } + + return data; + + } + +} + +const _vector$7 = /*@__PURE__*/ new Vector3(); +const _segCenter = /*@__PURE__*/ new Vector3(); +const _segDir = /*@__PURE__*/ new Vector3(); +const _diff = /*@__PURE__*/ new Vector3(); + +/** + * A ray that emits from an origin in a certain direction. The class is used by + * {@link Raycaster} to assist with raycasting. Raycasting is used for + * mouse picking (working out what objects in the 3D space the mouse is over) + * amongst other things. + */ +class Ray { + + /** + * Constructs a new ray. + * + * @param {Vector3} [origin=(0,0,0)] - The origin of the ray. + * @param {Vector3} [direction=(0,0,-1)] - The (normalized) direction of the ray. + */ + constructor( origin = new Vector3(), direction = new Vector3( 0, 0, -1 ) ) { + + /** + * The origin of the ray. + * + * @type {Vector3} + */ + this.origin = origin; + + /** + * The (normalized) direction of the ray. + * + * @type {Vector3} + */ + this.direction = direction; + + } + + /** + * Sets the ray's components by copying the given values. + * + * @param {Vector3} origin - The origin. + * @param {Vector3} direction - The direction. + * @return {Ray} A reference to this ray. + */ + set( origin, direction ) { + + this.origin.copy( origin ); + this.direction.copy( direction ); + + return this; + + } + + /** + * Copies the values of the given ray to this instance. + * + * @param {Ray} ray - The ray to copy. + * @return {Ray} A reference to this ray. + */ + copy( ray ) { + + this.origin.copy( ray.origin ); + this.direction.copy( ray.direction ); + + return this; + + } + + /** + * Returns a vector that is located at a given distance along this ray. + * + * @param {number} t - The distance along the ray to retrieve a position for. + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {Vector3} A position on the ray. + */ + at( t, target ) { + + return target.copy( this.origin ).addScaledVector( this.direction, t ); + + } + + /** + * Adjusts the direction of the ray to point at the given vector in world space. + * + * @param {Vector3} v - The target position. + * @return {Ray} A reference to this ray. + */ + lookAt( v ) { + + this.direction.copy( v ).sub( this.origin ).normalize(); + + return this; + + } + + /** + * Shift the origin of this ray along its direction by the given distance. + * + * @param {number} t - The distance along the ray to interpolate. + * @return {Ray} A reference to this ray. + */ + recast( t ) { + + this.origin.copy( this.at( t, _vector$7 ) ); + + return this; + + } + + /** + * Returns the point along this ray that is closest to the given point. + * + * @param {Vector3} point - A point in 3D space to get the closet location on the ray for. + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {Vector3} The closest point on this ray. + */ + closestPointToPoint( point, target ) { + + target.subVectors( point, this.origin ); + + const directionDistance = target.dot( this.direction ); + + if ( directionDistance < 0 ) { + + return target.copy( this.origin ); + + } + + return target.copy( this.origin ).addScaledVector( this.direction, directionDistance ); + + } + + /** + * Returns the distance of the closest approach between this ray and the given point. + * + * @param {Vector3} point - A point in 3D space to compute the distance to. + * @return {number} The distance. + */ + distanceToPoint( point ) { + + return Math.sqrt( this.distanceSqToPoint( point ) ); + + } + + /** + * Returns the squared distance of the closest approach between this ray and the given point. + * + * @param {Vector3} point - A point in 3D space to compute the distance to. + * @return {number} The squared distance. + */ + distanceSqToPoint( point ) { + + const directionDistance = _vector$7.subVectors( point, this.origin ).dot( this.direction ); + + // point behind the ray + + if ( directionDistance < 0 ) { + + return this.origin.distanceToSquared( point ); + + } + + _vector$7.copy( this.origin ).addScaledVector( this.direction, directionDistance ); + + return _vector$7.distanceToSquared( point ); + + } + + /** + * Returns the squared distance between this ray and the given line segment. + * + * @param {Vector3} v0 - The start point of the line segment. + * @param {Vector3} v1 - The end point of the line segment. + * @param {Vector3} [optionalPointOnRay] - When provided, it receives the point on this ray that is closest to the segment. + * @param {Vector3} [optionalPointOnSegment] - When provided, it receives the point on the line segment that is closest to this ray. + * @return {number} The squared distance. + */ + distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) { + + // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h + // It returns the min distance between the ray and the segment + // defined by v0 and v1 + // It can also set two optional targets : + // - The closest point on the ray + // - The closest point on the segment + + _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 ); + _segDir.copy( v1 ).sub( v0 ).normalize(); + _diff.copy( this.origin ).sub( _segCenter ); + + const segExtent = v0.distanceTo( v1 ) * 0.5; + const a01 = - this.direction.dot( _segDir ); + const b0 = _diff.dot( this.direction ); + const b1 = - _diff.dot( _segDir ); + const c = _diff.lengthSq(); + const det = Math.abs( 1 - a01 * a01 ); + let s0, s1, sqrDist, extDet; + + if ( det > 0 ) { + + // The ray and segment are not parallel. + + s0 = a01 * b1 - b0; + s1 = a01 * b0 - b1; + extDet = segExtent * det; + + if ( s0 >= 0 ) { + + if ( s1 >= - extDet ) { + + if ( s1 <= extDet ) { + + // region 0 + // Minimum at interior points of ray and segment. + + const invDet = 1 / det; + s0 *= invDet; + s1 *= invDet; + sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c; + + } else { + + // region 1 + + s1 = segExtent; + s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); + sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; + + } + + } else { + + // region 5 + + s1 = - segExtent; + s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); + sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; + + } + + } else { + + if ( s1 <= - extDet ) { + + // region 4 + + s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) ); + s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent ); + sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; + + } else if ( s1 <= extDet ) { + + // region 3 + + s0 = 0; + s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent ); + sqrDist = s1 * ( s1 + 2 * b1 ) + c; + + } else { + + // region 2 + + s0 = Math.max( 0, - ( a01 * segExtent + b0 ) ); + s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent ); + sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; + + } + + } + + } else { + + // Ray and segment are parallel. + + s1 = ( a01 > 0 ) ? - segExtent : segExtent; + s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); + sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; + + } + + if ( optionalPointOnRay ) { + + optionalPointOnRay.copy( this.origin ).addScaledVector( this.direction, s0 ); + + } + + if ( optionalPointOnSegment ) { + + optionalPointOnSegment.copy( _segCenter ).addScaledVector( _segDir, s1 ); + + } + + return sqrDist; + + } + + /** + * Intersects this ray with the given sphere, returning the intersection + * point or `null` if there is no intersection. + * + * @param {Sphere} sphere - The sphere to intersect. + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {?Vector3} The intersection point. + */ + intersectSphere( sphere, target ) { + + if ( sphere.radius < 0 ) return null; // handle empty spheres, see #31187 + + _vector$7.subVectors( sphere.center, this.origin ); + const tca = _vector$7.dot( this.direction ); + const d2 = _vector$7.dot( _vector$7 ) - tca * tca; + const radius2 = sphere.radius * sphere.radius; + + if ( d2 > radius2 ) return null; + + const thc = Math.sqrt( radius2 - d2 ); + + // t0 = first intersect point - entrance on front of sphere + const t0 = tca - thc; + + // t1 = second intersect point - exit point on back of sphere + const t1 = tca + thc; + + // test to see if t1 is behind the ray - if so, return null + if ( t1 < 0 ) return null; + + // test to see if t0 is behind the ray: + // if it is, the ray is inside the sphere, so return the second exit point scaled by t1, + // in order to always return an intersect point that is in front of the ray. + if ( t0 < 0 ) return this.at( t1, target ); + + // else t0 is in front of the ray, so return the first collision point scaled by t0 + return this.at( t0, target ); + + } + + /** + * Returns `true` if this ray intersects with the given sphere. + * + * @param {Sphere} sphere - The sphere to intersect. + * @return {boolean} Whether this ray intersects with the given sphere or not. + */ + intersectsSphere( sphere ) { + + if ( sphere.radius < 0 ) return false; // handle empty spheres, see #31187 + + return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius ); + + } + + /** + * Computes the distance from the ray's origin to the given plane. Returns `null` if the ray + * does not intersect with the plane. + * + * @param {Plane} plane - The plane to compute the distance to. + * @return {?number} Whether this ray intersects with the given sphere or not. + */ + distanceToPlane( plane ) { + + const denominator = plane.normal.dot( this.direction ); + + if ( denominator === 0 ) { + + // line is coplanar, return origin + if ( plane.distanceToPoint( this.origin ) === 0 ) { + + return 0; + + } + + // Null is preferable to undefined since undefined means.... it is undefined + + return null; + + } + + const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator; + + // Return if the ray never intersects the plane + + return t >= 0 ? t : null; + + } + + /** + * Intersects this ray with the given plane, returning the intersection + * point or `null` if there is no intersection. + * + * @param {Plane} plane - The plane to intersect. + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {?Vector3} The intersection point. + */ + intersectPlane( plane, target ) { + + const t = this.distanceToPlane( plane ); + + if ( t === null ) { + + return null; + + } + + return this.at( t, target ); + + } + + /** + * Returns `true` if this ray intersects with the given plane. + * + * @param {Plane} plane - The plane to intersect. + * @return {boolean} Whether this ray intersects with the given plane or not. + */ + intersectsPlane( plane ) { + + // check if the ray lies on the plane first + + const distToPoint = plane.distanceToPoint( this.origin ); + + if ( distToPoint === 0 ) { + + return true; + + } + + const denominator = plane.normal.dot( this.direction ); + + if ( denominator * distToPoint < 0 ) { + + return true; + + } + + // ray origin is behind the plane (and is pointing behind it) + + return false; + + } + + /** + * Intersects this ray with the given bounding box, returning the intersection + * point or `null` if there is no intersection. + * + * @param {Box3} box - The box to intersect. + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {?Vector3} The intersection point. + */ + intersectBox( box, target ) { + + let tmin, tmax, tymin, tymax, tzmin, tzmax; + + const invdirx = 1 / this.direction.x, + invdiry = 1 / this.direction.y, + invdirz = 1 / this.direction.z; + + const origin = this.origin; + + if ( invdirx >= 0 ) { + + tmin = ( box.min.x - origin.x ) * invdirx; + tmax = ( box.max.x - origin.x ) * invdirx; + + } else { + + tmin = ( box.max.x - origin.x ) * invdirx; + tmax = ( box.min.x - origin.x ) * invdirx; + + } + + if ( invdiry >= 0 ) { + + tymin = ( box.min.y - origin.y ) * invdiry; + tymax = ( box.max.y - origin.y ) * invdiry; + + } else { + + tymin = ( box.max.y - origin.y ) * invdiry; + tymax = ( box.min.y - origin.y ) * invdiry; + + } + + if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null; + + if ( tymin > tmin || isNaN( tmin ) ) tmin = tymin; + + if ( tymax < tmax || isNaN( tmax ) ) tmax = tymax; + + if ( invdirz >= 0 ) { + + tzmin = ( box.min.z - origin.z ) * invdirz; + tzmax = ( box.max.z - origin.z ) * invdirz; + + } else { + + tzmin = ( box.max.z - origin.z ) * invdirz; + tzmax = ( box.min.z - origin.z ) * invdirz; + + } + + if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null; + + if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin; + + if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax; + + //return point closest to the ray (positive side) + + if ( tmax < 0 ) return null; + + return this.at( tmin >= 0 ? tmin : tmax, target ); + + } + + /** + * Returns `true` if this ray intersects with the given box. + * + * @param {Box3} box - The box to intersect. + * @return {boolean} Whether this ray intersects with the given box or not. + */ + intersectsBox( box ) { + + return this.intersectBox( box, _vector$7 ) !== null; + + } + + /** + * Intersects this ray with the given triangle, returning the intersection + * point or `null` if there is no intersection. + * + * @param {Vector3} a - The first vertex of the triangle. + * @param {Vector3} b - The second vertex of the triangle. + * @param {Vector3} c - The third vertex of the triangle. + * @param {boolean} backfaceCulling - Whether to use backface culling or not. + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {?Vector3} The intersection point. + */ + intersectTriangle( a, b, c, backfaceCulling, target ) { + + // Watertight ray/triangle intersection. Reference: Woop, Benthin, Wald, + // "Watertight Ray/Triangle Intersection", JCGT vol. 2 no. 1 (2013), Appendix A. + // https://jcgt.org/published/0002/01/05/ + + const origin = this.origin; + const direction = this.direction; + + const dx = direction.x; + const dy = direction.y; + const dz = direction.z; + + // triangle vertices relative to the ray origin + + const aox = a.x - origin.x, aoy = a.y - origin.y, aoz = a.z - origin.z; + const box = b.x - origin.x, boy = b.y - origin.y, boz = b.z - origin.z; + const cox = c.x - origin.x, coy = c.y - origin.y, coz = c.z - origin.z; + + // Use the dimension where the ray direction is maximal as the projection + // axis (kz) and read every component already permuted into (kx, ky, kz). + // kx and ky are swapped when the direction's kz component is negative, to + // preserve the winding order of triangles. + + const adx = Math.abs( dx ), ady = Math.abs( dy ), adz = Math.abs( dz ); + + let dkx, dky, dkz; + let akx, aky, akz, bkx, bky, bkz, ckx, cky, ckz; + + if ( adx >= ady && adx >= adz ) { + + dkz = dx; akz = aox; bkz = box; ckz = cox; + + if ( dx >= 0 ) { + + dkx = dy; dky = dz; + akx = aoy; aky = aoz; bkx = boy; bky = boz; ckx = coy; cky = coz; + + } else { + + dkx = dz; dky = dy; + akx = aoz; aky = aoy; bkx = boz; bky = boy; ckx = coz; cky = coy; + + } + + } else if ( ady >= adz ) { + + dkz = dy; akz = aoy; bkz = boy; ckz = coy; + + if ( dy >= 0 ) { + + dkx = dz; dky = dx; + akx = aoz; aky = aox; bkx = boz; bky = box; ckx = coz; cky = cox; + + } else { + + dkx = dx; dky = dz; + akx = aox; aky = aoz; bkx = box; bky = boz; ckx = cox; cky = coz; + + } + + } else { + + dkz = dz; akz = aoz; bkz = boz; ckz = coz; + + if ( dz >= 0 ) { + + dkx = dx; dky = dy; + akx = aox; aky = aoy; bkx = box; bky = boy; ckx = cox; cky = coy; + + } else { + + dkx = dy; dky = dx; + akx = aoy; aky = aox; bkx = boy; bky = box; ckx = coy; cky = cox; + + } + + } + + // a zero direction has no maximal axis and cannot intersect + + if ( dkz === 0 ) return null; + + // shear constants that align the ray with the +kz axis + + const sx = dkx / dkz, sy = dky / dkz, sz = 1 / dkz; + + // sheared and scaled vertices + + const ax = akx - sx * akz, ay = aky - sy * akz; + const bx = bkx - sx * bkz, by = bky - sy * bkz; + const cx = ckx - sx * ckz, cy = cky - sy * ckz; + + // scaled barycentric coordinates (signed edge functions); the shear makes a + // shared edge evaluate identically for both adjacent triangles, so the ray + // can never fall between them + + const u = cx * by - cy * bx; + const v = ax * cy - ay * cx; + const w = bx * ay - by * ax; + + if ( backfaceCulling ) { + + if ( u < 0 || v < 0 || w < 0 ) return null; + + } else { + + if ( ( u < 0 || v < 0 || w < 0 ) && ( u > 0 || v > 0 || w > 0 ) ) return null; + + } + + const det = u + v + w; + + // ray is co-planar with the triangle + + if ( det === 0 ) return null; + + // scaled hit distance; t = tScaled / det must lie in front of the origin + + const tScaled = sz * ( u * akz + v * bkz + w * ckz ); + + if ( det > 0 ? tScaled < 0 : tScaled > 0 ) return null; + + return this.at( tScaled / det, target ); + + } + + /** + * Transforms this ray with the given 4x4 transformation matrix. + * + * @param {Matrix4} matrix4 - The transformation matrix. + * @return {Ray} A reference to this ray. + */ + applyMatrix4( matrix4 ) { + + this.origin.applyMatrix4( matrix4 ); + this.direction.transformDirection( matrix4 ); + + return this; + + } + + /** + * Returns `true` if this ray is equal with the given one. + * + * @param {Ray} ray - The ray to test for equality. + * @return {boolean} Whether this ray is equal with the given one. + */ + equals( ray ) { + + return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction ); + + } + + /** + * Returns a new ray with copied values from this instance. + * + * @return {Ray} A clone of this instance. + */ + clone() { + + return new this.constructor().copy( this ); + + } + +} + +/** + * A material for drawing geometries in a simple shaded (flat or wireframe) way. + * + * This material is not affected by lights. + * + * @augments Material + * @demo scenes/material-browser.html#MeshBasicMaterial + */ +class MeshBasicMaterial extends Material { + + /** + * Constructs a new mesh basic material. + * + * @param {Object} [parameters] - An object with one or more properties + * defining the material's appearance. Any property of the material + * (including any property from inherited materials) can be passed + * in here. Color values can be passed any type of value accepted + * by {@link Color#set}. + */ + constructor( parameters ) { + + super(); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isMeshBasicMaterial = true; + + this.type = 'MeshBasicMaterial'; + + /** + * Color of the material. + * + * @type {Color} + * @default (1,1,1) + */ + this.color = new Color( 0xffffff ); // diffuse + + /** + * The color map. May optionally include an alpha channel, typically combined + * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map + * color is modulated by the diffuse `color`. + * + * `map` represents color data, and the texture must be assigned a + * {@link Texture#colorSpace}. Most `map` textures set + * `texture.colorSpace = SRGBColorSpace`. + * + * @type {?Texture} + * @default null + */ + this.map = null; + + /** + * The light map. Requires a second set of UVs. + * + * `lightMap` represents pre-baked illuminance data, and the texture must be assigned + * a {@link Texture#colorSpace}. Most `lightMap` textures set + * `texture.colorSpace = LinearSRGBColorSpace` and use float-type formats + * such as `.exr` or `.hdr`. + * + * @type {?Texture} + * @default null + */ + this.lightMap = null; + + /** + * Intensity of the baked light. + * + * @type {number} + * @default 1 + */ + this.lightMapIntensity = 1.0; + + /** + * The red channel of this texture is used as the ambient occlusion map. + * Requires a second set of UVs. + * + * `aoMap` represents non-color data. Any texture assigned must have + * `texture.colorSpace = NoColorSpace` (default). + * + * @type {?Texture} + * @default null + */ + this.aoMap = null; + + /** + * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0` + * disables ambient occlusion. Where intensity is `1` and the AO map's + * red channel is also `1`, ambient light is fully occluded on a surface. + * + * @type {number} + * @default 1 + */ + this.aoMapIntensity = 1.0; + + /** + * Specular map used by the material. + * + * `specularMap` represents color data, and the texture must be assigned a + * {@link Texture#colorSpace}. Most `specularMap` textures set + * `texture.colorSpace = SRGBColorSpace`. + * + * @type {?Texture} + * @default null + */ + this.specularMap = null; + + /** + * The alpha map is a grayscale texture that controls the opacity across the + * surface (black: fully transparent; white: fully opaque). + * + * Only the color of the texture is used, ignoring the alpha channel if one + * exists. For RGB and RGBA textures, the renderer will use the green channel + * when sampling this texture due to the extra bit of precision provided for + * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and + * luminance/alpha textures will also still work as expected. + * + * `alphaMap` represents non-color data. Any texture assigned must have + * `texture.colorSpace = NoColorSpace` (default). + * + * @type {?Texture} + * @default null + */ + this.alphaMap = null; + + /** + * The environment map. + * + * `envMap` represents luminance data, and the texture must be assigned + * a {@link Texture#colorSpace}. Most `envMap` textures set + * `texture.colorSpace = LinearSRGBColorSpace` and use float-type formats + * such as `.exr` or `.hdr`. + * + * @type {?Texture} + * @default null + */ + this.envMap = null; + + /** + * The rotation of the environment map in radians. + * + * @type {Euler} + * @default (0,0,0) + */ + this.envMapRotation = new Euler(); + + /** + * How to combine the result of the surface's color with the environment map, if any. + * + * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to + * blend between the two colors. + * + * @type {(MultiplyOperation|MixOperation|AddOperation)} + * @default MultiplyOperation + */ + this.combine = MultiplyOperation; + + /** + * How much the environment map affects the surface. + * The valid range is between `0` (no reflections) and `1` (full reflections). + * + * @type {number} + * @default 1 + */ + this.reflectivity = 1; + + /** + * The index of refraction (IOR) of air (approximately 1) divided by the + * index of refraction of the material. It is used with environment mapping + * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}. + * The refraction ratio should not exceed `1`. + * + * @type {number} + * @default 0.98 + */ + this.refractionRatio = 0.98; + + /** + * Renders the geometry as a wireframe. + * + * @type {boolean} + * @default false + */ + this.wireframe = false; + + /** + * Controls the thickness of the wireframe. + * + * Can only be used with {@link SVGRenderer}. + * + * @type {number} + * @default 1 + */ + this.wireframeLinewidth = 1; + + /** + * Defines appearance of wireframe ends. + * + * Can only be used with {@link SVGRenderer}. + * + * @type {('round'|'bevel'|'miter')} + * @default 'round' + */ + this.wireframeLinecap = 'round'; + + /** + * Defines appearance of wireframe joints. + * + * Can only be used with {@link SVGRenderer}. + * + * @type {('round'|'bevel'|'miter')} + * @default 'round' + */ + this.wireframeLinejoin = 'round'; + + /** + * Whether the material is affected by fog or not. + * + * @type {boolean} + * @default true + */ + this.fog = true; + + this.setValues( parameters ); + + } + + copy( source ) { + + super.copy( source ); + + this.color.copy( source.color ); + + this.map = source.map; + + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; + + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + + this.specularMap = source.specularMap; + + this.alphaMap = source.alphaMap; + + this.envMap = source.envMap; + this.envMapRotation.copy( source.envMapRotation ); + this.combine = source.combine; + this.reflectivity = source.reflectivity; + this.refractionRatio = source.refractionRatio; + + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + + this.fog = source.fog; + + return this; + + } + +} + +const _inverseMatrix$3 = /*@__PURE__*/ new Matrix4(); +const _ray$3 = /*@__PURE__*/ new Ray(); +const _sphere$6 = /*@__PURE__*/ new Sphere(); +const _sphereHitAt = /*@__PURE__*/ new Vector3(); + +const _vA = /*@__PURE__*/ new Vector3(); +const _vB = /*@__PURE__*/ new Vector3(); +const _vC = /*@__PURE__*/ new Vector3(); + +const _tempA = /*@__PURE__*/ new Vector3(); +const _morphA = /*@__PURE__*/ new Vector3(); + +const _intersectionPoint = /*@__PURE__*/ new Vector3(); +const _intersectionPointWorld = /*@__PURE__*/ new Vector3(); + +/** + * Class representing triangular polygon mesh based objects. + * + * ```js + * const geometry = new THREE.BoxGeometry( 1, 1, 1 ); + * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } ); + * const mesh = new THREE.Mesh( geometry, material ); + * scene.add( mesh ); + * ``` + * + * @augments Object3D + */ +class Mesh extends Object3D { + + /** + * Constructs a new mesh. + * + * @param {BufferGeometry} [geometry] - The mesh geometry. + * @param {Material|Array} [material] - The mesh material. + */ + constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) { + + super(); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isMesh = true; + + this.type = 'Mesh'; + + /** + * The mesh geometry. + * + * @type {BufferGeometry} + */ + this.geometry = geometry; + + /** + * The mesh material. + * + * @type {Material|Array} + * @default MeshBasicMaterial + */ + this.material = material; + + /** + * A dictionary representing the morph targets in the geometry. The key is the + * morph targets name, the value its attribute index. This member is `undefined` + * by default and only set when morph targets are detected in the geometry. + * + * @type {Object|undefined} + * @default undefined + */ + this.morphTargetDictionary = undefined; + + /** + * An array of weights typically in the range `[0,1]` that specify how much of the morph + * is applied. This member is `undefined` by default and only set when morph targets are + * detected in the geometry. + * + * @type {Array|undefined} + * @default undefined + */ + this.morphTargetInfluences = undefined; + + /** + * The number of instances of this mesh. + * Can only be used with {@link WebGPURenderer}. + * + * @type {number} + * @default 1 + */ + this.count = 1; + + this.updateMorphTargets(); + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + if ( source.morphTargetInfluences !== undefined ) { + + this.morphTargetInfluences = source.morphTargetInfluences.slice(); + + } + + if ( source.morphTargetDictionary !== undefined ) { + + this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary ); + + } + + this.material = Array.isArray( source.material ) ? source.material.slice() : source.material; + this.geometry = source.geometry; + + return this; + + } + + /** + * Sets the values of {@link Mesh#morphTargetDictionary} and {@link Mesh#morphTargetInfluences} + * to make sure existing morph targets can influence this 3D object. + */ + updateMorphTargets() { + + const geometry = this.geometry; + + const morphAttributes = geometry.morphAttributes; + const keys = Object.keys( morphAttributes ); + + if ( keys.length > 0 ) { + + const morphAttribute = morphAttributes[ keys[ 0 ] ]; + + if ( morphAttribute !== undefined ) { + + this.morphTargetInfluences = []; + this.morphTargetDictionary = {}; + + for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) { + + const name = morphAttribute[ m ].name || String( m ); + + this.morphTargetInfluences.push( 0 ); + this.morphTargetDictionary[ name ] = m; + + } + + } + + } + + } + + /** + * Returns the local-space position of the vertex at the given index, taking into + * account the current animation state of both morph targets and skinning. + * + * @param {number} index - The vertex index. + * @param {Vector3} target - The target object that is used to store the method's result. + * @return {Vector3} The vertex position in local space. + */ + getVertexPosition( index, target ) { + + const geometry = this.geometry; + const position = geometry.attributes.position; + const morphPosition = geometry.morphAttributes.position; + const morphTargetsRelative = geometry.morphTargetsRelative; + + target.fromBufferAttribute( position, index ); + + const morphInfluences = this.morphTargetInfluences; + + if ( morphPosition && morphInfluences ) { + + _morphA.set( 0, 0, 0 ); + + for ( let i = 0, il = morphPosition.length; i < il; i ++ ) { + + const influence = morphInfluences[ i ]; + const morphAttribute = morphPosition[ i ]; + + if ( influence === 0 ) continue; + + _tempA.fromBufferAttribute( morphAttribute, index ); + + if ( morphTargetsRelative ) { + + _morphA.addScaledVector( _tempA, influence ); + + } else { + + _morphA.addScaledVector( _tempA.sub( target ), influence ); + + } + + } + + target.add( _morphA ); + + } + + return target; + + } + + /** + * Returns `true` if this mesh intersects the given frustum. + * + * @param {Frustum|FrustumArray} frustum - The frustum to test. + * @return {boolean} Whether this mesh intersects the given frustum or not. + */ + intersectsFrustum( frustum ) { + + return frustum.intersectsObject( this ); + + } + + /** + * Computes intersection points between a casted ray and this line. + * + * @param {Raycaster} raycaster - The raycaster. + * @param {Array} intersects - The target array that holds the intersection points. + */ + raycast( raycaster, intersects ) { + + const geometry = this.geometry; + const material = this.material; + const matrixWorld = this.matrixWorld; + + if ( material === undefined ) return; + + // test with bounding sphere in world space + + if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); + + _sphere$6.copy( geometry.boundingSphere ); + _sphere$6.applyMatrix4( matrixWorld ); + + // check distance from ray origin to bounding sphere + + _ray$3.copy( raycaster.ray ).recast( raycaster.near ); + + if ( _sphere$6.containsPoint( _ray$3.origin ) === false ) { + + if ( _ray$3.intersectSphere( _sphere$6, _sphereHitAt ) === null ) return; + + if ( _ray$3.origin.distanceToSquared( _sphereHitAt ) > ( raycaster.far - raycaster.near ) ** 2 ) return; + + } + + // convert ray to local space of mesh + + _inverseMatrix$3.copy( matrixWorld ).invert(); + _ray$3.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$3 ); + + // test with bounding box in local space + + if ( geometry.boundingBox !== null ) { + + if ( _ray$3.intersectsBox( geometry.boundingBox ) === false ) return; + + } + + // test for intersections with geometry + + this._computeIntersections( raycaster, intersects, _ray$3 ); + + } + + _computeIntersections( raycaster, intersects, rayLocalSpace ) { + + let intersection; + + const geometry = this.geometry; + const material = this.material; + + const index = geometry.index; + const position = geometry.attributes.position; + const uv = geometry.attributes.uv; + const uv1 = geometry.attributes.uv1; + const normal = geometry.attributes.normal; + const groups = geometry.groups; + const drawRange = geometry.drawRange; + + if ( index !== null ) { + + // indexed buffer geometry + + if ( Array.isArray( material ) ) { + + for ( let i = 0, il = groups.length; i < il; i ++ ) { + + const group = groups[ i ]; + const groupMaterial = material[ group.materialIndex ]; + + const start = Math.max( group.start, drawRange.start ); + const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) ); + + for ( let j = start, jl = end; j < jl; j += 3 ) { + + const a = index.getX( j ); + const b = index.getX( j + 1 ); + const c = index.getX( j + 2 ); + + intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c ); + + if ( intersection ) { + + intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics + intersection.face.materialIndex = group.materialIndex; + intersects.push( intersection ); + + } + + } + + } + + } else { + + const start = Math.max( 0, drawRange.start ); + const end = Math.min( index.count, ( drawRange.start + drawRange.count ) ); + + for ( let i = start, il = end; i < il; i += 3 ) { + + const a = index.getX( i ); + const b = index.getX( i + 1 ); + const c = index.getX( i + 2 ); + + intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c ); + + if ( intersection ) { + + intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics + intersects.push( intersection ); + + } + + } + + } + + } else if ( position !== undefined ) { + + // non-indexed buffer geometry + + if ( Array.isArray( material ) ) { + + for ( let i = 0, il = groups.length; i < il; i ++ ) { + + const group = groups[ i ]; + const groupMaterial = material[ group.materialIndex ]; + + const start = Math.max( group.start, drawRange.start ); + const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) ); + + for ( let j = start, jl = end; j < jl; j += 3 ) { + + const a = j; + const b = j + 1; + const c = j + 2; + + intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c ); + + if ( intersection ) { + + intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics + intersection.face.materialIndex = group.materialIndex; + intersects.push( intersection ); + + } + + } + + } + + } else { + + const start = Math.max( 0, drawRange.start ); + const end = Math.min( position.count, ( drawRange.start + drawRange.count ) ); + + for ( let i = start, il = end; i < il; i += 3 ) { + + const a = i; + const b = i + 1; + const c = i + 2; + + intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c ); + + if ( intersection ) { + + intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics + intersects.push( intersection ); + + } + + } + + } + + } + + } + +} + +function checkIntersection$1( object, material, raycaster, ray, pA, pB, pC, point ) { + + let intersect; + + if ( material.side === BackSide ) { + + intersect = ray.intersectTriangle( pC, pB, pA, true, point ); + + } else { + + intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point ); + + } + + if ( intersect === null ) return null; + + _intersectionPointWorld.copy( point ); + _intersectionPointWorld.applyMatrix4( object.matrixWorld ); + + const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld ); + + if ( distance < raycaster.near || distance > raycaster.far ) return null; + + return { + distance: distance, + point: _intersectionPointWorld.clone(), + object: object + }; + +} + +function checkGeometryIntersection( object, material, raycaster, ray, uv, uv1, normal, a, b, c ) { + + object.getVertexPosition( a, _vA ); + object.getVertexPosition( b, _vB ); + object.getVertexPosition( c, _vC ); + + const intersection = checkIntersection$1( object, material, raycaster, ray, _vA, _vB, _vC, _intersectionPoint ); + + if ( intersection ) { + + const barycoord = new Vector3(); + Triangle.getBarycoord( _intersectionPoint, _vA, _vB, _vC, barycoord ); + + if ( uv ) { + + intersection.uv = Triangle.getInterpolatedAttribute( uv, a, b, c, barycoord, new Vector2() ); + + } + + if ( uv1 ) { + + intersection.uv1 = Triangle.getInterpolatedAttribute( uv1, a, b, c, barycoord, new Vector2() ); + + } + + if ( normal ) { + + intersection.normal = Triangle.getInterpolatedAttribute( normal, a, b, c, barycoord, new Vector3() ); + + if ( intersection.normal.dot( ray.direction ) > 0 ) { + + intersection.normal.multiplyScalar( -1 ); + + } + + } + + const face = { + a: a, + b: b, + c: c, + normal: new Vector3(), + materialIndex: 0 + }; + + Triangle.getNormal( _vA, _vB, _vC, face.normal ); + + intersection.face = face; + intersection.barycoord = barycoord; + + } + + return intersection; + +} + +const _baseVector = /*@__PURE__*/ new Vector4(); + +const _skinIndex = /*@__PURE__*/ new Vector4(); +const _skinWeight = /*@__PURE__*/ new Vector4(); + +const _vector4 = /*@__PURE__*/ new Vector4(); +const _matrix4 = /*@__PURE__*/ new Matrix4(); +const _vertex = /*@__PURE__*/ new Vector3(); + +const _sphere$5 = /*@__PURE__*/ new Sphere(); +const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4(); +const _ray$2 = /*@__PURE__*/ new Ray(); + +/** + * A mesh that has a {@link Skeleton} that can then be used to animate the + * vertices of the geometry with skinning/skeleton animation. + * + * Next to a valid skeleton, the skinned mesh requires skin indices and weights + * as buffer attributes in its geometry. These attribute define which bones affect a single + * vertex to a certain extend. + * + * Typically skinned meshes are not created manually but loaders like {@link GLTFLoader} + * or {@link FBXLoader } import respective models. + * + * @augments Mesh + * @demo scenes/bones-browser.html + */ +class SkinnedMesh extends Mesh { + + /** + * Constructs a new skinned mesh. + * + * @param {BufferGeometry} [geometry] - The mesh geometry. + * @param {Material|Array} [material] - The mesh material. + */ + constructor( geometry, material ) { + + super( geometry, material ); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isSkinnedMesh = true; + + this.type = 'SkinnedMesh'; + + /** + * `AttachedBindMode` means the skinned mesh shares the same world space as the skeleton. + * This is not true when using `DetachedBindMode` which is useful when sharing a skeleton + * across multiple skinned meshes. + * + * @type {(AttachedBindMode|DetachedBindMode)} + * @default AttachedBindMode + */ + this.bindMode = AttachedBindMode; + + /** + * The base matrix that is used for the bound bone transforms. + * + * @type {Matrix4} + */ + this.bindMatrix = new Matrix4(); + + /** + * The base matrix that is used for resetting the bound bone transforms. + * + * @type {Matrix4} + */ + this.bindMatrixInverse = new Matrix4(); + + /** + * The bounding box of the skinned mesh. Can be computed via {@link SkinnedMesh#computeBoundingBox}. + * + * @type {?Box3} + * @default null + */ + this.boundingBox = null; + + /** + * The bounding sphere of the skinned mesh. Can be computed via {@link SkinnedMesh#computeBoundingSphere}. + * + * @type {?Sphere} + * @default null + */ + this.boundingSphere = null; + + } + + /** + * Computes the bounding box of the skinned mesh, and updates {@link SkinnedMesh#boundingBox}. + * The bounding box is not automatically computed by the engine; this method must be called by your app. + * If the skinned mesh is animated, the bounding box should be recomputed per frame in order to reflect + * the current animation state. + */ + computeBoundingBox() { + + const geometry = this.geometry; + + if ( this.boundingBox === null ) { + + this.boundingBox = new Box3(); + + } + + this.boundingBox.makeEmpty(); + + const positionAttribute = geometry.getAttribute( 'position' ); + + for ( let i = 0; i < positionAttribute.count; i ++ ) { + + this.getVertexPosition( i, _vertex ); + this.boundingBox.expandByPoint( _vertex ); + + } + + } + + /** + * Computes the bounding sphere of the skinned mesh, and updates {@link SkinnedMesh#boundingSphere}. + * The bounding sphere is automatically computed by the engine once when it is needed, e.g., for ray casting + * and view frustum culling. If the skinned mesh is animated, the bounding sphere should be recomputed + * per frame in order to reflect the current animation state. + */ + computeBoundingSphere() { + + const geometry = this.geometry; + + if ( this.boundingSphere === null ) { + + this.boundingSphere = new Sphere(); + + } + + this.boundingSphere.makeEmpty(); + + const positionAttribute = geometry.getAttribute( 'position' ); + + for ( let i = 0; i < positionAttribute.count; i ++ ) { + + this.getVertexPosition( i, _vertex ); + this.boundingSphere.expandByPoint( _vertex ); + + } + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + this.bindMode = source.bindMode; + this.bindMatrix.copy( source.bindMatrix ); + this.bindMatrixInverse.copy( source.bindMatrixInverse ); + + this.skeleton = source.skeleton; + + if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone(); + if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone(); + + return this; + + } + + raycast( raycaster, intersects ) { + + const material = this.material; + const matrixWorld = this.matrixWorld; + + if ( material === undefined ) return; + + // test with bounding sphere in world space + + if ( this.boundingSphere === null ) this.computeBoundingSphere(); + + _sphere$5.copy( this.boundingSphere ); + _sphere$5.applyMatrix4( matrixWorld ); + + if ( raycaster.ray.intersectsSphere( _sphere$5 ) === false ) return; + + // convert ray to local space of skinned mesh + + _inverseMatrix$2.copy( matrixWorld ).invert(); + _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 ); + + // test with bounding box in local space + + if ( this.boundingBox !== null ) { + + if ( _ray$2.intersectsBox( this.boundingBox ) === false ) return; + + } + + // test for intersections with geometry + + this._computeIntersections( raycaster, intersects, _ray$2 ); + + } + + getVertexPosition( index, target ) { + + super.getVertexPosition( index, target ); + + this.applyBoneTransform( index, target ); + + return target; + + } + + /** + * Binds the given skeleton to the skinned mesh. + * + * @param {Skeleton} skeleton - The skeleton to bind. + * @param {Matrix4} [bindMatrix] - The bind matrix. If no bind matrix is provided, + * the skinned mesh's world matrix will be used instead. + */ + bind( skeleton, bindMatrix ) { + + this.skeleton = skeleton; + + if ( bindMatrix === undefined ) { + + this.updateMatrixWorld( true ); + + this.skeleton.calculateInverses(); + + bindMatrix = this.matrixWorld; + + } + + this.bindMatrix.copy( bindMatrix ); + this.bindMatrixInverse.copy( bindMatrix ).invert(); + + } + + /** + * This method sets the skinned mesh in the rest pose). + */ + pose() { + + this.skeleton.pose(); + + } + + /** + * Normalizes the skin weights which are defined as a buffer attribute + * in the skinned mesh's geometry. + */ + normalizeSkinWeights() { + + const vector = new Vector4(); + + const skinWeight = this.geometry.attributes.skinWeight; + + for ( let i = 0, l = skinWeight.count; i < l; i ++ ) { + + vector.fromBufferAttribute( skinWeight, i ); + + const scale = 1.0 / vector.manhattanLength(); + + if ( scale !== Infinity ) { + + vector.multiplyScalar( scale ); + + } else { + + vector.set( 1, 0, 0, 0 ); // do something reasonable + + } + + skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w ); + + } + + } + + updateMatrixWorld( force ) { + + super.updateMatrixWorld( force ); + + if ( this.bindMode === AttachedBindMode ) { + + this.bindMatrixInverse.copy( this.matrixWorld ).invert(); + + } else if ( this.bindMode === DetachedBindMode ) { + + this.bindMatrixInverse.copy( this.bindMatrix ).invert(); + + } else { + + warn( 'SkinnedMesh: Unrecognized bindMode: ' + this.bindMode ); + + } + + } + + /** + * Applies the bone transform associated with the given index to the given + * vector. Can be used to transform positions or direction vectors by providing + * a Vector4 with 1 or 0 in the w component respectively. Returns the updated vector. + * + * @param {number} index - The vertex index. + * @param {Vector3|Vector4} target - The target object that is used to store the method's result. + * @return {Vector3|Vector4} The updated vertex attribute data. + */ + applyBoneTransform( index, target ) { + + const skeleton = this.skeleton; + const geometry = this.geometry; + + _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index ); + _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index ); + + if ( target.isVector4 ) { + + _baseVector.copy( target ); + target.set( 0, 0, 0, 0 ); + + } else { + + _baseVector.set( ...target, 1 ); + target.set( 0, 0, 0 ); + + } + + _baseVector.applyMatrix4( this.bindMatrix ); + + for ( let i = 0; i < 4; i ++ ) { + + const weight = _skinWeight.getComponent( i ); + + if ( weight !== 0 ) { + + const boneIndex = _skinIndex.getComponent( i ); + + _matrix4.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] ); + + target.addScaledVector( _vector4.copy( _baseVector ).applyMatrix4( _matrix4 ), weight ); + + } + + } + + if ( target.isVector4 ) { + + // ensure the homogenous coordinate remains unchanged after vector operations + target.w = _baseVector.w; + + } + + return target.applyMatrix4( this.bindMatrixInverse ); + + } + +} + +/** + * A bone which is part of a {@link Skeleton}. The skeleton in turn is used by + * the {@link SkinnedMesh}. + * + * ```js + * const root = new THREE.Bone(); + * const child = new THREE.Bone(); + * + * root.add( child ); + * child.position.y = 5; + * ``` + * + * @augments Object3D + */ +class Bone extends Object3D { + + /** + * Constructs a new bone. + */ + constructor() { + + super(); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isBone = true; + + this.type = 'Bone'; + + } + +} + +/** + * Creates a texture directly from raw buffer data. + * + * The interpretation of the data depends on type and format: If the type is + * `UnsignedByteType`, a `Uint8Array` will be useful for addressing the + * texel data. If the format is `RGBAFormat`, data needs four values for + * one texel; Red, Green, Blue and Alpha (typically the opacity). + * + * @augments Texture + */ +class DataTexture extends Texture { + + /** + * Constructs a new data texture. + * + * @param {?TypedArray} [data=null] - The buffer data. + * @param {number} [width=1] - The width of the texture. + * @param {number} [height=1] - The height of the texture. + * @param {number} [format=RGBAFormat] - The texture format. + * @param {number} [type=UnsignedByteType] - The texture type. + * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping. + * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value. + * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value. + * @param {number} [magFilter=NearestFilter] - The mag filter value. + * @param {number} [minFilter=NearestFilter] - The min filter value. + * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value. + * @param {string} [colorSpace=NoColorSpace] - The color space. + */ + constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, colorSpace ) { + + super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace ); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isDataTexture = true; + + /** + * The image definition of a data texture. + * + * @type {{data:TypedArray,width:number,height:number}} + */ + this.image = { data: data, width: width, height: height }; + + /** + * Whether to generate mipmaps (if possible) for a texture. + * + * Overwritten and set to `false` by default. + * + * @type {boolean} + * @default false + */ + this.generateMipmaps = false; + + /** + * If set to `true`, the texture is flipped along the vertical axis when + * uploaded to the GPU. + * + * Overwritten and set to `false` by default. + * + * @type {boolean} + * @default false + */ + this.flipY = false; + + /** + * Specifies the alignment requirements for the start of each pixel row in memory. + * + * Overwritten and set to `1` by default. + * + * @type {boolean} + * @default 1 + */ + this.unpackAlignment = 1; + + } + +} + +const _offsetMatrix = /*@__PURE__*/ new Matrix4(); +const _identityMatrix = /*@__PURE__*/ new Matrix4(); + +/** + * Class for representing the armatures in `three.js`. The skeleton + * is defined by a hierarchy of bones. + * + * ```js + * const bones = []; + * + * const shoulder = new THREE.Bone(); + * const elbow = new THREE.Bone(); + * const hand = new THREE.Bone(); + * + * shoulder.add( elbow ); + * elbow.add( hand ); + * + * bones.push( shoulder , elbow, hand); + * + * shoulder.position.y = -5; + * elbow.position.y = 0; + * hand.position.y = 5; + * + * const armSkeleton = new THREE.Skeleton( bones ); + * ``` + */ +class Skeleton { + + /** + * Constructs a new skeleton. + * + * @param {Array} [bones] - An array of bones. + * @param {Array} [boneInverses] - An array of bone inverse matrices. + * If not provided, these matrices will be computed automatically via {@link Skeleton#calculateInverses}. + */ + constructor( bones = [], boneInverses = [] ) { + + this.uuid = generateUUID(); + + /** + * An array of bones defining the skeleton. + * + * @type {Array} + */ + this.bones = bones.slice( 0 ); + + /** + * An array of bone inverse matrices. + * + * @type {Array} + */ + this.boneInverses = boneInverses; + + /** + * An array buffer holding the bone data. + * Input data for {@link Skeleton#boneTexture}. + * + * @type {?Float32Array} + * @default null + */ + this.boneMatrices = null; + + /** + * A texture holding the bone data for use + * in the vertex shader. + * + * @type {?DataTexture} + * @default null + */ + this.boneTexture = null; + + this.init(); + + } + + /** + * Initializes the skeleton. This method gets automatically called by the constructor + * but depending on how the skeleton is created it might be necessary to call this method + * manually. + */ + init() { + + const bones = this.bones; + const boneInverses = this.boneInverses; + + this.boneMatrices = new Float32Array( bones.length * 16 ); + + // calculate inverse bone matrices if necessary + + if ( boneInverses.length === 0 ) { + + this.calculateInverses(); + + } else { + + // handle special case + + if ( bones.length !== boneInverses.length ) { + + warn( 'Skeleton: Number of inverse bone matrices does not match amount of bones.' ); + + this.boneInverses = []; + + for ( let i = 0, il = this.bones.length; i < il; i ++ ) { + + this.boneInverses.push( new Matrix4() ); + + } + + } + + } + + } + + /** + * Computes the bone inverse matrices. This method resets {@link Skeleton#boneInverses} + * and fills it with new matrices. + */ + calculateInverses() { + + this.boneInverses.length = 0; + + for ( let i = 0, il = this.bones.length; i < il; i ++ ) { + + const inverse = new Matrix4(); + + if ( this.bones[ i ] ) { + + inverse.copy( this.bones[ i ].matrixWorld ).invert(); + + } + + this.boneInverses.push( inverse ); + + } + + } + + /** + * Resets the skeleton to the base pose. + */ + pose() { + + // recover the bind-time world matrices + + for ( let i = 0, il = this.bones.length; i < il; i ++ ) { + + const bone = this.bones[ i ]; + + if ( bone ) { + + bone.matrixWorld.copy( this.boneInverses[ i ] ).invert(); + + } + + } + + // compute the local matrices, positions, rotations and scales + + for ( let i = 0, il = this.bones.length; i < il; i ++ ) { + + const bone = this.bones[ i ]; + + if ( bone ) { + + if ( bone.parent && bone.parent.isBone ) { + + bone.matrix.copy( bone.parent.matrixWorld ).invert(); + bone.matrix.multiply( bone.matrixWorld ); + + } else { + + bone.matrix.copy( bone.matrixWorld ); + + } + + bone.matrix.decompose( bone.position, bone.quaternion, bone.scale ); + + } + + } + + } + + /** + * Resets the skeleton to the base pose. + */ + update() { + + const bones = this.bones; + const boneInverses = this.boneInverses; + const boneMatrices = this.boneMatrices; + const boneTexture = this.boneTexture; + + // flatten bone matrices to array + + for ( let i = 0, il = bones.length; i < il; i ++ ) { + + // compute the offset between the current and the original transform + + const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix; + + _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] ); + _offsetMatrix.toArray( boneMatrices, i * 16 ); + + } + + if ( boneTexture !== null ) { + + boneTexture.needsUpdate = true; + + } + + } + + /** + * Returns a new skeleton with copied values from this instance. + * + * @return {Skeleton} A clone of this instance. + */ + clone() { + + return new Skeleton( this.bones, this.boneInverses ); + + } + + /** + * Computes a data texture for passing bone data to the vertex shader. + * + * @return {Skeleton} A reference of this instance. + */ + computeBoneTexture() { + + // layout (1 matrix = 4 pixels) + // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4) + // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8) + // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16) + // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32) + // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64) + + let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix + size = Math.ceil( size / 4 ) * 4; + size = Math.max( size, 4 ); + + const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel + boneMatrices.set( this.boneMatrices ); // copy current values + + const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType ); + boneTexture.needsUpdate = true; + + this.boneMatrices = boneMatrices; + this.boneTexture = boneTexture; + + return this; + + } + + /** + * Searches through the skeleton's bone array and returns the first with a + * matching name. + * + * @param {string} name - The name of the bone. + * @return {Bone|undefined} The found bone. `undefined` if no bone has been found. + */ + getBoneByName( name ) { + + for ( let i = 0, il = this.bones.length; i < il; i ++ ) { + + const bone = this.bones[ i ]; + + if ( bone.name === name ) { + + return bone; + + } + + } + + return undefined; + + } + + /** + * Frees the GPU-related resources allocated by this instance. Call this + * method whenever this instance is no longer used in your app. + */ + dispose( ) { + + if ( this.boneTexture !== null ) { + + this.boneTexture.dispose(); + + this.boneTexture = null; + + } + + } + + /** + * Setups the skeleton by the given JSON and bones. + * + * @param {Object} json - The skeleton as serialized JSON. + * @param {Object} bones - An array of bones. + * @return {Skeleton} A reference of this instance. + */ + fromJSON( json, bones ) { + + this.uuid = json.uuid; + + for ( let i = 0, l = json.bones.length; i < l; i ++ ) { + + const uuid = json.bones[ i ]; + let bone = bones[ uuid ]; + + if ( bone === undefined ) { + + warn( 'Skeleton: No bone found with UUID:', uuid ); + bone = new Bone(); + + } + + this.bones.push( bone ); + this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) ); + + } + + this.init(); + + return this; + + } + + /** + * Serializes the skeleton into JSON. + * + * @return {Object} A JSON object representing the serialized skeleton. + * @see {@link ObjectLoader#parse} + */ + toJSON() { + + const data = { + metadata: { + version: 4.7, + type: 'Skeleton', + generator: 'Skeleton.toJSON' + }, + bones: [], + boneInverses: [] + }; + + data.uuid = this.uuid; + + const bones = this.bones; + const boneInverses = this.boneInverses; + + for ( let i = 0, l = bones.length; i < l; i ++ ) { + + const bone = bones[ i ]; + data.bones.push( bone.uuid ); + + const boneInverse = boneInverses[ i ]; + data.boneInverses.push( boneInverse.toArray() ); + + } + + return data; + + } + +} + +/** + * An instanced version of a buffer attribute. + * + * @augments BufferAttribute + */ +class InstancedBufferAttribute extends BufferAttribute { + + /** + * Constructs a new instanced buffer attribute. + * + * @param {TypedArray} array - The array holding the attribute data. + * @param {number} itemSize - The item size. + * @param {boolean} [normalized=false] - Whether the data are normalized or not. + * @param {number} [meshPerAttribute=1] - How often a value of this buffer attribute should be repeated. + */ + constructor( array, itemSize, normalized, meshPerAttribute = 1 ) { + + super( array, itemSize, normalized ); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isInstancedBufferAttribute = true; + + /** + * Defines how often a value of this buffer attribute should be repeated. A + * value of one means that each value of the instanced attribute is used for + * a single instance. A value of two means that each value is used for two + * consecutive instances (and so on). + * + * @type {number} + * @default 1 + */ + this.meshPerAttribute = meshPerAttribute; + + } + + copy( source ) { + + super.copy( source ); + + this.meshPerAttribute = source.meshPerAttribute; + + return this; + + } + + toJSON() { + + const data = super.toJSON(); + + data.meshPerAttribute = this.meshPerAttribute; + + data.isInstancedBufferAttribute = true; + + return data; + + } + +} + +const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4(); +const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4(); + +const _instanceIntersects = []; + +const _box3 = /*@__PURE__*/ new Box3(); +const _identity = /*@__PURE__*/ new Matrix4(); +const _mesh$1 = /*@__PURE__*/ new Mesh(); +const _sphere$4 = /*@__PURE__*/ new Sphere(); + +/** + * A special version of a mesh with instanced rendering support. Use + * this class if you have to render a large number of objects with the same + * geometry and material(s) but with different world transformations. The usage + * of 'InstancedMesh' will help you to reduce the number of draw calls and thus + * improve the overall rendering performance in your application. + * + * @augments Mesh + */ +class InstancedMesh extends Mesh { + + /** + * Constructs a new instanced mesh. + * + * @param {BufferGeometry} [geometry] - The mesh geometry. + * @param {Material|Array} [material] - The mesh material. + * @param {number} count - The number of instances. + */ + constructor( geometry, material, count ) { + + super( geometry, material ); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isInstancedMesh = true; + + /** + * Represents the local transformation of all instances. You have to set its + * {@link BufferAttribute#needsUpdate} flag to true if you modify instanced data + * via {@link InstancedMesh#setMatrixAt}. + * + * @type {InstancedBufferAttribute} + */ + this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 ); + + /** + * Represents the color of all instances. You have to set its + * {@link BufferAttribute#needsUpdate} flag to true if you modify instanced data + * via {@link InstancedMesh#setColorAt}. + * + * @type {?InstancedBufferAttribute} + * @default null + */ + this.instanceColor = null; + + /** + * Represents the morph target weights of all instances. You have to set its + * {@link Texture#needsUpdate} flag to true if you modify instanced data + * via {@link InstancedMesh#setMorphAt}. + * + * @type {?DataTexture} + * @default null + */ + this.morphTexture = null; + + /** + * The number of instances. + * + * @type {number} + */ + this.count = count; + + /** + * The bounding box of the instanced mesh. Can be computed via {@link InstancedMesh#computeBoundingBox}. + * + * @type {?Box3} + * @default null + */ + this.boundingBox = null; + + /** + * The bounding sphere of the instanced mesh. Can be computed via {@link InstancedMesh#computeBoundingSphere}. + * + * @type {?Sphere} + * @default null + */ + this.boundingSphere = null; + + for ( let i = 0; i < count; i ++ ) { + + this.setMatrixAt( i, _identity ); + + } + + } + + /** + * Computes the bounding box of the instanced mesh, and updates {@link InstancedMesh#boundingBox}. + * The bounding box is not automatically computed by the engine; this method must be called by your app. + * You may need to recompute the bounding box if an instance is transformed via {@link InstancedMesh#setMatrixAt}. + */ + computeBoundingBox() { + + const geometry = this.geometry; + const count = this.count; + + if ( this.boundingBox === null ) { + + this.boundingBox = new Box3(); + + } + + if ( geometry.boundingBox === null ) { + + geometry.computeBoundingBox(); + + } + + this.boundingBox.makeEmpty(); + + for ( let i = 0; i < count; i ++ ) { + + this.getMatrixAt( i, _instanceLocalMatrix ); + + _box3.copy( geometry.boundingBox ).applyMatrix4( _instanceLocalMatrix ); + + this.boundingBox.union( _box3 ); + + } + + } + + /** + * Computes the bounding sphere of the instanced mesh, and updates {@link InstancedMesh#boundingSphere} + * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling. + * You may need to recompute the bounding sphere if an instance is transformed via {@link InstancedMesh#setMatrixAt}. + */ + computeBoundingSphere() { + + const geometry = this.geometry; + const count = this.count; + + if ( this.boundingSphere === null ) { + + this.boundingSphere = new Sphere(); + + } + + if ( geometry.boundingSphere === null ) { + + geometry.computeBoundingSphere(); + + } + + this.boundingSphere.makeEmpty(); + + for ( let i = 0; i < count; i ++ ) { + + this.getMatrixAt( i, _instanceLocalMatrix ); + + _sphere$4.copy( geometry.boundingSphere ).applyMatrix4( _instanceLocalMatrix ); + + this.boundingSphere.union( _sphere$4 ); + + } + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + this.instanceMatrix.copy( source.instanceMatrix ); + + if ( source.morphTexture !== null ) this.morphTexture = source.morphTexture.clone(); + if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone(); + + this.count = source.count; + + if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone(); + if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone(); + + return this; + + } + + /** + * Gets the color of the defined instance. + * + * @param {number} index - The instance index. + * @param {Color} color - The target object that is used to store the method's result. + * @return {Color} A reference to the target color. + */ + getColorAt( index, color ) { + + if ( this.instanceColor === null ) { + + return color.setRGB( 1, 1, 1 ); + + } else { + + return color.fromArray( this.instanceColor.array, index * 3 ); + + } + + } + + /** + * Gets the local transformation matrix of the defined instance. + * + * @param {number} index - The instance index. + * @param {Matrix4} matrix - The target object that is used to store the method's result. + * @return {Matrix4} A reference to the target matrix. + */ + getMatrixAt( index, matrix ) { + + return matrix.fromArray( this.instanceMatrix.array, index * 16 ); + + } + + /** + * Gets the morph target weights of the defined instance. + * + * @param {number} index - The instance index. + * @param {Mesh} object - The target object that is used to store the method's result. + */ + getMorphAt( index, object ) { + + const objectInfluences = object.morphTargetInfluences; + + const array = this.morphTexture.source.data.data; + + const len = objectInfluences.length + 1; // All influences + the baseInfluenceSum + + const dataIndex = index * len + 1; // Skip the baseInfluenceSum at the beginning + + for ( let i = 0; i < objectInfluences.length; i ++ ) { + + objectInfluences[ i ] = array[ dataIndex + i ]; + + } + + } + + raycast( raycaster, intersects ) { + + const matrixWorld = this.matrixWorld; + const raycastTimes = this.count; + + _mesh$1.geometry = this.geometry; + _mesh$1.material = this.material; + + if ( _mesh$1.material === undefined ) return; + + // test with bounding sphere first + + if ( this.boundingSphere === null ) this.computeBoundingSphere(); + + _sphere$4.copy( this.boundingSphere ); + _sphere$4.applyMatrix4( matrixWorld ); + + if ( raycaster.ray.intersectsSphere( _sphere$4 ) === false ) return; + + // now test each instance + + for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) { + + // calculate the world matrix for each instance + + this.getMatrixAt( instanceId, _instanceLocalMatrix ); + + _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix ); + + // the mesh represents this single instance + + _mesh$1.matrixWorld = _instanceWorldMatrix; + + _mesh$1.raycast( raycaster, _instanceIntersects ); + + // process the result of raycast + + for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) { + + const intersect = _instanceIntersects[ i ]; + intersect.instanceId = instanceId; + intersect.object = this; + intersects.push( intersect ); + + } + + _instanceIntersects.length = 0; + + } + + } + + /** + * Sets the given color to the defined instance. Make sure you set the `needsUpdate` flag of + * {@link InstancedMesh#instanceColor} to `true` after updating all the colors. + * + * @param {number} index - The instance index. + * @param {Color} color - The instance color. + * @return {InstancedMesh} A reference to this instanced mesh. + */ + setColorAt( index, color ) { + + if ( this.instanceColor === null ) { + + this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ).fill( 1 ), 3 ); + + } + + color.toArray( this.instanceColor.array, index * 3 ); + return this; + + } + + /** + * Sets the given local transformation matrix to the defined instance. Make sure you set the `needsUpdate` flag of + * {@link InstancedMesh#instanceMatrix} to `true` after updating all the matrices. + * + * @param {number} index - The instance index. + * @param {Matrix4} matrix - The local transformation. + * @return {InstancedMesh} A reference to this instanced mesh. + */ + setMatrixAt( index, matrix ) { + + matrix.toArray( this.instanceMatrix.array, index * 16 ); + return this; + + } + + /** + * Sets the morph target weights to the defined instance. Make sure you set the `needsUpdate` flag of + * {@link InstancedMesh#morphTexture} to `true` after updating all the influences. + * + * @param {number} index - The instance index. + * @param {Mesh} object - A mesh which `morphTargetInfluences` property containing the morph target weights + * of a single instance. + * @return {InstancedMesh} A reference to this instanced mesh. + */ + setMorphAt( index, object ) { + + const objectInfluences = object.morphTargetInfluences; + + const len = objectInfluences.length + 1; // morphBaseInfluence + all influences + + if ( this.morphTexture === null ) { + + this.morphTexture = new DataTexture( new Float32Array( len * this.count ), len, this.count, RedFormat, FloatType ); + + } + + const array = this.morphTexture.source.data.data; + + let morphInfluencesSum = 0; + + for ( let i = 0; i < objectInfluences.length; i ++ ) { + + morphInfluencesSum += objectInfluences[ i ]; + + } + + const morphBaseInfluence = this.geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum; + + const dataIndex = len * index; + + array[ dataIndex ] = morphBaseInfluence; + + array.set( objectInfluences, dataIndex + 1 ); + return this; + + } + + updateMorphTargets() { + + } + + /** + * Frees the GPU-related resources allocated by this instance. Call this + * method whenever this instance is no longer used in your app. + */ + dispose() { + + super.dispose(); + + if ( this.morphTexture !== null ) { + + this.morphTexture.dispose(); + this.morphTexture = null; + + } + + } + +} + +const _sphere$3 = /*@__PURE__*/ new Sphere(); +const _defaultSpriteCenter = /*@__PURE__*/ new Vector2( 0.5, 0.5 ); +const _vector$6 = /*@__PURE__*/ new Vector3(); + +/** + * Frustums are used to determine what is inside the camera's field of view. + * They help speed up the rendering process - objects which lie outside a camera's + * frustum can safely be excluded from rendering. + * + * This class is mainly intended for use internally by a renderer. + */ +class Frustum { + + /** + * Constructs a new frustum. + * + * @param {Plane} [p0] - The first plane that encloses the frustum. + * @param {Plane} [p1] - The second plane that encloses the frustum. + * @param {Plane} [p2] - The third plane that encloses the frustum. + * @param {Plane} [p3] - The fourth plane that encloses the frustum. + * @param {Plane} [p4] - The fifth plane that encloses the frustum. + * @param {Plane} [p5] - The sixth plane that encloses the frustum. + */ + constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) { + + /** + * This array holds the planes that enclose the frustum. + * + * @type {Array} + */ + this.planes = [ p0, p1, p2, p3, p4, p5 ]; + + } + + /** + * Sets the frustum planes by copying the given planes. + * + * @param {Plane} [p0] - The first plane that encloses the frustum. + * @param {Plane} [p1] - The second plane that encloses the frustum. + * @param {Plane} [p2] - The third plane that encloses the frustum. + * @param {Plane} [p3] - The fourth plane that encloses the frustum. + * @param {Plane} [p4] - The fifth plane that encloses the frustum. + * @param {Plane} [p5] - The sixth plane that encloses the frustum. + * @return {Frustum} A reference to this frustum. + */ + set( p0, p1, p2, p3, p4, p5 ) { + + const planes = this.planes; + + planes[ 0 ].copy( p0 ); + planes[ 1 ].copy( p1 ); + planes[ 2 ].copy( p2 ); + planes[ 3 ].copy( p3 ); + planes[ 4 ].copy( p4 ); + planes[ 5 ].copy( p5 ); + + return this; + + } + + /** + * Copies the values of the given frustum to this instance. + * + * @param {Frustum} frustum - The frustum to copy. + * @return {Frustum} A reference to this frustum. + */ + copy( frustum ) { + + const planes = this.planes; + + for ( let i = 0; i < 6; i ++ ) { + + planes[ i ].copy( frustum.planes[ i ] ); + + } + + return this; + + } + + /** + * Sets the frustum planes from the given projection matrix. + * + * @param {Matrix4} m - The projection matrix. + * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} coordinateSystem - The coordinate system. + * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth. + * @return {Frustum} A reference to this frustum. + */ + setFromProjectionMatrix( m, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) { + + const planes = this.planes; + const me = m.elements; + const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ]; + const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ]; + const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ]; + const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ]; + + planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize(); + planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize(); + planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize(); + planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize(); + + if ( reversedDepth ) { + + planes[ 4 ].setComponents( me2, me6, me10, me14 ).normalize(); // far + planes[ 5 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize(); // near + + } else { + + planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize(); // far + + if ( coordinateSystem === WebGLCoordinateSystem ) { + + planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize(); // near + + } else if ( coordinateSystem === WebGPUCoordinateSystem ) { + + planes[ 5 ].setComponents( me2, me6, me10, me14 ).normalize(); // near + + } else { + + throw new Error( 'THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: ' + coordinateSystem ); + + } + + } + + return this; + + } + + /** + * Returns `true` if the 3D object's bounding sphere is intersecting this frustum. + * + * Note that the 3D object must have a geometry so that the bounding sphere can be calculated. + * + * @param {Object3D} object - The 3D object to test. + * @return {boolean} Whether the 3D object's bounding sphere is intersecting this frustum or not. + */ + intersectsObject( object ) { + + if ( object.boundingSphere !== undefined ) { + + if ( object.boundingSphere === null ) object.computeBoundingSphere(); + + _sphere$3.copy( object.boundingSphere ).applyMatrix4( object.matrixWorld ); + + } else { + + const geometry = object.geometry; + + if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); + + _sphere$3.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld ); + + } + + return this.intersectsSphere( _sphere$3 ); + + } + + /** + * Returns `true` if the given sprite is intersecting this frustum. + * + * @param {Sprite} sprite - The sprite to test. + * @return {boolean} Whether the sprite is intersecting this frustum or not. + */ + intersectsSprite( sprite ) { + + _sphere$3.center.set( 0, 0, 0 ); + + const offset = _defaultSpriteCenter.distanceTo( sprite.center ); + + _sphere$3.radius = 0.7071067811865476 + offset; + _sphere$3.applyMatrix4( sprite.matrixWorld ); + + return this.intersectsSphere( _sphere$3 ); + + } + + /** + * Returns `true` if the given bounding sphere is intersecting this frustum. + * + * This is a fast, conservative test that favors performance over precision. It can + * report false positives for spheres that lie outside the frustum but are not separated + * by a single frustum plane. It never reports false negatives, so it is safe for culling. + * + * @param {Sphere} sphere - The bounding sphere to test. + * @return {boolean} Whether the bounding sphere is intersecting this frustum or not. + */ + intersectsSphere( sphere ) { + + const planes = this.planes; + const center = sphere.center; + const negRadius = - sphere.radius; + + for ( let i = 0; i < 6; i ++ ) { + + const distance = planes[ i ].distanceToPoint( center ); + + if ( distance < negRadius ) { + + return false; + + } + + } + + return true; + + } + + /** + * Returns `true` if the given bounding box is intersecting this frustum. + * + * This is a fast, conservative test that favors performance over precision. It can + * report false positives for large boxes that lie outside the frustum but are not + * separated by a single frustum plane. It never reports false negatives, so it is + * safe for culling. + * + * @param {Box3} box - The bounding box to test. + * @return {boolean} Whether the bounding box is intersecting this frustum or not. + */ + intersectsBox( box ) { + + const planes = this.planes; + + for ( let i = 0; i < 6; i ++ ) { + + const plane = planes[ i ]; + + // corner at max distance + + _vector$6.x = plane.normal.x > 0 ? box.max.x : box.min.x; + _vector$6.y = plane.normal.y > 0 ? box.max.y : box.min.y; + _vector$6.z = plane.normal.z > 0 ? box.max.z : box.min.z; + + if ( plane.distanceToPoint( _vector$6 ) < 0 ) { + + return false; + + } + + } + + return true; + + } + + /** + * Returns `true` if the given point lies within the frustum. + * + * @param {Vector3} point - The point to test. + * @return {boolean} Whether the point lies within this frustum or not. + */ + containsPoint( point ) { + + const planes = this.planes; + + for ( let i = 0; i < 6; i ++ ) { + + if ( planes[ i ].distanceToPoint( point ) < 0 ) { + + return false; + + } + + } + + return true; + + } + + /** + * Returns a new frustum with copied values from this instance. + * + * @return {Frustum} A clone of this instance. + */ + clone() { + + return new this.constructor().copy( this ); + + } + +} + +const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4(); + +/** + * FrustumArray is used to determine if an object is visible in at least one camera + * from an array of cameras. This is particularly useful for multi-view renderers. +*/ +class FrustumArray { + + /** + * Constructs a new frustum array. + * + */ + constructor() { + + /** + * The coordinate system to use. + * + * @type {WebGLCoordinateSystem|WebGPUCoordinateSystem} + * @default WebGLCoordinateSystem + */ + this.coordinateSystem = WebGLCoordinateSystem; + + /** + * A pool of frustum instances. It may hold more entries than are + * currently in use; surplus instances are kept for reuse to avoid + * reallocating when array cameras of different lengths are rendered. + * + * @private + * @type {Array} + */ + this._frustums = []; + + /** + * The number of frustums in {@link FrustumArray#_frustums} that are currently + * in use. + * + * @private + * @type {number} + * @default 0 + */ + this._count = 0; + + } + + /** + * Computes and caches a frustum for each camera of the given array camera. + * + * @param {ArrayCamera} cameraArray - The array camera whose sub-cameras define the frustums. + * @return {FrustumArray} A reference to this frustum array. + */ + setFromArrayCamera( cameraArray ) { + + const cameras = cameraArray.cameras; + const frustums = this._frustums; + + for ( let i = 0; i < cameras.length; i ++ ) { + + const camera = cameras[ i ]; + + _projScreenMatrix$1.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse ); + + if ( frustums[ i ] === undefined ) frustums[ i ] = new Frustum(); + + frustums[ i ].setFromProjectionMatrix( _projScreenMatrix$1, camera.coordinateSystem, camera.reversedDepth ); + + } + + this._count = cameras.length; + + return this; + + } + + /** + * Returns `true` if the 3D object's bounding sphere is intersecting any cached frustum. + * + * {@link FrustumArray#setFromArrayCamera} must be called once per render before this method. + * + * @param {Object3D} object - The 3D object to test. + * @return {boolean} Whether the 3D object is visible in any camera. + */ + intersectsObject( object ) { + + const frustums = this._frustums; + + for ( let i = 0; i < this._count; i ++ ) { + + if ( frustums[ i ].intersectsObject( object ) ) return true; + + } + + return false; + + } + + /** + * Returns `true` if the given sprite is intersecting any cached frustum. + * + * {@link FrustumArray#setFromArrayCamera} must be called once per render before this method. + * + * @param {Sprite} sprite - The sprite to test. + * @return {boolean} Whether the sprite is visible in any camera. + */ + intersectsSprite( sprite ) { + + const frustums = this._frustums; + + for ( let i = 0; i < this._count; i ++ ) { + + if ( frustums[ i ].intersectsSprite( sprite ) ) return true; + + } + + return false; + + } + + /** + * Returns `true` if the given bounding sphere is intersecting any cached frustum. + * + * {@link FrustumArray#setFromArrayCamera} must be called once per render before this method. + * + * @param {Sphere} sphere - The bounding sphere to test. + * @return {boolean} Whether the sphere is visible in any camera. + */ + intersectsSphere( sphere ) { + + const frustums = this._frustums; + + for ( let i = 0; i < this._count; i ++ ) { + + if ( frustums[ i ].intersectsSphere( sphere ) ) return true; + + } + + return false; + + } + + /** + * Returns `true` if the given bounding box is intersecting any cached frustum. + * + * {@link FrustumArray#setFromArrayCamera} must be called once per render before this method. + * + * @param {Box3} box - The bounding box to test. + * @return {boolean} Whether the box is visible in any camera. + */ + intersectsBox( box ) { + + const frustums = this._frustums; + + for ( let i = 0; i < this._count; i ++ ) { + + if ( frustums[ i ].intersectsBox( box ) ) return true; + + } + + return false; + + } + + /** + * Returns `true` if the given point lies within any cached frustum. + * + * {@link FrustumArray#setFromArrayCamera} must be called once per render before this method. + * + * @param {Vector3} point - The point to test. + * @return {boolean} Whether the point is visible in any camera. + */ + containsPoint( point ) { + + const frustums = this._frustums; + + for ( let i = 0; i < this._count; i ++ ) { + + if ( frustums[ i ].containsPoint( point ) ) return true; + + } + + return false; + + } + + /** + * Copies the values of the given frustum array to this instance. + * + * @param {FrustumArray} source - The frustum array to copy. + * @return {FrustumArray} A reference to this frustum array. + */ + copy( source ) { + + this.coordinateSystem = source.coordinateSystem; + + const frustums = this._frustums; + const sourceFrustums = source._frustums; + + for ( let i = 0; i < source._count; i ++ ) { + + if ( frustums[ i ] === undefined ) frustums[ i ] = new Frustum(); + + frustums[ i ].copy( sourceFrustums[ i ] ); + + } + + this._count = source._count; + + return this; + + } + + /** + * Returns a new frustum array with copied values from this instance. + * + * @return {FrustumArray} A clone of this instance. + */ + clone() { + + return new FrustumArray().copy( this ); + + } + +} + +function ascIdSort( a, b ) { + + return a - b; + +} + +function sortOpaque( a, b ) { + + return a.z - b.z; + +} + +function sortTransparent( a, b ) { + + return b.z - a.z; + +} + +class MultiDrawRenderList { + + constructor() { + + this.index = 0; + this.pool = []; + this.list = []; + + } + + push( start, count, z, index ) { + + const pool = this.pool; + const list = this.list; + if ( this.index >= pool.length ) { + + pool.push( { + + start: -1, + count: -1, + z: -1, + index: -1, + + } ); + + } + + const item = pool[ this.index ]; + list.push( item ); + this.index ++; + + item.start = start; + item.count = count; + item.z = z; + item.index = index; + + } + + reset() { + + this.list.length = 0; + this.index = 0; + + } + +} + +const _matrix$1 = /*@__PURE__*/ new Matrix4(); +const _whiteColor = /*@__PURE__*/ new Color( 1, 1, 1 ); +const _frustum = /*@__PURE__*/ new Frustum(); +const _frustumArray = /*@__PURE__*/ new FrustumArray(); +const _box$1 = /*@__PURE__*/ new Box3(); +const _sphere$2 = /*@__PURE__*/ new Sphere(); +const _vector$5 = /*@__PURE__*/ new Vector3(); +const _forward$1 = /*@__PURE__*/ new Vector3(); +const _temp = /*@__PURE__*/ new Vector3(); +const _renderList = /*@__PURE__*/ new MultiDrawRenderList(); +const _mesh = /*@__PURE__*/ new Mesh(); +const _batchIntersects = []; + +// copies data from attribute "src" into "target" starting at "targetOffset" +function copyAttributeData( src, target, targetOffset = 0 ) { + + const itemSize = target.itemSize; + if ( src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor ) { + + // use the component getters and setters if the array data cannot + // be copied directly + const vertexCount = src.count; + for ( let i = 0; i < vertexCount; i ++ ) { + + for ( let c = 0; c < itemSize; c ++ ) { + + target.setComponent( i + targetOffset, c, src.getComponent( i, c ) ); + + } + + } + + } else { + + // faster copy approach using typed array set function + target.array.set( src.array, targetOffset * itemSize ); + + } + + target.needsUpdate = true; + +} + +// safely copies array contents to a potentially smaller array +function copyArrayContents( src, target ) { + + if ( src.constructor !== target.constructor ) { + + // if arrays are of a different type (eg due to index size increasing) then data must be per-element copied + const len = Math.min( src.length, target.length ); + for ( let i = 0; i < len; i ++ ) { + + target[ i ] = src[ i ]; + + } + + } else { + + // if the arrays use the same data layout we can use a fast block copy + const len = Math.min( src.length, target.length ); + target.set( new src.constructor( src.buffer, 0, len ) ); + + } + +} + +/** + * A special version of a mesh with multi draw batch rendering support. Use + * this class if you have to render a large number of objects with the same + * material but with different geometries or world transformations. The usage of + * `BatchedMesh` will help you to reduce the number of draw calls and thus improve the overall + * rendering performance in your application. + * + * ```js + * const box = new THREE.BoxGeometry( 1, 1, 1 ); + * const sphere = new THREE.SphereGeometry( 1, 12, 12 ); + * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } ); + * + * // initialize and add geometries into the batched mesh + * const batchedMesh = new BatchedMesh( 10, 5000, 10000, material ); + * const boxGeometryId = batchedMesh.addGeometry( box ); + * const sphereGeometryId = batchedMesh.addGeometry( sphere ); + * + * // create instances of those geometries + * const boxInstancedId1 = batchedMesh.addInstance( boxGeometryId ); + * const boxInstancedId2 = batchedMesh.addInstance( boxGeometryId ); + * + * const sphereInstancedId1 = batchedMesh.addInstance( sphereGeometryId ); + * const sphereInstancedId2 = batchedMesh.addInstance( sphereGeometryId ); + * + * // position the geometries + * batchedMesh.setMatrixAt( boxInstancedId1, boxMatrix1 ); + * batchedMesh.setMatrixAt( boxInstancedId2, boxMatrix2 ); + * + * batchedMesh.setMatrixAt( sphereInstancedId1, sphereMatrix1 ); + * batchedMesh.setMatrixAt( sphereInstancedId2, sphereMatrix2 ); + * + * scene.add( batchedMesh ); + * ``` + * + * @augments Mesh + */ +class BatchedMesh extends Mesh { + + /** + * Constructs a new batched mesh. + * + * @param {number} maxInstanceCount - The maximum number of individual instances planned to be added and rendered. + * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries. + * @param {number} [maxIndexCount=maxVertexCount*2] - The maximum number of indices to be used by all unique geometries + * @param {Material|Array} [material] - The mesh material. + */ + constructor( maxInstanceCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material ) { + + super( new BufferGeometry(), material ); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isBatchedMesh = true; + + /** + * When set ot `true`, the individual objects of a batch are frustum culled. + * + * @type {boolean} + * @default true + */ + this.perObjectFrustumCulled = true; + + /** + * When set to `true`, the individual objects of a batch are sorted to improve overdraw-related artifacts. + * If the material is marked as "transparent" objects are rendered back to front and if not then they are + * rendered front to back. + * + * @type {boolean} + * @default true + */ + this.sortObjects = true; + + /** + * The bounding box of the batched mesh. Can be computed via {@link BatchedMesh#computeBoundingBox}. + * + * @type {?Box3} + * @default null + */ + this.boundingBox = null; + + /** + * The bounding sphere of the batched mesh. Can be computed via {@link BatchedMesh#computeBoundingSphere}. + * + * @type {?Sphere} + * @default null + */ + this.boundingSphere = null; + + /** + * Takes a sort a function that is run before render. The function takes a list of instances to + * sort and a camera. The objects in the list include a "z" field to perform a depth-ordered + * sort with. + * + * @type {?Function} + * @default null + */ + this.customSort = null; + + // stores visible, active, and geometry id per instance and reserved buffer ranges for geometries + this._instanceInfo = []; + this._geometryInfo = []; + + // instance, geometry ids that have been set as inactive, and are available to be overwritten + this._availableInstanceIds = []; + this._availableGeometryIds = []; + + // used to track where the next point is that geometry should be inserted + this._nextIndexStart = 0; + this._nextVertexStart = 0; + this._geometryCount = 0; + + // flags + this._visibilityChanged = true; + this._geometryInitialized = false; + + // cached user options + this._maxInstanceCount = maxInstanceCount; + this._maxVertexCount = maxVertexCount; + this._maxIndexCount = maxIndexCount; + + // buffers for multi draw + this._multiDrawCounts = new Int32Array( maxInstanceCount ); + this._multiDrawStarts = new Int32Array( maxInstanceCount ); + this._multiDrawCount = 0; + this._multiDrawBytesPerElement = 1; + + // Local matrix per geometry by using data texture + this._matricesTexture = null; + this._indirectTexture = null; + this._colorsTexture = null; + + this._initMatricesTexture(); + this._initIndirectTexture(); + + } + + /** + * The maximum number of individual instances that can be stored in the batch. + * + * @type {number} + * @readonly + */ + get maxInstanceCount() { + + return this._maxInstanceCount; + + } + + /** + * The instance count. + * + * @type {number} + * @readonly + */ + get instanceCount() { + + return this._instanceInfo.length - this._availableInstanceIds.length; + + } + + /** + * The number of unused vertices. + * + * @type {number} + * @readonly + */ + get unusedVertexCount() { + + return this._maxVertexCount - this._nextVertexStart; + + } + + /** + * The number of unused indices. + * + * @type {number} + * @readonly + */ + get unusedIndexCount() { + + return this._maxIndexCount - this._nextIndexStart; + + } + + _initMatricesTexture() { + + // layout (1 matrix = 4 pixels) + // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4) + // with 8x8 pixel texture max 16 matrices * 4 pixels = (8 * 8) + // 16x16 pixel texture max 64 matrices * 4 pixels = (16 * 16) + // 32x32 pixel texture max 256 matrices * 4 pixels = (32 * 32) + // 64x64 pixel texture max 1024 matrices * 4 pixels = (64 * 64) + + let size = Math.sqrt( this._maxInstanceCount * 4 ); // 4 pixels needed for 1 matrix + size = Math.ceil( size / 4 ) * 4; + size = Math.max( size, 4 ); + + const matricesArray = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel + const matricesTexture = new DataTexture( matricesArray, size, size, RGBAFormat, FloatType ); + + this._matricesTexture = matricesTexture; + + } + + _initIndirectTexture() { + + let size = Math.sqrt( this._maxInstanceCount ); + size = Math.ceil( size ); + + const indirectArray = new Uint32Array( size * size ); + const indirectTexture = new DataTexture( indirectArray, size, size, RedIntegerFormat, UnsignedIntType ); + + this._indirectTexture = indirectTexture; + + } + + _initColorsTexture() { + + let size = Math.sqrt( this._maxInstanceCount ); + size = Math.ceil( size ); + + // 4 floats per RGBA pixel initialized to white + const colorsArray = new Float32Array( size * size * 4 ).fill( 1 ); + const colorsTexture = new DataTexture( colorsArray, size, size, RGBAFormat, FloatType ); + colorsTexture.colorSpace = ColorManagement.workingColorSpace; + + this._colorsTexture = colorsTexture; + + } + + _initializeGeometry( reference ) { + + const geometry = this.geometry; + const maxVertexCount = this._maxVertexCount; + const maxIndexCount = this._maxIndexCount; + if ( this._geometryInitialized === false ) { + + for ( const attributeName in reference.attributes ) { + + const srcAttribute = reference.getAttribute( attributeName ); + const { array, itemSize, normalized } = srcAttribute; + + const dstArray = new array.constructor( maxVertexCount * itemSize ); + const dstAttribute = new BufferAttribute( dstArray, itemSize, normalized ); + + geometry.setAttribute( attributeName, dstAttribute ); + + } + + if ( reference.getIndex() !== null ) { + + // Reserve last u16 index for primitive restart. + const indexArray = maxVertexCount > 65535 + ? new Uint32Array( maxIndexCount ) + : new Uint16Array( maxIndexCount ); + + geometry.setIndex( new BufferAttribute( indexArray, 1 ) ); + + } + + this._geometryInitialized = true; + + } + + } + + // Make sure the geometry is compatible with the existing combined geometry attributes + _validateGeometry( geometry ) { + + // check to ensure the geometries are using consistent attributes and indices + const batchGeometry = this.geometry; + if ( Boolean( geometry.getIndex() ) !== Boolean( batchGeometry.getIndex() ) ) { + + throw new Error( 'THREE.BatchedMesh: All geometries must consistently have "index".' ); + + } + + for ( const attributeName in batchGeometry.attributes ) { + + if ( ! geometry.hasAttribute( attributeName ) ) { + + throw new Error( `THREE.BatchedMesh: Added geometry missing "${ attributeName }". All geometries must have consistent attributes.` ); + + } + + const srcAttribute = geometry.getAttribute( attributeName ); + const dstAttribute = batchGeometry.getAttribute( attributeName ); + if ( srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized ) { + + throw new Error( 'THREE.BatchedMesh: All attributes must have a consistent itemSize and normalized value.' ); + + } + + } + + } + + /** + * Validates the instance defined by the given ID. + * + * @param {number} instanceId - The instance to validate. + */ + validateInstanceId( instanceId ) { + + const instanceInfo = this._instanceInfo; + if ( instanceId < 0 || instanceId >= instanceInfo.length || instanceInfo[ instanceId ].active === false ) { + + throw new Error( `THREE.BatchedMesh: Invalid instanceId ${instanceId}. Instance is either out of range or has been deleted.` ); + + } + + } + + /** + * Validates the geometry defined by the given ID. + * + * @param {number} geometryId - The geometry to validate. + */ + validateGeometryId( geometryId ) { + + const geometryInfoList = this._geometryInfo; + if ( geometryId < 0 || geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) { + + throw new Error( `THREE.BatchedMesh: Invalid geometryId ${geometryId}. Geometry is either out of range or has been deleted.` ); + + } + + } + + /** + * Takes a sort a function that is run before render. The function takes a list of instances to + * sort and a camera. The objects in the list include a "z" field to perform a depth-ordered sort with. + * + * @param {Function} func - The custom sort function. + * @return {BatchedMesh} A reference to this batched mesh. + */ + setCustomSort( func ) { + + this.customSort = func; + return this; + + } + + /** + * Computes the bounding box, updating {@link BatchedMesh#boundingBox}. + * Bounding boxes aren't computed by default. They need to be explicitly computed, + * otherwise they are `null`. + */ + computeBoundingBox() { + + if ( this.boundingBox === null ) { + + this.boundingBox = new Box3(); + + } + + const boundingBox = this.boundingBox; + const instanceInfo = this._instanceInfo; + + boundingBox.makeEmpty(); + for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) { + + if ( instanceInfo[ i ].active === false ) continue; + + const geometryId = instanceInfo[ i ].geometryIndex; + this.getMatrixAt( i, _matrix$1 ); + this.getBoundingBoxAt( geometryId, _box$1 ).applyMatrix4( _matrix$1 ); + boundingBox.union( _box$1 ); + + } + + } + + /** + * Computes the bounding sphere, updating {@link BatchedMesh#boundingSphere}. + * Bounding spheres aren't computed by default. They need to be explicitly computed, + * otherwise they are `null`. + */ + computeBoundingSphere() { + + if ( this.boundingSphere === null ) { + + this.boundingSphere = new Sphere(); + + } + + const boundingSphere = this.boundingSphere; + const instanceInfo = this._instanceInfo; + + boundingSphere.makeEmpty(); + for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) { + + if ( instanceInfo[ i ].active === false ) continue; + + const geometryId = instanceInfo[ i ].geometryIndex; + this.getMatrixAt( i, _matrix$1 ); + this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 ); + boundingSphere.union( _sphere$2 ); + + } + + } + + /** + * Adds a new instance to the batch using the geometry of the given ID and returns + * a new id referring to the new instance to be used by other functions. + * + * @param {number} geometryId - The ID of a previously added geometry via {@link BatchedMesh#addGeometry}. + * @return {number} The instance ID. + */ + addInstance( geometryId ) { + + const atCapacity = this._instanceInfo.length >= this.maxInstanceCount; + + // ensure we're not over geometry + if ( atCapacity && this._availableInstanceIds.length === 0 ) { + + throw new Error( 'THREE.BatchedMesh: Maximum item count reached.' ); + + } + + const instanceInfo = { + visible: true, + active: true, + geometryIndex: geometryId, + }; + + let drawId = null; + + // Prioritize using previously freed instance ids + if ( this._availableInstanceIds.length > 0 ) { + + this._availableInstanceIds.sort( ascIdSort ); + + drawId = this._availableInstanceIds.shift(); + this._instanceInfo[ drawId ] = instanceInfo; + + } else { + + drawId = this._instanceInfo.length; + this._instanceInfo.push( instanceInfo ); + + } + + const matricesTexture = this._matricesTexture; + _matrix$1.identity().toArray( matricesTexture.image.data, drawId * 16 ); + matricesTexture.needsUpdate = true; + + const colorsTexture = this._colorsTexture; + if ( colorsTexture ) { + + _whiteColor.toArray( colorsTexture.image.data, drawId * 4 ); + colorsTexture.needsUpdate = true; + + } + + this._visibilityChanged = true; + return drawId; + + } + + /** + * Adds the given geometry to the batch and returns the associated + * geometry id referring to it to be used in other functions. + * + * @param {BufferGeometry} geometry - The geometry to add. + * @param {number} [reservedVertexCount=-1] - Optional parameter specifying the amount of + * vertex buffer space to reserve for the added geometry. This is necessary if it is planned + * to set a new geometry at this index at a later time that is larger than the original geometry. + * Defaults to the length of the given geometry vertex buffer. + * @param {number} [reservedIndexCount=-1] - Optional parameter specifying the amount of index + * buffer space to reserve for the added geometry. This is necessary if it is planned to set a + * new geometry at this index at a later time that is larger than the original geometry. Defaults to + * the length of the given geometry index buffer. + * @return {number} The geometry ID. + */ + addGeometry( geometry, reservedVertexCount = -1, reservedIndexCount = -1 ) { + + this._initializeGeometry( geometry ); + + this._validateGeometry( geometry ); + + const geometryInfo = { + // geometry information + vertexStart: -1, + vertexCount: -1, + reservedVertexCount: -1, + + indexStart: -1, + indexCount: -1, + reservedIndexCount: -1, + + // draw range information + start: -1, + count: -1, + + // state + boundingBox: null, + boundingSphere: null, + active: true, + }; + + const geometryInfoList = this._geometryInfo; + geometryInfo.vertexStart = this._nextVertexStart; + geometryInfo.reservedVertexCount = reservedVertexCount === -1 ? geometry.getAttribute( 'position' ).count : reservedVertexCount; + + const index = geometry.getIndex(); + const hasIndex = index !== null; + if ( hasIndex ) { + + geometryInfo.indexStart = this._nextIndexStart; + geometryInfo.reservedIndexCount = reservedIndexCount === -1 ? index.count : reservedIndexCount; + + } + + if ( + geometryInfo.indexStart !== -1 && + geometryInfo.indexStart + geometryInfo.reservedIndexCount > this._maxIndexCount || + geometryInfo.vertexStart + geometryInfo.reservedVertexCount > this._maxVertexCount + ) { + + throw new Error( 'THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size.' ); + + } + + // update id + let geometryId; + if ( this._availableGeometryIds.length > 0 ) { + + this._availableGeometryIds.sort( ascIdSort ); + + geometryId = this._availableGeometryIds.shift(); + geometryInfoList[ geometryId ] = geometryInfo; + + + } else { + + geometryId = this._geometryCount; + this._geometryCount ++; + geometryInfoList.push( geometryInfo ); + + } + + // update the geometry + this.setGeometryAt( geometryId, geometry ); + + // increment the next geometry position + this._nextIndexStart = geometryInfo.indexStart + geometryInfo.reservedIndexCount; + this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount; + + return geometryId; + + } + + /** + * Replaces the geometry at the given ID with the provided geometry. Throws an error if there + * is not enough space reserved for geometry. Calling this will change all instances that are + * rendering that geometry. + * + * @param {number} geometryId - The ID of the geometry that should be replaced with the given geometry. + * @param {BufferGeometry} geometry - The new geometry. + * @return {number} The geometry ID. + */ + setGeometryAt( geometryId, geometry ) { + + if ( geometryId >= this._geometryCount ) { + + throw new Error( 'THREE.BatchedMesh: Maximum geometry count reached.' ); + + } + + this._validateGeometry( geometry ); + + const batchGeometry = this.geometry; + const hasIndex = batchGeometry.getIndex() !== null; + const dstIndex = batchGeometry.getIndex(); + const srcIndex = geometry.getIndex(); + const geometryInfo = this._geometryInfo[ geometryId ]; + if ( + hasIndex && + srcIndex.count > geometryInfo.reservedIndexCount || + geometry.attributes.position.count > geometryInfo.reservedVertexCount + ) { + + throw new Error( 'THREE.BatchedMesh: Reserved space not large enough for provided geometry.' ); + + } + + // copy geometry buffer data over + const vertexStart = geometryInfo.vertexStart; + const reservedVertexCount = geometryInfo.reservedVertexCount; + geometryInfo.vertexCount = geometry.getAttribute( 'position' ).count; + + for ( const attributeName in batchGeometry.attributes ) { + + // copy attribute data + const srcAttribute = geometry.getAttribute( attributeName ); + const dstAttribute = batchGeometry.getAttribute( attributeName ); + copyAttributeData( srcAttribute, dstAttribute, vertexStart ); + + // fill the rest in with zeroes + const itemSize = srcAttribute.itemSize; + for ( let i = srcAttribute.count, l = reservedVertexCount; i < l; i ++ ) { + + const index = vertexStart + i; + for ( let c = 0; c < itemSize; c ++ ) { + + dstAttribute.setComponent( index, c, 0 ); + + } + + } + + dstAttribute.needsUpdate = true; + dstAttribute.addUpdateRange( vertexStart * itemSize, reservedVertexCount * itemSize ); + + } + + // copy index + if ( hasIndex ) { + + const indexStart = geometryInfo.indexStart; + const reservedIndexCount = geometryInfo.reservedIndexCount; + geometryInfo.indexCount = geometry.getIndex().count; + + // copy index data over + for ( let i = 0; i < srcIndex.count; i ++ ) { + + dstIndex.setX( indexStart + i, vertexStart + srcIndex.getX( i ) ); + + } + + // fill the rest in with zeroes + for ( let i = srcIndex.count, l = reservedIndexCount; i < l; i ++ ) { + + dstIndex.setX( indexStart + i, vertexStart ); + + } + + dstIndex.needsUpdate = true; + dstIndex.addUpdateRange( indexStart, geometryInfo.reservedIndexCount ); + + } + + // update the draw range + geometryInfo.start = hasIndex ? geometryInfo.indexStart : geometryInfo.vertexStart; + geometryInfo.count = hasIndex ? geometryInfo.indexCount : geometryInfo.vertexCount; + + // store the bounding boxes + geometryInfo.boundingBox = null; + if ( geometry.boundingBox !== null ) { + + geometryInfo.boundingBox = geometry.boundingBox.clone(); + + } + + geometryInfo.boundingSphere = null; + if ( geometry.boundingSphere !== null ) { + + geometryInfo.boundingSphere = geometry.boundingSphere.clone(); + + } + + this._visibilityChanged = true; + return geometryId; + + } + + /** + * Deletes the geometry defined by the given ID from this batch. Any instances referencing + * this geometry will also be removed as a side effect. + * + * @param {number} geometryId - The ID of the geometry to remove from the batch. + * @return {BatchedMesh} A reference to this batched mesh. + */ + deleteGeometry( geometryId ) { + + const geometryInfoList = this._geometryInfo; + if ( geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) { + + return this; + + } + + // delete any instances associated with this geometry + const instanceInfo = this._instanceInfo; + for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) { + + if ( instanceInfo[ i ].active && instanceInfo[ i ].geometryIndex === geometryId ) { + + this.deleteInstance( i ); + + } + + } + + geometryInfoList[ geometryId ].active = false; + this._availableGeometryIds.push( geometryId ); + this._visibilityChanged = true; + + return this; + + } + + /** + * Deletes an existing instance from the batch using the given ID. + * + * @param {number} instanceId - The ID of the instance to remove from the batch. + * @return {BatchedMesh} A reference to this batched mesh. + */ + deleteInstance( instanceId ) { + + this.validateInstanceId( instanceId ); + + this._instanceInfo[ instanceId ].active = false; + this._availableInstanceIds.push( instanceId ); + this._visibilityChanged = true; + + return this; + + } + + /** + * Repacks the sub geometries in BatchedMesh to remove any unused space remaining from + * previously deleted geometry, freeing up space to add new geometry. + * + * @return {BatchedMesh} A reference to this batched mesh. + */ + optimize() { + + // track the next indices to copy data to + let nextVertexStart = 0; + let nextIndexStart = 0; + + // Iterate over all geometry ranges in order sorted from earliest in the geometry buffer to latest + // in the geometry buffer. Because draw range objects can be reused there is no guarantee of their order. + const geometryInfoList = this._geometryInfo; + const indices = geometryInfoList + .map( ( e, i ) => i ) + .sort( ( a, b ) => { + + return geometryInfoList[ a ].vertexStart - geometryInfoList[ b ].vertexStart; + + } ); + + const geometry = this.geometry; + for ( let i = 0, l = geometryInfoList.length; i < l; i ++ ) { + + // if a geometry range is inactive then don't copy anything + const index = indices[ i ]; + const geometryInfo = geometryInfoList[ index ]; + if ( geometryInfo.active === false ) { + + continue; + + } + + // if a geometry contains an index buffer then shift it, as well + if ( geometry.index !== null ) { + + if ( geometryInfo.indexStart !== nextIndexStart ) { + + const { indexStart, vertexStart, reservedIndexCount } = geometryInfo; + const index = geometry.index; + const array = index.array; + + // shift the index pointers based on how the vertex data will shift + // adjusting the index must happen first so the original vertex start value is available + const elementDelta = nextVertexStart - vertexStart; + for ( let j = indexStart; j < indexStart + reservedIndexCount; j ++ ) { + + array[ j ] = array[ j ] + elementDelta; + + } + + index.array.copyWithin( nextIndexStart, indexStart, indexStart + reservedIndexCount ); + index.addUpdateRange( nextIndexStart, reservedIndexCount ); + index.needsUpdate = true; + + geometryInfo.indexStart = nextIndexStart; + + } + + nextIndexStart += geometryInfo.reservedIndexCount; + + } + + // if a geometry needs to be moved then copy attribute data to overwrite unused space + if ( geometryInfo.vertexStart !== nextVertexStart ) { + + const { vertexStart, reservedVertexCount } = geometryInfo; + const attributes = geometry.attributes; + for ( const key in attributes ) { + + const attribute = attributes[ key ]; + const { array, itemSize } = attribute; + array.copyWithin( nextVertexStart * itemSize, vertexStart * itemSize, ( vertexStart + reservedVertexCount ) * itemSize ); + attribute.addUpdateRange( nextVertexStart * itemSize, reservedVertexCount * itemSize ); + attribute.needsUpdate = true; + + } + + geometryInfo.vertexStart = nextVertexStart; + + } + + nextVertexStart += geometryInfo.reservedVertexCount; + geometryInfo.start = geometry.index ? geometryInfo.indexStart : geometryInfo.vertexStart; + + } + + this._nextIndexStart = nextIndexStart; + this._nextVertexStart = nextVertexStart; + this._visibilityChanged = true; + + return this; + + } + + /** + * Returns the bounding box for the given geometry. + * + * @param {number} geometryId - The ID of the geometry to return the bounding box for. + * @param {Box3} target - The target object that is used to store the method's result. + * @return {?Box3} The geometry's bounding box. Returns `null` if no geometry has been found for the given ID. + */ + getBoundingBoxAt( geometryId, target ) { + + if ( geometryId >= this._geometryCount ) { + + return null; + + } + + // compute bounding box + const geometry = this.geometry; + const geometryInfo = this._geometryInfo[ geometryId ]; + if ( geometryInfo.boundingBox === null ) { + + const box = new Box3(); + const index = geometry.index; + const position = geometry.attributes.position; + for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) { + + let iv = i; + if ( index ) { + + iv = index.getX( iv ); + + } + + box.expandByPoint( _vector$5.fromBufferAttribute( position, iv ) ); + + } + + geometryInfo.boundingBox = box; + + } + + target.copy( geometryInfo.boundingBox ); + return target; + + } + + /** + * Returns the bounding sphere for the given geometry. + * + * @param {number} geometryId - The ID of the geometry to return the bounding sphere for. + * @param {Sphere} target - The target object that is used to store the method's result. + * @return {?Sphere} The geometry's bounding sphere. Returns `null` if no geometry has been found for the given ID. + */ + getBoundingSphereAt( geometryId, target ) { + + if ( geometryId >= this._geometryCount ) { + + return null; + + } + + // compute bounding sphere + const geometry = this.geometry; + const geometryInfo = this._geometryInfo[ geometryId ]; + if ( geometryInfo.boundingSphere === null ) { + + const sphere = new Sphere(); + this.getBoundingBoxAt( geometryId, _box$1 ); + _box$1.getCenter( sphere.center ); + + const index = geometry.index; + const position = geometry.attributes.position; + + let maxRadiusSq = 0; + for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) { + + let iv = i; + if ( index ) { + + iv = index.getX( iv ); + + } + + _vector$5.fromBufferAttribute( position, iv ); + maxRadiusSq = Math.max( maxRadiusSq, sphere.center.distanceToSquared( _vector$5 ) ); + + } + + sphere.radius = Math.sqrt( maxRadiusSq ); + geometryInfo.boundingSphere = sphere; + + } + + target.copy( geometryInfo.boundingSphere ); + return target; + + } + + /** + * Sets the given local transformation matrix to the defined instance. + * Negatively scaled matrices are not supported. + * + * @param {number} instanceId - The ID of an instance to set the matrix of. + * @param {Matrix4} matrix - A 4x4 matrix representing the local transformation of a single instance. + * @return {BatchedMesh} A reference to this batched mesh. + */ + setMatrixAt( instanceId, matrix ) { + + this.validateInstanceId( instanceId ); + + const matricesTexture = this._matricesTexture; + const matricesArray = this._matricesTexture.image.data; + matrix.toArray( matricesArray, instanceId * 16 ); + matricesTexture.needsUpdate = true; + + return this; + + } + + /** + * Returns the local transformation matrix of the defined instance. + * + * @param {number} instanceId - The ID of an instance to get the matrix of. + * @param {Matrix4} matrix - The target object that is used to store the method's result. + * @return {Matrix4} The instance's local transformation matrix. + */ + getMatrixAt( instanceId, matrix ) { + + this.validateInstanceId( instanceId ); + return matrix.fromArray( this._matricesTexture.image.data, instanceId * 16 ); + + } + + /** + * Sets the given color to the defined instance. + * + * @param {number} instanceId - The ID of an instance to set the color of. + * @param {Color|Vector4} color - The color to set the instance to. Use a `Vector4` to also define alpha. + * @return {BatchedMesh} A reference to this batched mesh. + */ + setColorAt( instanceId, color ) { + + this.validateInstanceId( instanceId ); + + if ( this._colorsTexture === null ) { + + this._initColorsTexture(); + + } + + color.toArray( this._colorsTexture.image.data, instanceId * 4 ); + this._colorsTexture.needsUpdate = true; + + return this; + + } + + /** + * Returns the color of the defined instance. + * + * @param {number} instanceId - The ID of an instance to get the color of. + * @param {Color|Vector4} color - The target object that is used to store the method's result. + * @return {Color|Vector4} The instance's color. Use a `Vector4` to also retrieve alpha. + */ + getColorAt( instanceId, color ) { + + this.validateInstanceId( instanceId ); + if ( this._colorsTexture === null ) { + + if ( color.isVector4 ) { + + return color.set( 1, 1, 1, 1 ); + + } else { + + return color.setRGB( 1, 1, 1 ); + + } + + } else { + + return color.fromArray( this._colorsTexture.image.data, instanceId * 4 ); + + } + + } + + /** + * Sets the visibility of the instance. + * + * @param {number} instanceId - The id of the instance to set the visibility of. + * @param {boolean} visible - Whether the instance is visible or not. + * @return {BatchedMesh} A reference to this batched mesh. + */ + setVisibleAt( instanceId, visible ) { + + this.validateInstanceId( instanceId ); + + if ( this._instanceInfo[ instanceId ].visible === visible ) { + + return this; + + } + + this._instanceInfo[ instanceId ].visible = visible; + this._visibilityChanged = true; + + return this; + + } + + /** + * Returns the visibility state of the defined instance. + * + * @param {number} instanceId - The ID of an instance to get the visibility state of. + * @return {boolean} Whether the instance is visible or not. + */ + getVisibleAt( instanceId ) { + + this.validateInstanceId( instanceId ); + + return this._instanceInfo[ instanceId ].visible; + + } + + /** + * Sets the geometry ID of the instance at the given index. + * + * @param {number} instanceId - The ID of the instance to set the geometry ID of. + * @param {number} geometryId - The geometry ID to be use by the instance. + * @return {BatchedMesh} A reference to this batched mesh. + */ + setGeometryIdAt( instanceId, geometryId ) { + + this.validateInstanceId( instanceId ); + this.validateGeometryId( geometryId ); + + this._instanceInfo[ instanceId ].geometryIndex = geometryId; + this._visibilityChanged = true; + + return this; + + } + + /** + * Returns the geometry ID of the defined instance. + * + * @param {number} instanceId - The ID of an instance to get the geometry ID of. + * @return {number} The instance's geometry ID. + */ + getGeometryIdAt( instanceId ) { + + this.validateInstanceId( instanceId ); + + return this._instanceInfo[ instanceId ].geometryIndex; + + } + + /** + * Get the range representing the subset of triangles related to the attached geometry, + * indicating the starting offset and count, or `null` if invalid. + * + * @param {number} geometryId - The id of the geometry to get the range of. + * @param {Object} [target] - The target object that is used to store the method's result. + * @return {{ + * vertexStart:number,vertexCount:number,reservedVertexCount:number, + * indexStart:number,indexCount:number,reservedIndexCount:number, + * start:number,count:number + * }} The result object with range data. + */ + getGeometryRangeAt( geometryId, target = {} ) { + + this.validateGeometryId( geometryId ); + + const geometryInfo = this._geometryInfo[ geometryId ]; + target.vertexStart = geometryInfo.vertexStart; + target.vertexCount = geometryInfo.vertexCount; + target.reservedVertexCount = geometryInfo.reservedVertexCount; + + target.indexStart = geometryInfo.indexStart; + target.indexCount = geometryInfo.indexCount; + target.reservedIndexCount = geometryInfo.reservedIndexCount; + + target.start = geometryInfo.start; + target.count = geometryInfo.count; + + return target; + + } + + /** + * Resizes the necessary buffers to support the provided number of instances. + * If the provided arguments shrink the number of instances but there are not enough + * unused Ids at the end of the list then an error is thrown. + * + * @param {number} maxInstanceCount - The max number of individual instances that can be added and rendered by the batch. + */ + setInstanceCount( maxInstanceCount ) { + + // shrink the available instances as much as possible + const availableInstanceIds = this._availableInstanceIds; + const instanceInfo = this._instanceInfo; + availableInstanceIds.sort( ascIdSort ); + while ( availableInstanceIds[ availableInstanceIds.length - 1 ] === instanceInfo.length - 1 ) { + + instanceInfo.pop(); + availableInstanceIds.pop(); + + } + + // throw an error if it can't be shrunk to the desired size + if ( maxInstanceCount < instanceInfo.length ) { + + throw new Error( `THREE.BatchedMesh: Instance ids outside the range ${ maxInstanceCount } are being used. Cannot shrink instance count.` ); + + } + + // copy the multi draw counts + const multiDrawCounts = new Int32Array( maxInstanceCount ); + const multiDrawStarts = new Int32Array( maxInstanceCount ); + copyArrayContents( this._multiDrawCounts, multiDrawCounts ); + copyArrayContents( this._multiDrawStarts, multiDrawStarts ); + + this._multiDrawCounts = multiDrawCounts; + this._multiDrawStarts = multiDrawStarts; + this._maxInstanceCount = maxInstanceCount; + + // update texture data for instance sampling + const indirectTexture = this._indirectTexture; + const matricesTexture = this._matricesTexture; + const colorsTexture = this._colorsTexture; + + indirectTexture.dispose(); + this._initIndirectTexture(); + copyArrayContents( indirectTexture.image.data, this._indirectTexture.image.data ); + + matricesTexture.dispose(); + this._initMatricesTexture(); + copyArrayContents( matricesTexture.image.data, this._matricesTexture.image.data ); + + if ( colorsTexture ) { + + colorsTexture.dispose(); + this._initColorsTexture(); + copyArrayContents( colorsTexture.image.data, this._colorsTexture.image.data ); + + } + + } + + /** + * Resizes the available space in the batch's vertex and index buffer attributes to the provided sizes. + * If the provided arguments shrink the geometry buffers but there is not enough unused space at the + * end of the geometry attributes then an error is thrown. + * + * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries to resize to. + * @param {number} maxIndexCount - The maximum number of indices to be used by all unique geometries to resize to. + */ + setGeometrySize( maxVertexCount, maxIndexCount ) { + + // Check if we can shrink to the requested vertex attribute size + const validRanges = [ ...this._geometryInfo ].filter( info => info.active ); + const requiredVertexLength = Math.max( ...validRanges.map( range => range.vertexStart + range.reservedVertexCount ) ); + if ( requiredVertexLength > maxVertexCount ) { + + throw new Error( `THREE.BatchedMesh: Geometry vertex values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` ); + + } + + // Check if we can shrink to the requested index attribute size + if ( this.geometry.index ) { + + const requiredIndexLength = Math.max( ...validRanges.map( range => range.indexStart + range.reservedIndexCount ) ); + if ( requiredIndexLength > maxIndexCount ) { + + throw new Error( `THREE.BatchedMesh: Geometry index values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` ); + + } + + } + + // + + // dispose of the previous geometry + const oldGeometry = this.geometry; + oldGeometry.dispose(); + + // recreate the geometry needed based on the previous variant + this._maxVertexCount = maxVertexCount; + this._maxIndexCount = maxIndexCount; + + if ( this._geometryInitialized ) { + + this._geometryInitialized = false; + this.geometry = new BufferGeometry(); + this._initializeGeometry( oldGeometry ); + + } + + // copy data from the previous geometry + const geometry = this.geometry; + if ( oldGeometry.index ) { + + copyArrayContents( oldGeometry.index.array, geometry.index.array ); + + } + + for ( const key in oldGeometry.attributes ) { + + copyArrayContents( oldGeometry.attributes[ key ].array, geometry.attributes[ key ].array ); + + } + + } + + raycast( raycaster, intersects ) { + + const instanceInfo = this._instanceInfo; + const geometryInfoList = this._geometryInfo; + const matrixWorld = this.matrixWorld; + const batchGeometry = this.geometry; + + // iterate over each geometry + _mesh.material = this.material; + _mesh.geometry.index = batchGeometry.index; + _mesh.geometry.attributes = batchGeometry.attributes; + if ( _mesh.geometry.boundingBox === null ) { + + _mesh.geometry.boundingBox = new Box3(); + + } + + if ( _mesh.geometry.boundingSphere === null ) { + + _mesh.geometry.boundingSphere = new Sphere(); + + } + + for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) { + + if ( ! instanceInfo[ i ].visible || ! instanceInfo[ i ].active ) { + + continue; + + } + + const geometryId = instanceInfo[ i ].geometryIndex; + const geometryInfo = geometryInfoList[ geometryId ]; + _mesh.geometry.setDrawRange( geometryInfo.start, geometryInfo.count ); + + // get the intersects + this.getMatrixAt( i, _mesh.matrixWorld ).premultiply( matrixWorld ); + this.getBoundingBoxAt( geometryId, _mesh.geometry.boundingBox ); + this.getBoundingSphereAt( geometryId, _mesh.geometry.boundingSphere ); + _mesh.raycast( raycaster, _batchIntersects ); + + // add batch id to the intersects + for ( let j = 0, l = _batchIntersects.length; j < l; j ++ ) { + + const intersect = _batchIntersects[ j ]; + intersect.object = this; + intersect.batchId = i; + intersects.push( intersect ); + + } + + _batchIntersects.length = 0; + + } + + _mesh.material = null; + _mesh.geometry.index = null; + _mesh.geometry.attributes = {}; + _mesh.geometry.setDrawRange( 0, Infinity ); + + } + + copy( source ) { + + super.copy( source ); + + this.geometry = source.geometry.clone(); + this.perObjectFrustumCulled = source.perObjectFrustumCulled; + this.sortObjects = source.sortObjects; + this.boundingBox = source.boundingBox !== null ? source.boundingBox.clone() : null; + this.boundingSphere = source.boundingSphere !== null ? source.boundingSphere.clone() : null; + + this._geometryInfo = source._geometryInfo.map( info => ( { + ...info, + + boundingBox: info.boundingBox !== null ? info.boundingBox.clone() : null, + boundingSphere: info.boundingSphere !== null ? info.boundingSphere.clone() : null, + } ) ); + this._instanceInfo = source._instanceInfo.map( info => ( { ...info } ) ); + + this._availableInstanceIds = source._availableInstanceIds.slice(); + this._availableGeometryIds = source._availableGeometryIds.slice(); + + this._nextIndexStart = source._nextIndexStart; + this._nextVertexStart = source._nextVertexStart; + this._geometryCount = source._geometryCount; + + this._maxInstanceCount = source._maxInstanceCount; + this._maxVertexCount = source._maxVertexCount; + this._maxIndexCount = source._maxIndexCount; + + this._geometryInitialized = source._geometryInitialized; + this._multiDrawCounts = source._multiDrawCounts.slice(); + this._multiDrawStarts = source._multiDrawStarts.slice(); + this._multiDrawBytesPerElement = source._multiDrawBytesPerElement; + + this._indirectTexture = source._indirectTexture.clone(); + this._indirectTexture.image.data = this._indirectTexture.image.data.slice(); + + this._matricesTexture = source._matricesTexture.clone(); + this._matricesTexture.image.data = this._matricesTexture.image.data.slice(); + + if ( this._colorsTexture !== null ) { + + this._colorsTexture = source._colorsTexture.clone(); + this._colorsTexture.image.data = this._colorsTexture.image.data.slice(); + + } + + return this; + + } + + /** + * Frees the GPU-related resources allocated by this instance. Call this + * method whenever this instance is no longer used in your app. + */ + dispose() { + + super.dispose(); + + // Assuming the geometry is not shared with other meshes + this.geometry.dispose(); + + this._matricesTexture.dispose(); + this._matricesTexture = null; + + this._indirectTexture.dispose(); + this._indirectTexture = null; + + if ( this._colorsTexture !== null ) { + + this._colorsTexture.dispose(); + this._colorsTexture = null; + + } + + } + + onBeforeRender( renderer, scene, camera, geometry, material/*, _group*/ ) { + + // if visibility has not changed and frustum culling and object sorting is not required + // then skip iterating over all items + if ( ! this._visibilityChanged && ! this.perObjectFrustumCulled && ! this.sortObjects ) { + + return; + + } + + // the indexed version of the multi draw function requires specifying the start + // offset in bytes. + const index = geometry.getIndex(); + let bytesPerElement = index === null ? 1 : index.array.BYTES_PER_ELEMENT; + + + // the "wireframe" attribute implicitly creates a line attribute in the renderer, which is double + // the vertices to draw (3 lines per triangle) so we multiply the draw counts / starts and make + // assumptions about the index buffer byte size. + let multiDrawMultiplier = 1; + if ( material.wireframe ) { + + multiDrawMultiplier = 2; + bytesPerElement = geometry.attributes.position.count > 65535 ? 4 : 2; + + } + + const instanceInfo = this._instanceInfo; + const multiDrawStarts = this._multiDrawStarts; + const multiDrawCounts = this._multiDrawCounts; + const geometryInfoList = this._geometryInfo; + const perObjectFrustumCulled = this.perObjectFrustumCulled; + const indirectTexture = this._indirectTexture; + const indirectArray = indirectTexture.image.data; + + const frustum = camera.isArrayCamera ? _frustumArray : _frustum; + // prepare the frustum in the local frame + if ( perObjectFrustumCulled ) { + + if ( camera.isArrayCamera ) { + + frustum.setFromArrayCamera( camera ); + + } else { + + _matrix$1 + .multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse ) + .multiply( this.matrixWorld ); + + frustum.setFromProjectionMatrix( + _matrix$1, + camera.coordinateSystem, + camera.reversedDepth + ); + + } + + } + + let multiDrawCount = 0; + if ( this.sortObjects ) { + + // get the camera position in the local frame + _matrix$1.copy( this.matrixWorld ).invert(); + _vector$5.setFromMatrixPosition( camera.matrixWorld ).applyMatrix4( _matrix$1 ); + _forward$1.set( 0, 0, -1 ).transformDirection( camera.matrixWorld ).transformDirection( _matrix$1 ); + + for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) { + + if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) { + + const geometryId = instanceInfo[ i ].geometryIndex; + + // get the bounds in world space + this.getMatrixAt( i, _matrix$1 ); + this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 ); + + // determine whether the batched geometry is within the frustum + let culled = false; + if ( perObjectFrustumCulled ) { + + culled = ! frustum.intersectsSphere( _sphere$2 ); + + } + + if ( ! culled ) { + + // get the distance from camera used for sorting + const geometryInfo = geometryInfoList[ geometryId ]; + const z = _temp.subVectors( _sphere$2.center, _vector$5 ).dot( _forward$1 ); + _renderList.push( geometryInfo.start, geometryInfo.count, z, i ); + + } + + } + + } + + // Sort the draw ranges and prep for rendering + const list = _renderList.list; + const customSort = this.customSort; + if ( customSort === null ) { + + list.sort( material.transparent ? sortTransparent : sortOpaque ); + + } else { + + customSort.call( this, list, camera ); + + } + + for ( let i = 0, l = list.length; i < l; i ++ ) { + + const item = list[ i ]; + multiDrawStarts[ multiDrawCount ] = item.start * bytesPerElement * multiDrawMultiplier; + multiDrawCounts[ multiDrawCount ] = item.count * multiDrawMultiplier; + indirectArray[ multiDrawCount ] = item.index; + multiDrawCount ++; + + } + + _renderList.reset(); + + } else { + + for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) { + + if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) { + + const geometryId = instanceInfo[ i ].geometryIndex; + + // determine whether the batched geometry is within the frustum + let culled = false; + if ( perObjectFrustumCulled ) { + + // get the bounds in world space + this.getMatrixAt( i, _matrix$1 ); + this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 ); + culled = ! frustum.intersectsSphere( _sphere$2 ); + + } + + if ( ! culled ) { + + const geometryInfo = geometryInfoList[ geometryId ]; + multiDrawStarts[ multiDrawCount ] = geometryInfo.start * bytesPerElement * multiDrawMultiplier; + multiDrawCounts[ multiDrawCount ] = geometryInfo.count * multiDrawMultiplier; + indirectArray[ multiDrawCount ] = i; + multiDrawCount ++; + + } + + } + + } + + } + + indirectTexture.needsUpdate = true; + this._multiDrawCount = multiDrawCount; + this._multiDrawBytesPerElement = bytesPerElement; + this._visibilityChanged = false; + + } + + onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial/* , group */ ) { + + this.onBeforeRender( renderer, null, shadowCamera, geometry, depthMaterial ); + + } + +} + +/** + * A material for rendering line primitives. + * + * Materials define the appearance of renderable 3D objects. + * + * ```js + * const material = new THREE.LineBasicMaterial( { color: 0xffffff } ); + * ``` + * + * @augments Material + */ +class LineBasicMaterial extends Material { + + /** + * Constructs a new line basic material. + * + * @param {Object} [parameters] - An object with one or more properties + * defining the material's appearance. Any property of the material + * (including any property from inherited materials) can be passed + * in here. Color values can be passed any type of value accepted + * by {@link Color#set}. + */ + constructor( parameters ) { + + super(); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isLineBasicMaterial = true; + + this.type = 'LineBasicMaterial'; + + /** + * Color of the material. + * + * @type {Color} + * @default (1,1,1) + */ + this.color = new Color( 0xffffff ); + + /** + * Sets the color of the lines using data from a texture. The texture map + * color is modulated by the diffuse `color`. + * + * `map` represents color data, and the texture must be assigned a + * {@link Texture#colorSpace}. Most `map` textures set + * `texture.colorSpace = SRGBColorSpace`. + * + * @type {?Texture} + * @default null + */ + this.map = null; + + /** + * Controls line thickness or lines. + * + * Can only be used with {@link SVGRenderer}. WebGL and WebGPU + * ignore this setting and always render line primitives with a + * width of one pixel. + * + * @type {number} + * @default 1 + */ + this.linewidth = 1; + + /** + * Defines appearance of line ends. + * + * Can only be used with {@link SVGRenderer}. + * + * @type {('butt'|'round'|'square')} + * @default 'round' + */ + this.linecap = 'round'; + + /** + * Defines appearance of line joints. + * + * Can only be used with {@link SVGRenderer}. + * + * @type {('round'|'bevel'|'miter')} + * @default 'round' + */ + this.linejoin = 'round'; + + /** + * Whether the material is affected by fog or not. + * + * @type {boolean} + * @default true + */ + this.fog = true; + + this.setValues( parameters ); + + } + + copy( source ) { + + super.copy( source ); + + this.color.copy( source.color ); + + this.map = source.map; + + this.linewidth = source.linewidth; + this.linecap = source.linecap; + this.linejoin = source.linejoin; + + this.fog = source.fog; + + return this; + + } + +} + +const _vStart = /*@__PURE__*/ new Vector3(); +const _vEnd = /*@__PURE__*/ new Vector3(); + +const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4(); +const _ray$1 = /*@__PURE__*/ new Ray(); +const _sphere$1 = /*@__PURE__*/ new Sphere(); + +const _intersectPointOnRay = /*@__PURE__*/ new Vector3(); +const _intersectPointOnSegment = /*@__PURE__*/ new Vector3(); + +/** + * A continuous line. The line are rendered by connecting consecutive + * vertices with straight lines. + * + * ```js + * const material = new THREE.LineBasicMaterial( { color: 0x0000ff } ); + * + * const points = []; + * points.push( new THREE.Vector3( - 10, 0, 0 ) ); + * points.push( new THREE.Vector3( 0, 10, 0 ) ); + * points.push( new THREE.Vector3( 10, 0, 0 ) ); + * + * const geometry = new THREE.BufferGeometry().setFromPoints( points ); + * + * const line = new THREE.Line( geometry, material ); + * scene.add( line ); + * ``` + * + * @augments Object3D + */ +class Line extends Object3D { + + /** + * Constructs a new line. + * + * @param {BufferGeometry} [geometry] - The line geometry. + * @param {Material|Array} [material] - The line material. + */ + constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) { + + super(); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isLine = true; + + this.type = 'Line'; + + /** + * The line geometry. + * + * @type {BufferGeometry} + */ + this.geometry = geometry; + + /** + * The line material. + * + * @type {Material|Array} + * @default LineBasicMaterial + */ + this.material = material; + + /** + * A dictionary representing the morph targets in the geometry. The key is the + * morph targets name, the value its attribute index. This member is `undefined` + * by default and only set when morph targets are detected in the geometry. + * + * @type {Object|undefined} + * @default undefined + */ + this.morphTargetDictionary = undefined; + + /** + * An array of weights typically in the range `[0,1]` that specify how much of the morph + * is applied. This member is `undefined` by default and only set when morph targets are + * detected in the geometry. + * + * @type {Array|undefined} + * @default undefined + */ + this.morphTargetInfluences = undefined; + + this.updateMorphTargets(); + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + this.material = Array.isArray( source.material ) ? source.material.slice() : source.material; + this.geometry = source.geometry; + + return this; + + } + + /** + * Computes an array of distance values which are necessary for rendering dashed lines. + * For each vertex in the geometry, the method calculates the cumulative length from the + * current point to the very beginning of the line. + * + * @return {Line} A reference to this line. + */ + computeLineDistances() { + + const geometry = this.geometry; + + // we assume non-indexed geometry + + if ( geometry.index === null ) { + + const positionAttribute = geometry.attributes.position; + const lineDistances = [ 0 ]; + + for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) { + + _vStart.fromBufferAttribute( positionAttribute, i - 1 ); + _vEnd.fromBufferAttribute( positionAttribute, i ); + + lineDistances[ i ] = lineDistances[ i - 1 ]; + lineDistances[ i ] += _vStart.distanceTo( _vEnd ); + + } + + geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) ); + + } else { + + warn( 'Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' ); + + } + + return this; + + } + + /** + * Returns `true` if this line intersects the given frustum. + * + * @param {Frustum|FrustumArray} frustum - The frustum to test. + * @return {boolean} Whether this line intersects the given frustum or not. + */ + intersectsFrustum( frustum ) { + + return frustum.intersectsObject( this ); + + } + + /** + * Computes intersection points between a casted ray and this line. + * + * @param {Raycaster} raycaster - The raycaster. + * @param {Array} intersects - The target array that holds the intersection points. + */ + raycast( raycaster, intersects ) { + + const geometry = this.geometry; + const matrixWorld = this.matrixWorld; + const threshold = raycaster.params.Line.threshold; + const drawRange = geometry.drawRange; + + // Checking boundingSphere distance to ray + + if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); + + _sphere$1.copy( geometry.boundingSphere ); + _sphere$1.applyMatrix4( matrixWorld ); + _sphere$1.radius += threshold; + + if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return; + + // + + _inverseMatrix$1.copy( matrixWorld ).invert(); + _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 ); + + const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 ); + const localThresholdSq = localThreshold * localThreshold; + + const step = this.isLineSegments ? 2 : 1; + + const index = geometry.index; + const attributes = geometry.attributes; + const positionAttribute = attributes.position; + + if ( index !== null ) { + + const start = Math.max( 0, drawRange.start ); + const end = Math.min( index.count, ( drawRange.start + drawRange.count ) ); + + for ( let i = start, l = end - 1; i < l; i += step ) { + + const a = index.getX( i ); + const b = index.getX( i + 1 ); + + const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, i ); + + if ( intersect ) { + + intersects.push( intersect ); + + } + + } + + if ( this.isLineLoop ) { + + const a = index.getX( end - 1 ); + const b = index.getX( start ); + + const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, end - 1 ); + + if ( intersect ) { + + intersects.push( intersect ); + + } + + } + + } else { + + const start = Math.max( 0, drawRange.start ); + const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) ); + + for ( let i = start, l = end - 1; i < l; i += step ) { + + const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, i, i + 1, i ); + + if ( intersect ) { + + intersects.push( intersect ); + + } + + } + + if ( this.isLineLoop ) { + + const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, end - 1, start, end - 1 ); + + if ( intersect ) { + + intersects.push( intersect ); + + } + + } + + } + + } + + /** + * Sets the values of {@link Line#morphTargetDictionary} and {@link Line#morphTargetInfluences} + * to make sure existing morph targets can influence this 3D object. + */ + updateMorphTargets() { + + const geometry = this.geometry; + + const morphAttributes = geometry.morphAttributes; + const keys = Object.keys( morphAttributes ); + + if ( keys.length > 0 ) { + + const morphAttribute = morphAttributes[ keys[ 0 ] ]; + + if ( morphAttribute !== undefined ) { + + this.morphTargetInfluences = []; + this.morphTargetDictionary = {}; + + for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) { + + const name = morphAttribute[ m ].name || String( m ); + + this.morphTargetInfluences.push( 0 ); + this.morphTargetDictionary[ name ] = m; + + } + + } + + } + + } + +} + +function checkIntersection( object, raycaster, ray, thresholdSq, a, b, i ) { + + const positionAttribute = object.geometry.attributes.position; + + _vStart.fromBufferAttribute( positionAttribute, a ); + _vEnd.fromBufferAttribute( positionAttribute, b ); + + const distSq = ray.distanceSqToSegment( _vStart, _vEnd, _intersectPointOnRay, _intersectPointOnSegment ); + + if ( distSq > thresholdSq ) return; + + _intersectPointOnRay.applyMatrix4( object.matrixWorld ); // Move back to world space for distance calculation + + const distance = raycaster.ray.origin.distanceTo( _intersectPointOnRay ); + + if ( distance < raycaster.near || distance > raycaster.far ) return; + + return { + + distance: distance, + // What do we want? intersection point on the ray or on the segment?? + // point: raycaster.ray.at( distance ), + point: _intersectPointOnSegment.clone().applyMatrix4( object.matrixWorld ), + index: i, + face: null, + faceIndex: null, + barycoord: null, + object: object + + }; + +} + +const _start = /*@__PURE__*/ new Vector3(); +const _end = /*@__PURE__*/ new Vector3(); + +/** + * A series of lines drawn between pairs of vertices. + * + * @augments Line + */ +class LineSegments extends Line { + + /** + * Constructs a new line segments. + * + * @param {BufferGeometry} [geometry] - The line geometry. + * @param {Material|Array} [material] - The line material. + */ + constructor( geometry, material ) { + + super( geometry, material ); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isLineSegments = true; + + this.type = 'LineSegments'; + + } + + computeLineDistances() { + + const geometry = this.geometry; + + // we assume non-indexed geometry + + if ( geometry.index === null ) { + + const positionAttribute = geometry.attributes.position; + const lineDistances = []; + + for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) { + + _start.fromBufferAttribute( positionAttribute, i ); + _end.fromBufferAttribute( positionAttribute, i + 1 ); + + lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ]; + lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end ); + + } + + geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) ); + + } else { + + warn( 'LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' ); + + } + + return this; + + } + +} + +/** + * A continuous line. This is nearly the same as {@link Line} the only difference + * is that the last vertex is connected with the first vertex in order to close + * the line to form a loop. + * + * @augments Line + */ +class LineLoop extends Line { + + /** + * Constructs a new line loop. + * + * @param {BufferGeometry} [geometry] - The line geometry. + * @param {Material|Array} [material] - The line material. + */ + constructor( geometry, material ) { + + super( geometry, material ); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isLineLoop = true; + + this.type = 'LineLoop'; + + } + +} + +/** + * A material for rendering point primitives. + * + * Materials define the appearance of renderable 3D objects. + * + * ```js + * const vertices = []; + * + * for ( let i = 0; i < 10000; i ++ ) { + * const x = THREE.MathUtils.randFloatSpread( 2000 ); + * const y = THREE.MathUtils.randFloatSpread( 2000 ); + * const z = THREE.MathUtils.randFloatSpread( 2000 ); + * + * vertices.push( x, y, z ); + * } + * + * const geometry = new THREE.BufferGeometry(); + * geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( vertices, 3 ) ); + * const material = new THREE.PointsMaterial( { color: 0x888888 } ); + * const points = new THREE.Points( geometry, material ); + * scene.add( points ); + * ``` + * + * @augments Material + */ +class PointsMaterial extends Material { + + /** + * Constructs a new points material. + * + * @param {Object} [parameters] - An object with one or more properties + * defining the material's appearance. Any property of the material + * (including any property from inherited materials) can be passed + * in here. Color values can be passed any type of value accepted + * by {@link Color#set}. + */ + constructor( parameters ) { + + super(); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isPointsMaterial = true; + + this.type = 'PointsMaterial'; + + /** + * Color of the material. + * + * @type {Color} + * @default (1,1,1) + */ + this.color = new Color( 0xffffff ); + + /** + * The color map. May optionally include an alpha channel, typically combined + * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map + * color is modulated by the diffuse `color`. + * + * `map` represents color data, and the texture must be assigned a + * {@link Texture#colorSpace}. Most `map` textures set + * `texture.colorSpace = SRGBColorSpace`. + * + * @type {?Texture} + * @default null + */ + this.map = null; + + /** + * The alpha map is a grayscale texture that controls the opacity across the + * surface (black: fully transparent; white: fully opaque). + * + * Only the color of the texture is used, ignoring the alpha channel if one + * exists. For RGB and RGBA textures, the renderer will use the green channel + * when sampling this texture due to the extra bit of precision provided for + * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and + * luminance/alpha textures will also still work as expected. + * + * `alphaMap` represents non-color data. Any texture assigned must have + * `texture.colorSpace = NoColorSpace` (default). + * + * @type {?Texture} + * @default null + */ + this.alphaMap = null; + + /** + * Defines the size of the points in pixels. + * + * Might be capped if the value exceeds hardware dependent parameters like [gl.ALIASED_POINT_SIZE_RANGE](https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getParamete). + * + * @type {number} + * @default 1 + */ + this.size = 1; + + /** + * Specifies whether size of individual points is attenuated by the camera depth (perspective camera only). + * + * @type {boolean} + * @default true + */ + this.sizeAttenuation = true; + + /** + * Whether the material is affected by fog or not. + * + * @type {boolean} + * @default true + */ + this.fog = true; + + this.setValues( parameters ); + + } + + copy( source ) { + + super.copy( source ); + + this.color.copy( source.color ); + + this.map = source.map; + + this.alphaMap = source.alphaMap; + + this.size = source.size; + this.sizeAttenuation = source.sizeAttenuation; + + this.fog = source.fog; + + return this; + + } + +} + +const _inverseMatrix = /*@__PURE__*/ new Matrix4(); +const _ray = /*@__PURE__*/ new Ray(); +const _sphere = /*@__PURE__*/ new Sphere(); +const _position$3 = /*@__PURE__*/ new Vector3(); + +/** + * A class for displaying points or point clouds. + * + * @augments Object3D + */ +class Points extends Object3D { + + /** + * Constructs a new point cloud. + * + * @param {BufferGeometry} [geometry] - The points geometry. + * @param {Material|Array} [material] - The points material. + */ + constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) { + + super(); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isPoints = true; + + this.type = 'Points'; + + /** + * The points geometry. + * + * @type {BufferGeometry} + */ + this.geometry = geometry; + + /** + * The line material. + * + * @type {Material|Array} + * @default PointsMaterial + */ + this.material = material; + + /** + * A dictionary representing the morph targets in the geometry. The key is the + * morph targets name, the value its attribute index. This member is `undefined` + * by default and only set when morph targets are detected in the geometry. + * + * @type {Object|undefined} + * @default undefined + */ + this.morphTargetDictionary = undefined; + + /** + * An array of weights typically in the range `[0,1]` that specify how much of the morph + * is applied. This member is `undefined` by default and only set when morph targets are + * detected in the geometry. + * + * @type {Array|undefined} + * @default undefined + */ + this.morphTargetInfluences = undefined; + + this.updateMorphTargets(); + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + this.material = Array.isArray( source.material ) ? source.material.slice() : source.material; + this.geometry = source.geometry; + + return this; + + } + + /** + * Returns `true` if this point cloud intersects the given frustum. + * + * @param {Frustum|FrustumArray} frustum - The frustum to test. + * @return {boolean} Whether this point cloud intersects the given frustum or not. + */ + intersectsFrustum( frustum ) { + + return frustum.intersectsObject( this ); + + } + + /** + * Computes intersection points between a casted ray and this point cloud. + * + * @param {Raycaster} raycaster - The raycaster. + * @param {Array} intersects - The target array that holds the intersection points. + */ + raycast( raycaster, intersects ) { + + const geometry = this.geometry; + const matrixWorld = this.matrixWorld; + const threshold = raycaster.params.Points.threshold; + const drawRange = geometry.drawRange; + + // Checking boundingSphere distance to ray + + if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); + + _sphere.copy( geometry.boundingSphere ); + _sphere.applyMatrix4( matrixWorld ); + _sphere.radius += threshold; + + if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return; + + // + + _inverseMatrix.copy( matrixWorld ).invert(); + _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix ); + + const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 ); + const localThresholdSq = localThreshold * localThreshold; + + const index = geometry.index; + const attributes = geometry.attributes; + const positionAttribute = attributes.position; + + if ( index !== null ) { + + const start = Math.max( 0, drawRange.start ); + const end = Math.min( index.count, ( drawRange.start + drawRange.count ) ); + + for ( let i = start, il = end; i < il; i ++ ) { + + const a = index.getX( i ); + + _position$3.fromBufferAttribute( positionAttribute, a ); + + testPoint( _position$3, a, localThresholdSq, matrixWorld, raycaster, intersects, this ); + + } + + } else { + + const start = Math.max( 0, drawRange.start ); + const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) ); + + for ( let i = start, l = end; i < l; i ++ ) { + + _position$3.fromBufferAttribute( positionAttribute, i ); + + testPoint( _position$3, i, localThresholdSq, matrixWorld, raycaster, intersects, this ); + + } + + } + + } + + /** + * Sets the values of {@link Points#morphTargetDictionary} and {@link Points#morphTargetInfluences} + * to make sure existing morph targets can influence this 3D object. + */ + updateMorphTargets() { + + const geometry = this.geometry; + + const morphAttributes = geometry.morphAttributes; + const keys = Object.keys( morphAttributes ); + + if ( keys.length > 0 ) { + + const morphAttribute = morphAttributes[ keys[ 0 ] ]; + + if ( morphAttribute !== undefined ) { + + this.morphTargetInfluences = []; + this.morphTargetDictionary = {}; + + for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) { + + const name = morphAttribute[ m ].name || String( m ); + + this.morphTargetInfluences.push( 0 ); + this.morphTargetDictionary[ name ] = m; + + } + + } + + } + + } + +} + +function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) { + + const rayPointDistanceSq = _ray.distanceSqToPoint( point ); + + if ( rayPointDistanceSq < localThresholdSq ) { + + const intersectPoint = new Vector3(); + + _ray.closestPointToPoint( point, intersectPoint ); + intersectPoint.applyMatrix4( matrixWorld ); + + const distance = raycaster.ray.origin.distanceTo( intersectPoint ); + + if ( distance < raycaster.near || distance > raycaster.far ) return; + + intersects.push( { + + distance: distance, + distanceToRay: Math.sqrt( rayPointDistanceSq ), + point: intersectPoint, + index: index, + face: null, + faceIndex: null, + barycoord: null, + object: object + + } ); + + } + +} + +/** + * A texture for use with a video. + * + * ```js + * // assuming you have created a HTML video element with id="video" + * const video = document.getElementById( 'video' ); + * const texture = new THREE.VideoTexture( video ); + * ``` + * + * Note: When using video textures with {@link WebGPURenderer}, {@link Texture#colorSpace} must be + * set to THREE.SRGBColorSpace. + * + * Note: After the initial use of a texture, its dimensions, format, and type + * cannot be changed. Instead, call {@link Texture#dispose} on the texture and instantiate a new one. + * + * @augments Texture + */ +class VideoTexture extends Texture { + + /** + * Constructs a new video texture. + * + * @param {HTMLVideoElement} video - The video element to use as a data source for the texture. + * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping. + * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value. + * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value. + * @param {number} [magFilter=LinearFilter] - The mag filter value. + * @param {number} [minFilter=LinearFilter] - The min filter value. + * @param {number} [format=RGBAFormat] - The texture format. + * @param {number} [type=UnsignedByteType] - The texture type. + * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value. + */ + constructor( video, mapping, wrapS, wrapT, magFilter = LinearFilter, minFilter = LinearFilter, format, type, anisotropy ) { + + super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isVideoTexture = true; + + /** + * Whether to generate mipmaps (if possible) for a texture. + * + * Overwritten and set to `false` by default. + * + * @type {boolean} + * @default false + */ + this.generateMipmaps = false; + + /** + * The video frame request callback identifier, which is a positive integer. + * + * Value of 0 represents no scheduled rVFC. + * + * @private + * @type {number} + */ + this._requestVideoFrameCallbackId = 0; + + const scope = this; + + function updateVideo() { + + scope.needsUpdate = true; + scope._requestVideoFrameCallbackId = video.requestVideoFrameCallback( updateVideo ); + + } + + if ( 'requestVideoFrameCallback' in video ) { + + this._requestVideoFrameCallbackId = video.requestVideoFrameCallback( updateVideo ); + + } + + } + + clone() { + + return new this.constructor( this.image ).copy( this ); + + } + + /** + * This method is called automatically by the renderer and sets {@link Texture#needsUpdate} + * to `true` every time a new frame is available. + * + * Only relevant if `requestVideoFrameCallback` is not supported in the browser. + */ + update() { + + const video = this.image; + const hasVideoFrameCallback = 'requestVideoFrameCallback' in video; + + if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) { + + this.needsUpdate = true; + + } + + } + + dispose() { + + if ( this._requestVideoFrameCallbackId !== 0 ) { + + this.source.data.cancelVideoFrameCallback( this._requestVideoFrameCallbackId ); + + this._requestVideoFrameCallbackId = 0; + + } + + super.dispose(); + + } + +} + +/** + * This class can be used as an alternative way to define video data. Instead of using + * an instance of `HTMLVideoElement` like with `VideoTexture`, `VideoFrameTexture` expects each frame is + * defined manually via {@link VideoFrameTexture#setFrame}. A typical use case for this module is when + * video frames are decoded with the WebCodecs API. + * + * ```js + * const texture = new THREE.VideoFrameTexture(); + * texture.setFrame( frame ); + * ``` + * + * @augments VideoTexture + */ +class VideoFrameTexture extends VideoTexture { + + /** + * Constructs a new video frame texture. + * + * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping. + * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value. + * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value. + * @param {number} [magFilter=LinearFilter] - The mag filter value. + * @param {number} [minFilter=LinearFilter] - The min filter value. + * @param {number} [format=RGBAFormat] - The texture format. + * @param {number} [type=UnsignedByteType] - The texture type. + * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value. + */ + constructor( mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { + + super( {}, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isVideoFrameTexture = true; + + } + + /** + * This method overwritten with an empty implementation since + * this type of texture is updated via `setFrame()`. + */ + update() {} + + clone() { + + return new this.constructor().copy( this ); // restoring Texture.clone() + + } + + /** + * Sets the current frame of the video. This will automatically update the texture + * so the data can be used for rendering. + * + * @param {VideoFrame} frame - The video frame. + */ + setFrame( frame ) { + + this.image = frame; + this.needsUpdate = true; + + } + +} + +/** + * This class can only be used in combination with `copyFramebufferToTexture()` methods + * of renderers. It extracts the contents of the current bound framebuffer and provides it + * as a texture for further usage. + * + * ```js + * const pixelRatio = window.devicePixelRatio; + * const textureSize = 128 * pixelRatio; + * + * const frameTexture = new FramebufferTexture( textureSize, textureSize ); + * + * // calculate start position for copying part of the frame data + * const vector = new Vector2(); + * vector.x = ( window.innerWidth * pixelRatio / 2 ) - ( textureSize / 2 ); + * vector.y = ( window.innerHeight * pixelRatio / 2 ) - ( textureSize / 2 ); + * + * renderer.render( scene, camera ); + * + * // copy part of the rendered frame into the framebuffer texture + * renderer.copyFramebufferToTexture( frameTexture, vector ); + * ``` + * + * @augments Texture + */ +class FramebufferTexture extends Texture { + + /** + * Constructs a new framebuffer texture. + * + * @param {number} [width] - The width of the texture. + * @param {number} [height] - The height of the texture. + */ + constructor( width, height ) { + + super( { width, height } ); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isFramebufferTexture = true; + + /** + * How the texture is sampled when a texel covers more than one pixel. + * + * Overwritten and set to `NearestFilter` by default to disable filtering. + * + * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)} + * @default NearestFilter + */ + this.magFilter = NearestFilter; + + /** + * How the texture is sampled when a texel covers less than one pixel. + * + * Overwritten and set to `NearestFilter` by default to disable filtering. + * + * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)} + * @default NearestFilter + */ + this.minFilter = NearestFilter; + + /** + * Whether to generate mipmaps (if possible) for a texture. + * + * Overwritten and set to `false` by default. + * + * @type {boolean} + * @default false + */ + this.generateMipmaps = false; + + this.needsUpdate = true; + + } + +} + +/** + * Creates a texture based on data in compressed form. + * + * These texture are usually loaded with {@link CompressedTextureLoader}. + * + * @augments Texture + */ +class CompressedTexture extends Texture { + + /** + * Constructs a new compressed texture. + * + * @param {Array} mipmaps - This array holds for all mipmaps (including the bases mip) + * the data and dimensions. + * @param {number} width - The width of the texture. + * @param {number} height - The height of the texture. + * @param {number} [format=RGBAFormat] - The texture format. + * @param {number} [type=UnsignedByteType] - The texture type. + * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping. + * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value. + * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value. + * @param {number} [magFilter=LinearFilter] - The mag filter value. + * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value. + * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value. + * @param {string} [colorSpace=NoColorSpace] - The color space. + */ + constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace ) { + + super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace ); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isCompressedTexture = true; + + /** + * The image property of a compressed texture just defines its dimensions. + * + * @type {{width:number,height:number}} + */ + this.image = { width: width, height: height }; + + /** + * This array holds for all mipmaps (including the bases mip) the data and dimensions. + * + * @type {Array} + */ + this.mipmaps = mipmaps; + + /** + * If set to `true`, the texture is flipped along the vertical axis when + * uploaded to the GPU. + * + * Overwritten and set to `false` by default since it is not possible to + * flip compressed textures. + * + * @type {boolean} + * @default false + * @readonly + */ + this.flipY = false; + + /** + * Whether to generate mipmaps (if possible) for a texture. + * + * Overwritten and set to `false` by default since it is not + * possible to generate mipmaps for compressed data. Mipmaps + * must be embedded in the compressed texture file. + * + * @type {boolean} + * @default false + * @readonly + */ + this.generateMipmaps = false; + + } + +} + +/** + * Creates a texture 2D array based on data in compressed form. + * + * These texture are usually loaded with {@link CompressedTextureLoader}. + * + * @augments CompressedTexture + */ +class CompressedArrayTexture extends CompressedTexture { + + /** + * Constructs a new compressed array texture. + * + * @param {Array} mipmaps - This array holds for all mipmaps (including the bases mip) + * the data and dimensions. + * @param {number} width - The width of the texture. + * @param {number} height - The height of the texture. + * @param {number} depth - The depth of the texture. + * @param {number} [format=RGBAFormat] - The min filter value. + * @param {number} [type=UnsignedByteType] - The min filter value. + */ + constructor( mipmaps, width, height, depth, format, type ) { + + super( mipmaps, width, height, format, type ); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isCompressedArrayTexture = true; + + /** + * The image property of a compressed texture just defines its dimensions. + * + * @name CompressedArrayTexture#image + * @type {{width:number,height:number,depth:number}} + */ + this.image.depth = depth; + + /** + * This defines how the texture is wrapped in the depth and corresponds to + * *W* in UVW mapping. + * + * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)} + * @default ClampToEdgeWrapping + */ + this.wrapR = ClampToEdgeWrapping; + + /** + * A set of all layers which need to be updated in the texture. + * + * @type {Set} + */ + this.layerUpdates = new Set(); + + } + + /** + * Copies the values of the given texture to this instance. + * + * @param {CompressedArrayTexture} source - The texture to copy. + * @return {CompressedArrayTexture} A reference to this instance. + */ + copy( source ) { + + super.copy( source ); + + this.wrapR = source.wrapR; + + return this; + + } + + /** + * Describes that a specific layer of the texture needs to be updated. + * Normally when {@link Texture#needsUpdate} is set to `true`, the + * entire compressed texture array is sent to the GPU. Marking specific + * layers will only transmit subsets of all mipmaps associated with a + * specific depth in the array which is often much more performant. + * + * @param {number} layerIndex - The layer index that should be updated. + */ + addLayerUpdate( layerIndex ) { + + this.layerUpdates.add( layerIndex ); + + } + + /** + * Resets the layer updates registry. + */ + clearLayerUpdates() { + + this.layerUpdates.clear(); + + } + +} + +/** + * Creates a cube texture based on data in compressed form. + * + * These texture are usually loaded with {@link CompressedTextureLoader}. + * + * @augments CompressedTexture + */ +class CompressedCubeTexture extends CompressedTexture { + + /** + * Constructs a new compressed texture. + * + * @param {Array} images - An array of compressed textures. + * @param {number} [format=RGBAFormat] - The texture format. + * @param {number} [type=UnsignedByteType] - The texture type. + */ + constructor( images, format, type ) { + + super( undefined, images[ 0 ].width, images[ 0 ].height, format, type, CubeReflectionMapping ); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isCompressedCubeTexture = true; + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isCubeTexture = true; + + this.image = images; + + } + +} + +/** + * Creates a cube texture made up of six images. + * + * ```js + * const loader = new THREE.CubeTextureLoader(); + * loader.setPath( 'textures/cube/pisa/' ); + * + * const textureCube = loader.load( [ + * 'px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png' + * ] ); + * + * const material = new THREE.MeshBasicMaterial( { color: 0xffffff, envMap: textureCube } ); + * ``` + * + * @augments Texture + */ +class CubeTexture extends Texture { + + /** + * Constructs a new cube texture. + * + * @param {Array} [images=[]] - An array holding a image for each side of a cube. + * @param {number} [mapping=CubeReflectionMapping] - The texture mapping. + * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value. + * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value. + * @param {number} [magFilter=LinearFilter] - The mag filter value. + * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value. + * @param {number} [format=RGBAFormat] - The texture format. + * @param {number} [type=UnsignedByteType] - The texture type. + * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value. + * @param {string} [colorSpace=NoColorSpace] - The color space value. + */ + constructor( images = [], mapping = CubeReflectionMapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace ) { + + super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace ); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isCubeTexture = true; + + /** + * If set to `true`, the texture is flipped along the vertical axis when + * uploaded to the GPU. + * + * Overwritten and set to `false` by default. + * + * @type {boolean} + * @default false + */ + this.flipY = false; + + } + + /** + * Alias for {@link CubeTexture#image}. + * + * @type {Array} + */ + get images() { + + return this.image; + + } + + set images( value ) { + + this.image = value; + + } + +} + +/** + * Creates a texture from a canvas element. + * + * This is almost the same as the base texture class, except that it sets {@link Texture#needsUpdate} + * to `true` immediately since a canvas can directly be used for rendering. + * + * @augments Texture + */ +class CanvasTexture extends Texture { + + /** + * Constructs a new texture. + * + * @param {HTMLCanvasElement} [canvas] - The HTML canvas element. + * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping. + * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value. + * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value. + * @param {number} [magFilter=LinearFilter] - The mag filter value. + * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value. + * @param {number} [format=RGBAFormat] - The texture format. + * @param {number} [type=UnsignedByteType] - The texture type. + * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value. + */ + constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { + + super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isCanvasTexture = true; + + this.needsUpdate = true; + + } + +} + +/** + * Creates a texture from an HTML element. + * + * This is almost the same as the base texture class, except that it sets {@link Texture#needsUpdate} + * to `true` immediately and listens for the parent canvas's paint events to trigger updates. + * + * @augments Texture + */ +class HTMLTexture extends Texture { + + /** + * Constructs a new texture. + * + * @param {HTMLElement} [element] - The HTML element. + * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping. + * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value. + * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value. + * @param {number} [magFilter=LinearFilter] - The mag filter value. + * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value. + * @param {number} [format=RGBAFormat] - The texture format. + * @param {number} [type=UnsignedByteType] - The texture type. + * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value. + */ + constructor( element, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { + + super( element, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isHTMLTexture = true; + this.generateMipmaps = false; + + this.needsUpdate = true; + + const parent = element ? element.parentNode : null; + + if ( parent !== null && 'requestPaint' in parent ) { + + parent.onpaint = () => { + + this.needsUpdate = true; + + }; + + parent.requestPaint(); + + } + + } + + dispose() { + + const parent = this.image ? this.image.parentNode : null; + + if ( parent !== null && 'onpaint' in parent ) { + + parent.onpaint = null; + + } + + super.dispose(); + + } + +} + +/** + * This class can be used to automatically save the depth information of a + * rendering into a texture. + * + * @augments Texture + */ +class DepthTexture extends Texture { + + /** + * Constructs a new depth texture. + * + * @param {number} width - The width of the texture. + * @param {number} height - The height of the texture. + * @param {number} [type=UnsignedIntType] - The texture type. + * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping. + * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value. + * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value. + * @param {number} [magFilter=LinearFilter] - The mag filter value. + * @param {number} [minFilter=LinearFilter] - The min filter value. + * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value. + * @param {number} [format=DepthFormat] - The texture format. + * @param {number} [depth=1] - The depth of the texture. + */ + constructor( width, height, type = UnsignedIntType, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, format = DepthFormat, depth = 1 ) { + + if ( format !== DepthFormat && format !== DepthStencilFormat ) { + + throw new Error( 'THREE.DepthTexture: format must be either THREE.DepthFormat or THREE.DepthStencilFormat' ); + + } + + const image = { width: width, height: height, depth: depth }; + + super( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isDepthTexture = true; + + /** + * If set to `true`, the texture is flipped along the vertical axis when + * uploaded to the GPU. + * + * Overwritten and set to `false` by default. + * + * @type {boolean} + * @default false + */ + this.flipY = false; + + /** + * Whether to generate mipmaps (if possible) for a texture. + * + * Overwritten and set to `false` by default. + * + * @type {boolean} + * @default false + */ + this.generateMipmaps = false; + + /** + * Code corresponding to the depth compare function. + * + * @type {?(NeverCompare|LessCompare|EqualCompare|LessEqualCompare|GreaterCompare|NotEqualCompare|GreaterEqualCompare|AlwaysCompare)} + * @default null + */ + this.compareFunction = null; + + } + + + copy( source ) { + + super.copy( source ); + + this.source = new TextureSource( Object.assign( {}, source.image ) ); // see #30540 + this.compareFunction = source.compareFunction; + + return this; + + } + + toJSON( meta ) { + + const data = super.toJSON( meta ); + + data.compareFunction = this.compareFunction; + + return data; + + } + +} + +/** + * This class can be used to automatically save the depth information of a + * cube rendering into a cube texture with depth format. Used for PointLight shadows. + * + * @augments DepthTexture + */ +class CubeDepthTexture extends DepthTexture { + + /** + * Constructs a new cube depth texture. + * + * @param {number} size - The size (width and height) of each cube face. + * @param {number} [type=UnsignedIntType] - The texture type. + * @param {number} [mapping=CubeReflectionMapping] - The texture mapping. + * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value. + * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value. + * @param {number} [magFilter=NearestFilter] - The mag filter value. + * @param {number} [minFilter=NearestFilter] - The min filter value. + * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value. + * @param {number} [format=DepthFormat] - The texture format. + */ + constructor( size, type = UnsignedIntType, mapping = CubeReflectionMapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, format = DepthFormat ) { + + // Create 6 identical image descriptors for the cube faces + const image = { width: size, height: size, depth: 1 }; + const images = [ image, image, image, image, image, image ]; + + // Call DepthTexture constructor with width, height + super( size, size, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ); + + // Replace the single image with the array of 6 images + this.image = images; + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isCubeDepthTexture = true; + + /** + * Set to true for cube texture handling in WebGLTextures. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isCubeTexture = true; + + } + + /** + * Alias for {@link CubeDepthTexture#image}. + * + * @type {Array} + */ + get images() { + + return this.image; + + } + + set images( value ) { + + this.image = value; + + } + +} + +/** + * Represents a texture created externally with the same renderer context. + * + * This may be a texture from a protected media stream, device camera feed, + * or other data feeds like a depth sensor. + * + * @augments Texture + */ +class ExternalTexture extends Texture { + + /** + * Creates a new raw texture. + * + * @param {?(WebGLTexture|GPUTexture)} [sourceTexture=null] - The external texture. + */ + constructor( sourceTexture = null ) { + + super(); + + /** + * The external source texture. + * + * @type {?(WebGLTexture|GPUTexture)} + * @default null + */ + this.sourceTexture = sourceTexture; + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isExternalTexture = true; + + } + + copy( source ) { + + super.copy( source ); + + this.sourceTexture = source.sourceTexture; + + return this; + + } + +} + +/** + * A geometry class for a rectangular cuboid with a given width, height, and depth. + * On creation, the cuboid is centred on the origin, with each edge parallel to one + * of the axes. + * + * ```js + * const geometry = new THREE.BoxGeometry( 1, 1, 1 ); + * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } ); + * const cube = new THREE.Mesh( geometry, material ); + * scene.add( cube ); + * ``` + * + * @augments BufferGeometry + * @demo scenes/geometry-browser.html#BoxGeometry + */ +class BoxGeometry extends BufferGeometry { + + /** + * Constructs a new box geometry. + * + * @param {number} [width=1] - The width. That is, the length of the edges parallel to the X axis. + * @param {number} [height=1] - The height. That is, the length of the edges parallel to the Y axis. + * @param {number} [depth=1] - The depth. That is, the length of the edges parallel to the Z axis. + * @param {number} [widthSegments=1] - Number of segmented rectangular faces along the width of the sides. + * @param {number} [heightSegments=1] - Number of segmented rectangular faces along the height of the sides. + * @param {number} [depthSegments=1] - Number of segmented rectangular faces along the depth of the sides. + */ + constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) { + + super(); + + this.type = 'BoxGeometry'; + + /** + * Holds the constructor parameters that have been + * used to generate the geometry. Any modification + * after instantiation does not change the geometry. + * + * @type {Object} + */ + this.parameters = { + width: width, + height: height, + depth: depth, + widthSegments: widthSegments, + heightSegments: heightSegments, + depthSegments: depthSegments + }; + + const scope = this; + + // segments + + widthSegments = Math.floor( widthSegments ); + heightSegments = Math.floor( heightSegments ); + depthSegments = Math.floor( depthSegments ); + + // buffers + + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + + // helper variables + + let numberOfVertices = 0; + let groupStart = 0; + + // build each side of the box geometry + + buildPlane( 'z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0 ); // px + buildPlane( 'z', 'y', 'x', 1, -1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx + buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py + buildPlane( 'x', 'z', 'y', 1, -1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny + buildPlane( 'x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4 ); // pz + buildPlane( 'x', 'y', 'z', -1, -1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz + + // build geometry + + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + + function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) { + + const segmentWidth = width / gridX; + const segmentHeight = height / gridY; + + const widthHalf = width / 2; + const heightHalf = height / 2; + const depthHalf = depth / 2; + + const gridX1 = gridX + 1; + const gridY1 = gridY + 1; + + let vertexCounter = 0; + let groupCount = 0; + + const vector = new Vector3(); + + // generate vertices, normals and uvs + + for ( let iy = 0; iy < gridY1; iy ++ ) { + + const y = iy * segmentHeight - heightHalf; + + for ( let ix = 0; ix < gridX1; ix ++ ) { + + const x = ix * segmentWidth - widthHalf; + + // set values to correct vector component + + vector[ u ] = x * udir; + vector[ v ] = y * vdir; + vector[ w ] = depthHalf; + + // now apply vector to vertex buffer + + vertices.push( vector.x, vector.y, vector.z ); + + // set values to correct vector component + + vector[ u ] = 0; + vector[ v ] = 0; + vector[ w ] = depth > 0 ? 1 : -1; + + // now apply vector to normal buffer + + normals.push( vector.x, vector.y, vector.z ); + + // uvs + + uvs.push( ix / gridX ); + uvs.push( 1 - ( iy / gridY ) ); + + // counters + + vertexCounter += 1; + + } + + } + + // indices + + // 1. you need three indices to draw a single face + // 2. a single segment consists of two faces + // 3. so we need to generate six (2*3) indices per segment + + for ( let iy = 0; iy < gridY; iy ++ ) { + + for ( let ix = 0; ix < gridX; ix ++ ) { + + const a = numberOfVertices + ix + gridX1 * iy; + const b = numberOfVertices + ix + gridX1 * ( iy + 1 ); + const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 ); + const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy; + + // faces + + indices.push( a, b, d ); + indices.push( b, c, d ); + + // increase counter + + groupCount += 6; + + } + + } + + // add a group to the geometry. this will ensure multi material support + + scope.addGroup( groupStart, groupCount, materialIndex ); + + // calculate new start value for groups + + groupStart += groupCount; + + // update total number of vertices + + numberOfVertices += vertexCounter; + + } + + } + + copy( source ) { + + super.copy( source ); + + this.parameters = Object.assign( {}, source.parameters ); + + return this; + + } + + /** + * Factory method for creating an instance of this class from the given + * JSON object. + * + * @param {Object} data - A JSON object representing the serialized geometry. + * @return {BoxGeometry} A new instance. + */ + static fromJSON( data ) { + + return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments ); + + } + +} + +/** + * A geometry class for representing a capsule. + * + * ```js + * const geometry = new THREE.CapsuleGeometry( 1, 1, 4, 8, 1 ); + * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } ); + * const capsule = new THREE.Mesh( geometry, material ); + * scene.add( capsule ); + * ``` + * + * @augments BufferGeometry + * @demo scenes/geometry-browser.html#CapsuleGeometry + */ +class CapsuleGeometry extends BufferGeometry { + + /** + * Constructs a new capsule geometry. + * + * @param {number} [radius=1] - Radius of the capsule. + * @param {number} [height=1] - Height of the middle section. + * @param {number} [capSegments=4] - Number of curve segments used to build each cap. + * @param {number} [radialSegments=8] - Number of segmented faces around the circumference of the capsule. Must be an integer >= 3. + * @param {number} [heightSegments=1] - Number of rows of faces along the height of the middle section. Must be an integer >= 1. + */ + constructor( radius = 1, height = 1, capSegments = 4, radialSegments = 8, heightSegments = 1 ) { + + super(); + + this.type = 'CapsuleGeometry'; + + /** + * Holds the constructor parameters that have been + * used to generate the geometry. Any modification + * after instantiation does not change the geometry. + * + * @type {Object} + */ + this.parameters = { + radius: radius, + height: height, + capSegments: capSegments, + radialSegments: radialSegments, + heightSegments: heightSegments, + }; + + height = Math.max( 0, height ); + capSegments = Math.max( 1, Math.floor( capSegments ) ); + radialSegments = Math.max( 3, Math.floor( radialSegments ) ); + heightSegments = Math.max( 1, Math.floor( heightSegments ) ); + + // buffers + + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + + // helper variables + + const halfHeight = height / 2; + const capArcLength = ( Math.PI / 2 ) * radius; + const cylinderPartLength = height; + const totalArcLength = 2 * capArcLength + cylinderPartLength; + + const numVerticalSegments = capSegments * 2 + heightSegments; + const verticesPerRow = radialSegments + 1; + + const normal = new Vector3(); + const vertex = new Vector3(); + + // generate vertices, normals, and uvs + + for ( let iy = 0; iy <= numVerticalSegments; iy ++ ) { + + let currentArcLength = 0; + let profileY = 0; + let profileRadius = 0; + let normalYComponent = 0; + + if ( iy <= capSegments ) { + + // bottom cap + const segmentProgress = iy / capSegments; + const angle = ( segmentProgress * Math.PI ) / 2; + profileY = - halfHeight - radius * Math.cos( angle ); + profileRadius = radius * Math.sin( angle ); + normalYComponent = - radius * Math.cos( angle ); + currentArcLength = segmentProgress * capArcLength; + + } else if ( iy <= capSegments + heightSegments ) { + + // middle section + const segmentProgress = ( iy - capSegments ) / heightSegments; + profileY = - halfHeight + segmentProgress * height; + profileRadius = radius; + normalYComponent = 0; + currentArcLength = capArcLength + segmentProgress * cylinderPartLength; + + } else { + + // top cap + const segmentProgress = + ( iy - capSegments - heightSegments ) / capSegments; + const angle = ( segmentProgress * Math.PI ) / 2; + profileY = halfHeight + radius * Math.sin( angle ); + profileRadius = radius * Math.cos( angle ); + normalYComponent = radius * Math.sin( angle ); + currentArcLength = + capArcLength + cylinderPartLength + segmentProgress * capArcLength; + + } + + const v = Math.max( 0, Math.min( 1, currentArcLength / totalArcLength ) ); + + + // special case for the poles + + let uOffset = 0; + + if ( iy === 0 ) { + + uOffset = 0.5 / radialSegments; + + } else if ( iy === numVerticalSegments ) { + + uOffset = -0.5 / radialSegments; + + } + + for ( let ix = 0; ix <= radialSegments; ix ++ ) { + + const u = ix / radialSegments; + const theta = u * Math.PI * 2; + + const sinTheta = Math.sin( theta ); + const cosTheta = Math.cos( theta ); + + // vertex + + vertex.x = - profileRadius * cosTheta; + vertex.y = profileY; + vertex.z = profileRadius * sinTheta; + vertices.push( vertex.x, vertex.y, vertex.z ); + + // normal + + normal.set( + - profileRadius * cosTheta, + normalYComponent, + profileRadius * sinTheta + ); + normal.normalize(); + normals.push( normal.x, normal.y, normal.z ); + + // uv + + uvs.push( u + uOffset, v ); + + } + + if ( iy > 0 ) { + + const prevIndexRow = ( iy - 1 ) * verticesPerRow; + for ( let ix = 0; ix < radialSegments; ix ++ ) { + + const i1 = prevIndexRow + ix; + const i2 = prevIndexRow + ix + 1; + const i3 = iy * verticesPerRow + ix; + const i4 = iy * verticesPerRow + ix + 1; + + indices.push( i1, i2, i3 ); + indices.push( i2, i4, i3 ); + + } + + } + + } + + // build geometry + + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + + } + + copy( source ) { + + super.copy( source ); + + this.parameters = Object.assign( {}, source.parameters ); + + return this; + + } + + /** + * Factory method for creating an instance of this class from the given + * JSON object. + * + * @param {Object} data - A JSON object representing the serialized geometry. + * @return {CapsuleGeometry} A new instance. + */ + static fromJSON( data ) { + + return new CapsuleGeometry( data.radius, data.height, data.capSegments, data.radialSegments, data.heightSegments ); + + } + +} + +/** + * A simple shape of Euclidean geometry. It is constructed from a + * number of triangular segments that are oriented around a central point and + * extend as far out as a given radius. It is built counter-clockwise from a + * start angle and a given central angle. It can also be used to create + * regular polygons, where the number of segments determines the number of + * sides. + * + * ```js + * const geometry = new THREE.CircleGeometry( 5, 32 ); + * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } ); + * const circle = new THREE.Mesh( geometry, material ); + * scene.add( circle ) + * ``` + * + * @augments BufferGeometry + * @demo scenes/geometry-browser.html#CircleGeometry + */ +class CircleGeometry extends BufferGeometry { + + /** + * Constructs a new circle geometry. + * + * @param {number} [radius=1] - Radius of the circle. + * @param {number} [segments=32] - Number of segments (triangles), minimum = `3`. + * @param {number} [thetaStart=0] - Start angle for first segment in radians. + * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta, + * of the circular sector in radians. The default value results in a complete circle. + */ + constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) { + + super(); + + this.type = 'CircleGeometry'; + + /** + * Holds the constructor parameters that have been + * used to generate the geometry. Any modification + * after instantiation does not change the geometry. + * + * @type {Object} + */ + this.parameters = { + radius: radius, + segments: segments, + thetaStart: thetaStart, + thetaLength: thetaLength + }; + + segments = Math.max( 3, segments ); + + // buffers + + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + + // helper variables + + const vertex = new Vector3(); + const uv = new Vector2(); + + // center point + + vertices.push( 0, 0, 0 ); + normals.push( 0, 0, 1 ); + uvs.push( 0.5, 0.5 ); + + for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) { + + const segment = thetaStart + s / segments * thetaLength; + + // vertex + + vertex.x = radius * Math.cos( segment ); + vertex.y = radius * Math.sin( segment ); + + vertices.push( vertex.x, vertex.y, vertex.z ); + + // normal + + normals.push( 0, 0, 1 ); + + // uvs + + uv.x = ( vertices[ i ] / radius + 1 ) / 2; + uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2; + + uvs.push( uv.x, uv.y ); + + } + + // indices + + for ( let i = 1; i <= segments; i ++ ) { + + indices.push( i, i + 1, 0 ); + + } + + // build geometry + + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + + } + + copy( source ) { + + super.copy( source ); + + this.parameters = Object.assign( {}, source.parameters ); + + return this; + + } + + /** + * Factory method for creating an instance of this class from the given + * JSON object. + * + * @param {Object} data - A JSON object representing the serialized geometry. + * @return {CircleGeometry} A new instance. + */ + static fromJSON( data ) { + + return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength ); + + } + +} + +/** + * A geometry class for representing a cylinder. + * + * ```js + * const geometry = new THREE.CylinderGeometry( 5, 5, 20, 32 ); + * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } ); + * const cylinder = new THREE.Mesh( geometry, material ); + * scene.add( cylinder ); + * ``` + * + * @augments BufferGeometry + * @demo scenes/geometry-browser.html#CylinderGeometry + */ +class CylinderGeometry extends BufferGeometry { + + /** + * Constructs a new cylinder geometry. + * + * @param {number} [radiusTop=1] - Radius of the cylinder at the top. + * @param {number} [radiusBottom=1] - Radius of the cylinder at the bottom. + * @param {number} [height=1] - Height of the cylinder. + * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cylinder. + * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cylinder. + * @param {boolean} [openEnded=false] - Whether the base of the cylinder is open or capped. + * @param {number} [thetaStart=0] - Start angle for first segment, in radians. + * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians. + * The default value results in a complete cylinder. + */ + constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) { + + super(); + + this.type = 'CylinderGeometry'; + + /** + * Holds the constructor parameters that have been + * used to generate the geometry. Any modification + * after instantiation does not change the geometry. + * + * @type {Object} + */ + this.parameters = { + radiusTop: radiusTop, + radiusBottom: radiusBottom, + height: height, + radialSegments: radialSegments, + heightSegments: heightSegments, + openEnded: openEnded, + thetaStart: thetaStart, + thetaLength: thetaLength + }; + + const scope = this; + + radialSegments = Math.floor( radialSegments ); + heightSegments = Math.floor( heightSegments ); + + // buffers + + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + + // helper variables + + let index = 0; + const indexArray = []; + const halfHeight = height / 2; + let groupStart = 0; + + // generate geometry + + generateTorso(); + + if ( openEnded === false ) { + + if ( radiusTop > 0 ) generateCap( true ); + if ( radiusBottom > 0 ) generateCap( false ); + + } + + // build geometry + + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + + function generateTorso() { + + const normal = new Vector3(); + const vertex = new Vector3(); + + let groupCount = 0; + + // this will be used to calculate the normal + const slope = ( radiusBottom - radiusTop ) / height; + + // generate vertices, normals and uvs + + for ( let y = 0; y <= heightSegments; y ++ ) { + + const indexRow = []; + + const v = y / heightSegments; + + // calculate the radius of the current row + + const radius = v * ( radiusBottom - radiusTop ) + radiusTop; + + for ( let x = 0; x <= radialSegments; x ++ ) { + + const u = x / radialSegments; + + const theta = u * thetaLength + thetaStart; + + const sinTheta = Math.sin( theta ); + const cosTheta = Math.cos( theta ); + + // vertex + + vertex.x = radius * sinTheta; + vertex.y = - v * height + halfHeight; + vertex.z = radius * cosTheta; + vertices.push( vertex.x, vertex.y, vertex.z ); + + // normal + + normal.set( sinTheta, slope, cosTheta ).normalize(); + normals.push( normal.x, normal.y, normal.z ); + + // uv + + uvs.push( u, 1 - v ); + + // save index of vertex in respective row + + indexRow.push( index ++ ); + + } + + // now save vertices of the row in our index array + + indexArray.push( indexRow ); + + } + + // generate indices + + for ( let x = 0; x < radialSegments; x ++ ) { + + for ( let y = 0; y < heightSegments; y ++ ) { + + // we use the index array to access the correct indices + + const a = indexArray[ y ][ x ]; + const b = indexArray[ y + 1 ][ x ]; + const c = indexArray[ y + 1 ][ x + 1 ]; + const d = indexArray[ y ][ x + 1 ]; + + // faces + + if ( radiusTop > 0 || y !== 0 ) { + + indices.push( a, b, d ); + groupCount += 3; + + } + + if ( radiusBottom > 0 || y !== heightSegments - 1 ) { + + indices.push( b, c, d ); + groupCount += 3; + + } + + } + + } + + // add a group to the geometry. this will ensure multi material support + + scope.addGroup( groupStart, groupCount, 0 ); + + // calculate new start value for groups + + groupStart += groupCount; + + } + + function generateCap( top ) { + + // save the index of the first center vertex + const centerIndexStart = index; + + const uv = new Vector2(); + const vertex = new Vector3(); + + let groupCount = 0; + + const radius = ( top === true ) ? radiusTop : radiusBottom; + const sign = ( top === true ) ? 1 : -1; + + // first we generate the center vertex data of the cap. + // because the geometry needs one set of uvs per face, + // we must generate a center vertex per face/segment + + for ( let x = 1; x <= radialSegments; x ++ ) { + + // vertex + + vertices.push( 0, halfHeight * sign, 0 ); + + // normal + + normals.push( 0, sign, 0 ); + + // uv + + uvs.push( 0.5, 0.5 ); + + // increase index + + index ++; + + } + + // save the index of the last center vertex + const centerIndexEnd = index; + + // now we generate the surrounding vertices, normals and uvs + + for ( let x = 0; x <= radialSegments; x ++ ) { + + const u = x / radialSegments; + const theta = u * thetaLength + thetaStart; + + const cosTheta = Math.cos( theta ); + const sinTheta = Math.sin( theta ); + + // vertex + + vertex.x = radius * sinTheta; + vertex.y = halfHeight * sign; + vertex.z = radius * cosTheta; + vertices.push( vertex.x, vertex.y, vertex.z ); + + // normal + + normals.push( 0, sign, 0 ); + + // uv + + uv.x = ( cosTheta * 0.5 ) + 0.5; + uv.y = ( sinTheta * 0.5 * sign ) + 0.5; + uvs.push( uv.x, uv.y ); + + // increase index + + index ++; + + } + + // generate indices + + for ( let x = 0; x < radialSegments; x ++ ) { + + const c = centerIndexStart + x; + const i = centerIndexEnd + x; + + if ( top === true ) { + + // face top + + indices.push( i, i + 1, c ); + + } else { + + // face bottom + + indices.push( i + 1, i, c ); + + } + + groupCount += 3; + + } + + // add a group to the geometry. this will ensure multi material support + + scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 ); + + // calculate new start value for groups + + groupStart += groupCount; + + } + + } + + copy( source ) { + + super.copy( source ); + + this.parameters = Object.assign( {}, source.parameters ); + + return this; + + } + + /** + * Factory method for creating an instance of this class from the given + * JSON object. + * + * @param {Object} data - A JSON object representing the serialized geometry. + * @return {CylinderGeometry} A new instance. + */ + static fromJSON( data ) { + + return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength ); + + } + +} + +/** + * A geometry class for representing a cone. + * + * ```js + * const geometry = new THREE.ConeGeometry( 5, 20, 32 ); + * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } ); + * const cone = new THREE.Mesh(geometry, material ); + * scene.add( cone ); + * ``` + * + * @augments CylinderGeometry + * @demo scenes/geometry-browser.html#ConeGeometry + */ +class ConeGeometry extends CylinderGeometry { + + /** + * Constructs a new cone geometry. + * + * @param {number} [radius=1] - Radius of the cone base. + * @param {number} [height=1] - Height of the cone. + * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cone. + * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cone. + * @param {boolean} [openEnded=false] - Whether the base of the cone is open or capped. + * @param {number} [thetaStart=0] - Start angle for first segment, in radians. + * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians. + * The default value results in a complete cone. + */ + constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) { + + super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ); + + this.type = 'ConeGeometry'; + + /** + * Holds the constructor parameters that have been + * used to generate the geometry. Any modification + * after instantiation does not change the geometry. + * + * @type {Object} + */ + this.parameters = { + radius: radius, + height: height, + radialSegments: radialSegments, + heightSegments: heightSegments, + openEnded: openEnded, + thetaStart: thetaStart, + thetaLength: thetaLength + }; + + } + + /** + * Factory method for creating an instance of this class from the given + * JSON object. + * + * @param {Object} data - A JSON object representing the serialized geometry. + * @return {ConeGeometry} A new instance. + */ + static fromJSON( data ) { + + return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength ); + + } + +} + +/** + * A polyhedron is a solid in three dimensions with flat faces. This class + * will take an array of vertices, project them onto a sphere, and then + * divide them up to the desired level of detail. + * + * @augments BufferGeometry + */ +class PolyhedronGeometry extends BufferGeometry { + + /** + * Constructs a new polyhedron geometry. + * + * @param {Array} [vertices] - A flat array of vertices describing the base shape. + * @param {Array} [indices] - A flat array of indices describing the base shape. + * @param {number} [radius=1] - The radius of the shape. + * @param {number} [detail=0] - How many levels to subdivide the geometry. The more detail, the smoother the shape. + */ + constructor( vertices = [], indices = [], radius = 1, detail = 0 ) { + + super(); + + this.type = 'PolyhedronGeometry'; + + /** + * Holds the constructor parameters that have been + * used to generate the geometry. Any modification + * after instantiation does not change the geometry. + * + * @type {Object} + */ + this.parameters = { + vertices: vertices, + indices: indices, + radius: radius, + detail: detail + }; + + // default buffer data + + const vertexBuffer = []; + const uvBuffer = []; + + // the subdivision creates the vertex buffer data + + subdivide( detail ); + + // all vertices should lie on a conceptual sphere with a given radius + + applyRadius( radius ); + + // finally, create the uv data + + generateUVs(); + + // build non-indexed geometry + + this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) ); + + if ( detail === 0 ) { + + this.computeVertexNormals(); // flat normals + + } else { + + this.normalizeNormals(); // smooth normals + + } + + // helper functions + + function subdivide( detail ) { + + const a = new Vector3(); + const b = new Vector3(); + const c = new Vector3(); + + // iterate over all faces and apply a subdivision with the given detail value + + for ( let i = 0; i < indices.length; i += 3 ) { + + // get the vertices of the face + + getVertexByIndex( indices[ i + 0 ], a ); + getVertexByIndex( indices[ i + 1 ], b ); + getVertexByIndex( indices[ i + 2 ], c ); + + // perform subdivision + + subdivideFace( a, b, c, detail ); + + } + + } + + function subdivideFace( a, b, c, detail ) { + + const cols = detail + 1; + + // we use this multidimensional array as a data structure for creating the subdivision + + const v = []; + + // construct all of the vertices for this subdivision + + for ( let i = 0; i <= cols; i ++ ) { + + v[ i ] = []; + + const aj = a.clone().lerp( c, i / cols ); + const bj = b.clone().lerp( c, i / cols ); + + const rows = cols - i; + + for ( let j = 0; j <= rows; j ++ ) { + + if ( j === 0 && i === cols ) { + + v[ i ][ j ] = aj; + + } else { + + v[ i ][ j ] = aj.clone().lerp( bj, j / rows ); + + } + + } + + } + + // construct all of the faces + + for ( let i = 0; i < cols; i ++ ) { + + for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) { + + const k = Math.floor( j / 2 ); + + if ( j % 2 === 0 ) { + + pushVertex( v[ i ][ k + 1 ] ); + pushVertex( v[ i + 1 ][ k ] ); + pushVertex( v[ i ][ k ] ); + + } else { + + pushVertex( v[ i ][ k + 1 ] ); + pushVertex( v[ i + 1 ][ k + 1 ] ); + pushVertex( v[ i + 1 ][ k ] ); + + } + + } + + } + + } + + function applyRadius( radius ) { + + const vertex = new Vector3(); + + // iterate over the entire buffer and apply the radius to each vertex + + for ( let i = 0; i < vertexBuffer.length; i += 3 ) { + + vertex.x = vertexBuffer[ i + 0 ]; + vertex.y = vertexBuffer[ i + 1 ]; + vertex.z = vertexBuffer[ i + 2 ]; + + vertex.normalize().multiplyScalar( radius ); + + vertexBuffer[ i + 0 ] = vertex.x; + vertexBuffer[ i + 1 ] = vertex.y; + vertexBuffer[ i + 2 ] = vertex.z; + + } + + } + + function generateUVs() { + + const vertex = new Vector3(); + + for ( let i = 0; i < vertexBuffer.length; i += 3 ) { + + vertex.x = vertexBuffer[ i + 0 ]; + vertex.y = vertexBuffer[ i + 1 ]; + vertex.z = vertexBuffer[ i + 2 ]; + + const u = azimuth( vertex ) / 2 / Math.PI + 0.5; + const v = inclination( vertex ) / Math.PI + 0.5; + uvBuffer.push( u, 1 - v ); + + } + + correctUVs(); + + correctSeam(); + + } + + function correctSeam() { + + // handle case when face straddles the seam, see #3269 + + for ( let i = 0; i < uvBuffer.length; i += 6 ) { + + // uv data of a single face + + const x0 = uvBuffer[ i + 0 ]; + const x1 = uvBuffer[ i + 2 ]; + const x2 = uvBuffer[ i + 4 ]; + + const max = Math.max( x0, x1, x2 ); + const min = Math.min( x0, x1, x2 ); + + // 0.9 is somewhat arbitrary + + if ( max > 0.9 && min < 0.1 ) { + + if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1; + if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1; + if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1; + + } + + } + + } + + function pushVertex( vertex ) { + + vertexBuffer.push( vertex.x, vertex.y, vertex.z ); + + } + + function getVertexByIndex( index, vertex ) { + + const stride = index * 3; + + vertex.x = vertices[ stride + 0 ]; + vertex.y = vertices[ stride + 1 ]; + vertex.z = vertices[ stride + 2 ]; + + } + + function correctUVs() { + + const a = new Vector3(); + const b = new Vector3(); + const c = new Vector3(); + + const centroid = new Vector3(); + + const uvA = new Vector2(); + const uvB = new Vector2(); + const uvC = new Vector2(); + + for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) { + + a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] ); + b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] ); + c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] ); + + uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] ); + uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] ); + uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] ); + + centroid.copy( a ).add( b ).add( c ).divideScalar( 3 ); + + const azi = azimuth( centroid ); + + correctUV( uvA, j + 0, a, azi ); + correctUV( uvB, j + 2, b, azi ); + correctUV( uvC, j + 4, c, azi ); + + } + + } + + function correctUV( uv, stride, vector, azimuth ) { + + if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) { + + uvBuffer[ stride ] = uv.x - 1; + + } + + if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) { + + uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5; + + } + + } + + // Angle around the Y axis, counter-clockwise when looking from above. + + function azimuth( vector ) { + + return Math.atan2( vector.z, - vector.x ); + + } + + + // Angle above the XZ plane. + + function inclination( vector ) { + + return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) ); + + } + + } + + copy( source ) { + + super.copy( source ); + + this.parameters = Object.assign( {}, source.parameters ); + + return this; + + } + + /** + * Factory method for creating an instance of this class from the given + * JSON object. + * + * @param {Object} data - A JSON object representing the serialized geometry. + * @return {PolyhedronGeometry} A new instance. + */ + static fromJSON( data ) { + + return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.detail ); + + } + +} + +/** + * A geometry class for representing a dodecahedron. + * + * ```js + * const geometry = new THREE.DodecahedronGeometry(); + * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } ); + * const dodecahedron = new THREE.Mesh( geometry, material ); + * scene.add( dodecahedron ); + * ``` + * + * @augments PolyhedronGeometry + * @demo scenes/geometry-browser.html#DodecahedronGeometry + */ +class DodecahedronGeometry extends PolyhedronGeometry { + + /** + * Constructs a new dodecahedron geometry. + * + * @param {number} [radius=1] - Radius of the dodecahedron. + * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a dodecahedron. + */ + constructor( radius = 1, detail = 0 ) { + + const t = ( 1 + Math.sqrt( 5 ) ) / 2; + const r = 1 / t; + + const vertices = [ + + // (±1, ±1, ±1) + -1, -1, -1, -1, -1, 1, + -1, 1, -1, -1, 1, 1, + 1, -1, -1, 1, -1, 1, + 1, 1, -1, 1, 1, 1, + + // (0, ±1/φ, ±φ) + 0, - r, - t, 0, - r, t, + 0, r, - t, 0, r, t, + + // (±1/φ, ±φ, 0) + - r, - t, 0, - r, t, 0, + r, - t, 0, r, t, 0, + + // (±φ, 0, ±1/φ) + - t, 0, - r, t, 0, - r, + - t, 0, r, t, 0, r + ]; + + const indices = [ + 3, 11, 7, 3, 7, 15, 3, 15, 13, + 7, 19, 17, 7, 17, 6, 7, 6, 15, + 17, 4, 8, 17, 8, 10, 17, 10, 6, + 8, 0, 16, 8, 16, 2, 8, 2, 10, + 0, 12, 1, 0, 1, 18, 0, 18, 16, + 6, 10, 2, 6, 2, 13, 6, 13, 15, + 2, 16, 18, 2, 18, 3, 2, 3, 13, + 18, 1, 9, 18, 9, 11, 18, 11, 3, + 4, 14, 12, 4, 12, 0, 4, 0, 8, + 11, 9, 5, 11, 5, 19, 11, 19, 7, + 19, 5, 14, 19, 14, 4, 19, 4, 17, + 1, 12, 14, 1, 14, 5, 1, 5, 9 + ]; + + super( vertices, indices, radius, detail ); + + this.type = 'DodecahedronGeometry'; + + /** + * Holds the constructor parameters that have been + * used to generate the geometry. Any modification + * after instantiation does not change the geometry. + * + * @type {Object} + */ + this.parameters = { + radius: radius, + detail: detail + }; + + } + + /** + * Factory method for creating an instance of this class from the given + * JSON object. + * + * @param {Object} data - A JSON object representing the serialized geometry. + * @return {DodecahedronGeometry} A new instance. + */ + static fromJSON( data ) { + + return new DodecahedronGeometry( data.radius, data.detail ); + + } + +} + +const _v0 = /*@__PURE__*/ new Vector3(); +const _v1$1 = /*@__PURE__*/ new Vector3(); +const _normal = /*@__PURE__*/ new Vector3(); +const _triangle = /*@__PURE__*/ new Triangle(); + +/** + * Can be used as a helper object to view the edges of a geometry. + * + * ```js + * const geometry = new THREE.BoxGeometry(); + * const edges = new THREE.EdgesGeometry( geometry ); + * const line = new THREE.LineSegments( edges ); + * scene.add( line ); + * ``` + * + * Note: It is not yet possible to serialize/deserialize instances of this class. + * + * @augments BufferGeometry + */ +class EdgesGeometry extends BufferGeometry { + + /** + * Constructs a new edges geometry. + * + * @param {?BufferGeometry} [geometry=null] - The geometry. + * @param {number} [thresholdAngle=1] - An edge is only rendered if the angle (in degrees) + * between the face normals of the adjoining faces exceeds this value. + */ + constructor( geometry = null, thresholdAngle = 1 ) { + + super(); + + this.type = 'EdgesGeometry'; + + /** + * Holds the constructor parameters that have been + * used to generate the geometry. Any modification + * after instantiation does not change the geometry. + * + * @type {Object} + */ + this.parameters = { + geometry: geometry, + thresholdAngle: thresholdAngle + }; + + if ( geometry !== null ) { + + const precisionPoints = 4; + const precision = Math.pow( 10, precisionPoints ); + const thresholdDot = Math.cos( DEG2RAD * thresholdAngle ); + + const indexAttr = geometry.getIndex(); + const positionAttr = geometry.getAttribute( 'position' ); + const indexCount = indexAttr ? indexAttr.count : positionAttr.count; + + const indexArr = [ 0, 0, 0 ]; + const vertKeys = [ 'a', 'b', 'c' ]; + const hashes = new Array( 3 ); + + const edgeData = {}; + const vertices = []; + for ( let i = 0; i < indexCount; i += 3 ) { + + if ( indexAttr ) { + + indexArr[ 0 ] = indexAttr.getX( i ); + indexArr[ 1 ] = indexAttr.getX( i + 1 ); + indexArr[ 2 ] = indexAttr.getX( i + 2 ); + + } else { + + indexArr[ 0 ] = i; + indexArr[ 1 ] = i + 1; + indexArr[ 2 ] = i + 2; + + } + + const { a, b, c } = _triangle; + a.fromBufferAttribute( positionAttr, indexArr[ 0 ] ); + b.fromBufferAttribute( positionAttr, indexArr[ 1 ] ); + c.fromBufferAttribute( positionAttr, indexArr[ 2 ] ); + _triangle.getNormal( _normal ); + + // create hashes for the edge from the vertices + hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`; + hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`; + hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`; + + // skip degenerate triangles + if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) { + + continue; + + } + + // iterate over every edge + for ( let j = 0; j < 3; j ++ ) { + + // get the first and next vertex making up the edge + const jNext = ( j + 1 ) % 3; + const vecHash0 = hashes[ j ]; + const vecHash1 = hashes[ jNext ]; + const v0 = _triangle[ vertKeys[ j ] ]; + const v1 = _triangle[ vertKeys[ jNext ] ]; + + const hash = `${ vecHash0 }_${ vecHash1 }`; + const reverseHash = `${ vecHash1 }_${ vecHash0 }`; + + if ( reverseHash in edgeData && edgeData[ reverseHash ] ) { + + // if we found a sibling edge add it into the vertex array if + // it meets the angle threshold and delete the edge from the map. + if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) { + + vertices.push( v0.x, v0.y, v0.z ); + vertices.push( v1.x, v1.y, v1.z ); + + } + + edgeData[ reverseHash ] = null; + + } else if ( ! ( hash in edgeData ) ) { + + // if we've already got an edge here then skip adding a new one + edgeData[ hash ] = { + + index0: indexArr[ j ], + index1: indexArr[ jNext ], + normal: _normal.clone(), + + }; + + } + + } + + } + + // iterate over all remaining, unmatched edges and add them to the vertex array + for ( const key in edgeData ) { + + if ( edgeData[ key ] ) { + + const { index0, index1 } = edgeData[ key ]; + _v0.fromBufferAttribute( positionAttr, index0 ); + _v1$1.fromBufferAttribute( positionAttr, index1 ); + + vertices.push( _v0.x, _v0.y, _v0.z ); + vertices.push( _v1$1.x, _v1$1.y, _v1$1.z ); + + } + + } + + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + + } + + } + + copy( source ) { + + super.copy( source ); + + this.parameters = Object.assign( {}, source.parameters ); + + return this; + + } + +} + +/** + * An abstract base class for creating an analytic curve object that contains methods + * for interpolation. + * + * @abstract + */ +class Curve { + + /** + * Constructs a new curve. + */ + constructor() { + + /** + * The type property is used for detecting the object type + * in context of serialization/deserialization. + * + * @type {string} + * @readonly + */ + this.type = 'Curve'; + + /** + * This value determines the amount of divisions when calculating the + * cumulative segment lengths of a curve via {@link Curve#getLengths}. To ensure + * precision when using methods like {@link Curve#getSpacedPoints}, it is + * recommended to increase the value of this property if the curve is very large. + * + * @type {number} + * @default 200 + */ + this.arcLengthDivisions = 200; + + /** + * Must be set to `true` if the curve parameters have changed. + * + * @type {boolean} + * @default false + */ + this.needsUpdate = false; + + /** + * An internal cache that holds precomputed curve length values. + * + * @private + * @type {?Array} + * @default null + */ + this.cacheArcLengths = null; + + } + + /** + * This method returns a vector in 2D or 3D space (depending on the curve definition) + * for the given interpolation factor. + * + * @abstract + * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`. + * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to. + * @return {(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition. + */ + getPoint( /* t, optionalTarget */ ) { + + warn( 'Curve: .getPoint() not implemented.' ); + + } + + /** + * This method returns a vector in 2D or 3D space (depending on the curve definition) + * for the given interpolation factor. Unlike {@link Curve#getPoint}, this method honors the length + * of the curve which equidistant samples. + * + * @param {number} u - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`. + * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to. + * @return {(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition. + */ + getPointAt( u, optionalTarget ) { + + const t = this.getUtoTmapping( u ); + return this.getPoint( t, optionalTarget ); + + } + + /** + * This method samples the curve via {@link Curve#getPoint} and returns an array of points representing + * the curve shape. + * + * @param {number} [divisions=5] - The number of divisions. + * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`. + */ + getPoints( divisions = 5 ) { + + const points = []; + + for ( let d = 0; d <= divisions; d ++ ) { + + points.push( this.getPoint( d / divisions ) ); + + } + + return points; + + } + + // Get sequence of points using getPointAt( u ) + + /** + * This method samples the curve via {@link Curve#getPointAt} and returns an array of points representing + * the curve shape. Unlike {@link Curve#getPoints}, this method returns equi-spaced points across the entire + * curve. + * + * @param {number} [divisions=5] - The number of divisions. + * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`. + */ + getSpacedPoints( divisions = 5 ) { + + const points = []; + + for ( let d = 0; d <= divisions; d ++ ) { + + points.push( this.getPointAt( d / divisions ) ); + + } + + return points; + + } + + /** + * Returns the total arc length of the curve. + * + * @return {number} The length of the curve. + */ + getLength() { + + const lengths = this.getLengths(); + return lengths[ lengths.length - 1 ]; + + } + + /** + * Returns an array of cumulative segment lengths of the curve. + * + * @param {number} [divisions=this.arcLengthDivisions] - The number of divisions. + * @return {Array} An array holding the cumulative segment lengths. + */ + getLengths( divisions = this.arcLengthDivisions ) { + + if ( this.cacheArcLengths && + ( this.cacheArcLengths.length === divisions + 1 ) && + ! this.needsUpdate ) { + + return this.cacheArcLengths; + + } + + this.needsUpdate = false; + + const cache = []; + let current, last = this.getPoint( 0 ); + let sum = 0; + + cache.push( 0 ); + + for ( let p = 1; p <= divisions; p ++ ) { + + current = this.getPoint( p / divisions ); + sum += current.distanceTo( last ); + cache.push( sum ); + last = current; + + } + + this.cacheArcLengths = cache; + + return cache; // { sums: cache, sum: sum }; Sum is in the last element. + + } + + /** + * Update the cumulative segment distance cache. The method must be called + * every time curve parameters are changed. If an updated curve is part of a + * composed curve like {@link CurvePath}, this method must be called on the + * composed curve, too. + */ + updateArcLengths() { + + this.needsUpdate = true; + this.getLengths(); + + } + + /** + * Given an interpolation factor in the range `[0,1]`, this method returns an updated + * interpolation factor in the same range that can be ued to sample equidistant points + * from a curve. + * + * @param {number} u - The interpolation factor. + * @param {?number} distance - An optional distance on the curve. + * @return {number} The updated interpolation factor. + */ + getUtoTmapping( u, distance = null ) { + + const arcLengths = this.getLengths(); + + let i = 0; + const il = arcLengths.length; + + let targetArcLength; // The targeted u distance value to get + + if ( distance ) { + + targetArcLength = distance; + + } else { + + targetArcLength = u * arcLengths[ il - 1 ]; + + } + + // binary search for the index with largest value smaller than target u distance + + let low = 0, high = il - 1, comparison; + + while ( low <= high ) { + + i = Math.floor( low + ( high - low ) / 2 ); // less likely to overflow, though probably not issue here, JS doesn't really have integers, all numbers are floats + + comparison = arcLengths[ i ] - targetArcLength; + + if ( comparison < 0 ) { + + low = i + 1; + + } else if ( comparison > 0 ) { + + high = i - 1; + + } else { + + high = i; + break; + + // DONE + + } + + } + + i = high; + + if ( arcLengths[ i ] === targetArcLength ) { + + return i / ( il - 1 ); + + } + + // we could get finer grain at lengths, or use simple interpolation between two points + + const lengthBefore = arcLengths[ i ]; + const lengthAfter = arcLengths[ i + 1 ]; + + const segmentLength = lengthAfter - lengthBefore; + + // determine where we are between the 'before' and 'after' points + + const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength; + + // add that fractional amount to t + + const t = ( i + segmentFraction ) / ( il - 1 ); + + return t; + + } + + /** + * Returns a unit vector tangent for the given interpolation factor. + * If the derived curve does not implement its tangent derivation, + * two points a small delta apart will be used to find its gradient + * which seems to give a reasonable approximation. + * + * @param {number} t - The interpolation factor. + * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to. + * @return {(Vector2|Vector3)} The tangent vector. + */ + getTangent( t, optionalTarget ) { + + const delta = 0.0001; + let t1 = t - delta; + let t2 = t + delta; + + // Capping in case of danger + + if ( t1 < 0 ) t1 = 0; + if ( t2 > 1 ) t2 = 1; + + const pt1 = this.getPoint( t1 ); + const pt2 = this.getPoint( t2 ); + + const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() ); + + tangent.copy( pt2 ).sub( pt1 ).normalize(); + + return tangent; + + } + + /** + * Same as {@link Curve#getTangent} but with equidistant samples. + * + * @param {number} u - The interpolation factor. + * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to. + * @return {(Vector2|Vector3)} The tangent vector. + * @see {@link Curve#getPointAt} + */ + getTangentAt( u, optionalTarget ) { + + const t = this.getUtoTmapping( u ); + return this.getTangent( t, optionalTarget ); + + } + + /** + * Generates the Frenet Frames. Requires a curve definition in 3D space. Used + * in geometries like {@link TubeGeometry} or {@link ExtrudeGeometry}. + * + * @param {number} segments - The number of segments. + * @param {boolean} [closed=false] - Whether the curve is closed or not. + * @return {{tangents: Array, normals: Array, binormals: Array}} The Frenet Frames. + */ + computeFrenetFrames( segments, closed = false ) { + + // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf + + const normal = new Vector3(); + + const tangents = []; + const normals = []; + const binormals = []; + + const vec = new Vector3(); + const mat = new Matrix4(); + + // compute the tangent vectors for each segment on the curve + + for ( let i = 0; i <= segments; i ++ ) { + + const u = i / segments; + + tangents[ i ] = this.getTangentAt( u, new Vector3() ); + + } + + // select an initial normal vector perpendicular to the first tangent vector, + // and in the direction of the minimum tangent xyz component + + normals[ 0 ] = new Vector3(); + binormals[ 0 ] = new Vector3(); + let min = Number.MAX_VALUE; + const tx = Math.abs( tangents[ 0 ].x ); + const ty = Math.abs( tangents[ 0 ].y ); + const tz = Math.abs( tangents[ 0 ].z ); + + if ( tx <= min ) { + + min = tx; + normal.set( 1, 0, 0 ); + + } + + if ( ty <= min ) { + + min = ty; + normal.set( 0, 1, 0 ); + + } + + if ( tz <= min ) { + + normal.set( 0, 0, 1 ); + + } + + vec.crossVectors( tangents[ 0 ], normal ).normalize(); + + normals[ 0 ].crossVectors( tangents[ 0 ], vec ); + binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ); + + + // compute the slowly-varying normal and binormal vectors for each segment on the curve + + for ( let i = 1; i <= segments; i ++ ) { + + normals[ i ] = normals[ i - 1 ].clone(); + + binormals[ i ] = binormals[ i - 1 ].clone(); + + vec.crossVectors( tangents[ i - 1 ], tangents[ i ] ); + + if ( vec.length() > Number.EPSILON ) { + + vec.normalize(); + + const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), -1, 1 ) ); // clamp for floating pt errors + + normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) ); + + } + + binormals[ i ].crossVectors( tangents[ i ], normals[ i ] ); + + } + + // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same + + if ( closed === true ) { + + let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), -1, 1 ) ); + theta /= segments; + + if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) { + + theta = - theta; + + } + + for ( let i = 1; i <= segments; i ++ ) { + + // twist a little... + normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) ); + binormals[ i ].crossVectors( tangents[ i ], normals[ i ] ); + + } + + } + + return { + tangents: tangents, + normals: normals, + binormals: binormals + }; + + } + + /** + * Returns a new curve with copied values from this instance. + * + * @return {Curve} A clone of this instance. + */ + clone() { + + return new this.constructor().copy( this ); + + } + + /** + * Copies the values of the given curve to this instance. + * + * @param {Curve} source - The curve to copy. + * @return {Curve} A reference to this curve. + */ + copy( source ) { + + this.arcLengthDivisions = source.arcLengthDivisions; + + return this; + + } + + /** + * Serializes the curve into JSON. + * + * @return {Object} A JSON object representing the serialized curve. + * @see {@link ObjectLoader#parse} + */ + toJSON() { + + const data = { + metadata: { + version: 4.7, + type: 'Curve', + generator: 'Curve.toJSON' + } + }; + + data.arcLengthDivisions = this.arcLengthDivisions; + data.type = this.type; + + return data; + + } + + /** + * Deserializes the curve from the given JSON. + * + * @param {Object} json - The JSON holding the serialized curve. + * @return {Curve} A reference to this curve. + */ + fromJSON( json ) { + + this.arcLengthDivisions = json.arcLengthDivisions; + + return this; + + } + +} + +/** + * A curve representing an ellipse. + * + * ```js + * const curve = new THREE.EllipseCurve( + * 0, 0, + * 10, 10, + * 0, 2 * Math.PI, + * false, + * 0 + * ); + * + * const points = curve.getPoints( 50 ); + * const geometry = new THREE.BufferGeometry().setFromPoints( points ); + * + * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } ); + * + * // Create the final object to add to the scene + * const ellipse = new THREE.Line( geometry, material ); + * ``` + * + * @augments Curve + */ +class EllipseCurve extends Curve { + + /** + * Constructs a new ellipse curve. + * + * @param {number} [aX=0] - The X center of the ellipse. + * @param {number} [aY=0] - The Y center of the ellipse. + * @param {number} [xRadius=1] - The radius of the ellipse in the x direction. + * @param {number} [yRadius=1] - The radius of the ellipse in the y direction. + * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis. + * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis. + * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not. + * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis. + */ + constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) { + + super(); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isEllipseCurve = true; + + this.type = 'EllipseCurve'; + + /** + * The X center of the ellipse. + * + * @type {number} + * @default 0 + */ + this.aX = aX; + + /** + * The Y center of the ellipse. + * + * @type {number} + * @default 0 + */ + this.aY = aY; + + /** + * The radius of the ellipse in the x direction. + * Setting the this value equal to the {@link EllipseCurve#yRadius} will result in a circle. + * + * @type {number} + * @default 1 + */ + this.xRadius = xRadius; + + /** + * The radius of the ellipse in the y direction. + * Setting the this value equal to the {@link EllipseCurve#xRadius} will result in a circle. + * + * @type {number} + * @default 1 + */ + this.yRadius = yRadius; + + /** + * The start angle of the curve in radians starting from the positive X axis. + * + * @type {number} + * @default 0 + */ + this.aStartAngle = aStartAngle; + + /** + * The end angle of the curve in radians starting from the positive X axis. + * + * @type {number} + * @default Math.PI*2 + */ + this.aEndAngle = aEndAngle; + + /** + * Whether the ellipse is drawn clockwise or not. + * + * @type {boolean} + * @default false + */ + this.aClockwise = aClockwise; + + /** + * The rotation angle of the ellipse in radians, counterclockwise from the positive X axis. + * + * @type {number} + * @default 0 + */ + this.aRotation = aRotation; + + } + + /** + * Returns a point on the curve. + * + * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`. + * @param {Vector2} [optionalTarget] - The optional target vector the result is written to. + * @return {Vector2} The position on the curve. + */ + getPoint( t, optionalTarget = new Vector2() ) { + + const point = optionalTarget; + + const twoPi = Math.PI * 2; + let deltaAngle = this.aEndAngle - this.aStartAngle; + const samePoints = Math.abs( deltaAngle ) < Number.EPSILON; + + // ensures that deltaAngle is 0 .. 2 PI + while ( deltaAngle < 0 ) deltaAngle += twoPi; + while ( deltaAngle > twoPi ) deltaAngle -= twoPi; + + if ( deltaAngle < Number.EPSILON ) { + + if ( samePoints ) { + + deltaAngle = 0; + + } else { + + deltaAngle = twoPi; + + } + + } + + if ( this.aClockwise === true && ! samePoints ) { + + if ( deltaAngle === twoPi ) { + + deltaAngle = - twoPi; + + } else { + + deltaAngle = deltaAngle - twoPi; + + } + + } + + const angle = this.aStartAngle + t * deltaAngle; + let x = this.aX + this.xRadius * Math.cos( angle ); + let y = this.aY + this.yRadius * Math.sin( angle ); + + if ( this.aRotation !== 0 ) { + + const cos = Math.cos( this.aRotation ); + const sin = Math.sin( this.aRotation ); + + const tx = x - this.aX; + const ty = y - this.aY; + + // Rotate the point about the center of the ellipse. + x = tx * cos - ty * sin + this.aX; + y = tx * sin + ty * cos + this.aY; + + } + + return point.set( x, y ); + + } + + copy( source ) { + + super.copy( source ); + + this.aX = source.aX; + this.aY = source.aY; + + this.xRadius = source.xRadius; + this.yRadius = source.yRadius; + + this.aStartAngle = source.aStartAngle; + this.aEndAngle = source.aEndAngle; + + this.aClockwise = source.aClockwise; + + this.aRotation = source.aRotation; + + return this; + + } + + toJSON() { + + const data = super.toJSON(); + + data.aX = this.aX; + data.aY = this.aY; + + data.xRadius = this.xRadius; + data.yRadius = this.yRadius; + + data.aStartAngle = this.aStartAngle; + data.aEndAngle = this.aEndAngle; + + data.aClockwise = this.aClockwise; + + data.aRotation = this.aRotation; + + return data; + + } + + fromJSON( json ) { + + super.fromJSON( json ); + + this.aX = json.aX; + this.aY = json.aY; + + this.xRadius = json.xRadius; + this.yRadius = json.yRadius; + + this.aStartAngle = json.aStartAngle; + this.aEndAngle = json.aEndAngle; + + this.aClockwise = json.aClockwise; + + this.aRotation = json.aRotation; + + return this; + + } + +} + +/** + * A curve representing an arc. + * + * @augments EllipseCurve + */ +class ArcCurve extends EllipseCurve { + + /** + * Constructs a new arc curve. + * + * @param {number} [aX=0] - The X center of the ellipse. + * @param {number} [aY=0] - The Y center of the ellipse. + * @param {number} [aRadius=1] - The radius of the ellipse in the x direction. + * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis. + * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis. + * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not. + */ + constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { + + super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise ); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isArcCurve = true; + + this.type = 'ArcCurve'; + + } + +} + +function CubicPoly() { + + /** + * Centripetal CatmullRom Curve - which is useful for avoiding + * cusps and self-intersections in non-uniform catmull rom curves. + * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf + * + * curve.type accepts centripetal(default), chordal and catmullrom + * curve.tension is used for catmullrom which defaults to 0.5 + */ + + /* + Based on an optimized c++ solution in + - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/ + - http://ideone.com/NoEbVM + + This CubicPoly class could be used for reusing some variables and calculations, + but for three.js curve use, it could be possible inlined and flatten into a single function call + which can be placed in CurveUtils. + */ + + let c0 = 0, c1 = 0, c2 = 0, c3 = 0; + + /* + * Compute coefficients for a cubic polynomial + * p(s) = c0 + c1*s + c2*s^2 + c3*s^3 + * such that + * p(0) = x0, p(1) = x1 + * and + * p'(0) = t0, p'(1) = t1. + */ + function init( x0, x1, t0, t1 ) { + + c0 = x0; + c1 = t0; + c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1; + c3 = 2 * x0 - 2 * x1 + t0 + t1; + + } + + return { + + initCatmullRom: function ( x0, x1, x2, x3, tension ) { + + init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) ); + + }, + + initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) { + + // compute tangents when parameterized in [t1,t2] + let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1; + let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2; + + // rescale tangents for parametrization in [0,1] + t1 *= dt1; + t2 *= dt1; + + init( x1, x2, t1, t2 ); + + }, + + calc: function ( t ) { + + const t2 = t * t; + const t3 = t2 * t; + return c0 + c1 * t + c2 * t2 + c3 * t3; + + } + + }; + +} + +// + +const tmp = /*@__PURE__*/ new Vector3(); +const tmp2 = /*@__PURE__*/ new Vector3(); +const px = /*@__PURE__*/ new CubicPoly(); +const py = /*@__PURE__*/ new CubicPoly(); +const pz = /*@__PURE__*/ new CubicPoly(); + +/** + * A curve representing a Catmull-Rom spline. + * + * ```js + * //Create a closed wavey loop + * const curve = new THREE.CatmullRomCurve3( [ + * new THREE.Vector3( -10, 0, 10 ), + * new THREE.Vector3( -5, 5, 5 ), + * new THREE.Vector3( 0, 0, 0 ), + * new THREE.Vector3( 5, -5, 5 ), + * new THREE.Vector3( 10, 0, 10 ) + * ] ); + * + * const points = curve.getPoints( 50 ); + * const geometry = new THREE.BufferGeometry().setFromPoints( points ); + * + * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } ); + * + * // Create the final object to add to the scene + * const curveObject = new THREE.Line( geometry, material ); + * ``` + * + * @augments Curve + */ +class CatmullRomCurve3 extends Curve { + + /** + * Constructs a new Catmull-Rom curve. + * + * @param {Array} [points] - An array of 3D points defining the curve. + * @param {boolean} [closed=false] - Whether the curve is closed or not. + * @param {('centripetal'|'chordal'|'catmullrom')} [curveType='centripetal'] - The curve type. + * @param {number} [tension=0.5] - Tension of the curve. + */ + constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) { + + super(); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isCatmullRomCurve3 = true; + + this.type = 'CatmullRomCurve3'; + + /** + * An array of 3D points defining the curve. + * + * @type {Array} + */ + this.points = points; + + /** + * Whether the curve is closed or not. + * + * @type {boolean} + * @default false + */ + this.closed = closed; + + /** + * The curve type. + * + * @type {('centripetal'|'chordal'|'catmullrom')} + * @default 'centripetal' + */ + this.curveType = curveType; + + /** + * Tension of the curve. + * + * @type {number} + * @default 0.5 + */ + this.tension = tension; + + } + + /** + * Returns a point on the curve. + * + * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`. + * @param {Vector3} [optionalTarget] - The optional target vector the result is written to. + * @return {Vector3} The position on the curve. + */ + getPoint( t, optionalTarget = new Vector3() ) { + + const point = optionalTarget; + + const points = this.points; + const l = points.length; + + const p = ( l - ( this.closed ? 0 : 1 ) ) * t; + let intPoint = Math.floor( p ); + let weight = p - intPoint; + + if ( this.closed ) { + + intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l; + + } else if ( weight === 0 && intPoint === l - 1 ) { + + intPoint = l - 2; + weight = 1; + + } + + let p0, p3; // 4 points (p1 & p2 defined below) + + if ( this.closed || intPoint > 0 ) { + + p0 = points[ ( intPoint - 1 ) % l ]; + + } else { + + // extrapolate first point + tmp2.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] ); + p0 = tmp2; + + } + + const p1 = points[ intPoint % l ]; + const p2 = points[ ( intPoint + 1 ) % l ]; + + if ( this.closed || intPoint + 2 < l ) { + + p3 = points[ ( intPoint + 2 ) % l ]; + + } else { + + // extrapolate last point + tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] ); + p3 = tmp; + + } + + if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) { + + // init Centripetal / Chordal Catmull-Rom + const pow = this.curveType === 'chordal' ? 0.5 : 0.25; + let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow ); + let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow ); + let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow ); + + // safety check for repeated points + if ( dt1 < 1e-4 ) dt1 = 1.0; + if ( dt0 < 1e-4 ) dt0 = dt1; + if ( dt2 < 1e-4 ) dt2 = dt1; + + px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 ); + py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 ); + pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 ); + + } else if ( this.curveType === 'catmullrom' ) { + + px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension ); + py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension ); + pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension ); + + } + + point.set( + px.calc( weight ), + py.calc( weight ), + pz.calc( weight ) + ); + + return point; + + } + + copy( source ) { + + super.copy( source ); + + this.points = []; + + for ( let i = 0, l = source.points.length; i < l; i ++ ) { + + const point = source.points[ i ]; + + this.points.push( point.clone() ); + + } + + this.closed = source.closed; + this.curveType = source.curveType; + this.tension = source.tension; + + return this; + + } + + toJSON() { + + const data = super.toJSON(); + + data.points = []; + + for ( let i = 0, l = this.points.length; i < l; i ++ ) { + + const point = this.points[ i ]; + data.points.push( point.toArray() ); + + } + + data.closed = this.closed; + data.curveType = this.curveType; + data.tension = this.tension; + + return data; + + } + + fromJSON( json ) { + + super.fromJSON( json ); + + this.points = []; + + for ( let i = 0, l = json.points.length; i < l; i ++ ) { + + const point = json.points[ i ]; + this.points.push( new Vector3().fromArray( point ) ); + + } + + this.closed = json.closed; + this.curveType = json.curveType; + this.tension = json.tension; + + return this; + + } + +} + +/** + * Interpolations contains spline and Bézier functions internally used by concrete curve classes. + * + * Bezier Curves formulas obtained from: https://en.wikipedia.org/wiki/B%C3%A9zier_curve + * + * @module Interpolations + */ + +/** + * Computes a point on a Catmull-Rom spline. + * + * @param {number} t - The interpolation factor. + * @param {number} p0 - The first control point. + * @param {number} p1 - The second control point. + * @param {number} p2 - The third control point. + * @param {number} p3 - The fourth control point. + * @return {number} The calculated point on a Catmull-Rom spline. + */ +function CatmullRom( t, p0, p1, p2, p3 ) { + + const v0 = ( p2 - p0 ) * 0.5; + const v1 = ( p3 - p1 ) * 0.5; + const t2 = t * t; + const t3 = t * t2; + return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( -3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1; + +} + +// + +function QuadraticBezierP0( t, p ) { + + const k = 1 - t; + return k * k * p; + +} + +function QuadraticBezierP1( t, p ) { + + return 2 * ( 1 - t ) * t * p; + +} + +function QuadraticBezierP2( t, p ) { + + return t * t * p; + +} + +/** + * Computes a point on a Quadratic Bezier curve. + * + * @param {number} t - The interpolation factor. + * @param {number} p0 - The first control point. + * @param {number} p1 - The second control point. + * @param {number} p2 - The third control point. + * @return {number} The calculated point on a Quadratic Bezier curve. + */ +function QuadraticBezier( t, p0, p1, p2 ) { + + return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) + + QuadraticBezierP2( t, p2 ); + +} + +// + +function CubicBezierP0( t, p ) { + + const k = 1 - t; + return k * k * k * p; + +} + +function CubicBezierP1( t, p ) { + + const k = 1 - t; + return 3 * k * k * t * p; + +} + +function CubicBezierP2( t, p ) { + + return 3 * ( 1 - t ) * t * t * p; + +} + +function CubicBezierP3( t, p ) { + + return t * t * t * p; + +} + +/** + * Computes a point on a Cubic Bezier curve. + * + * @param {number} t - The interpolation factor. + * @param {number} p0 - The first control point. + * @param {number} p1 - The second control point. + * @param {number} p2 - The third control point. + * @param {number} p3 - The fourth control point. + * @return {number} The calculated point on a Cubic Bezier curve. + */ +function CubicBezier( t, p0, p1, p2, p3 ) { + + return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) + + CubicBezierP3( t, p3 ); + +} + +/** + * A curve representing a 2D Cubic Bezier curve. + * + * ```js + * const curve = new THREE.CubicBezierCurve( + * new THREE.Vector2( - 0, 0 ), + * new THREE.Vector2( - 5, 15 ), + * new THREE.Vector2( 20, 15 ), + * new THREE.Vector2( 10, 0 ) + * ); + * + * const points = curve.getPoints( 50 ); + * const geometry = new THREE.BufferGeometry().setFromPoints( points ); + * + * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } ); + * + * // Create the final object to add to the scene + * const curveObject = new THREE.Line( geometry, material ); + * ``` + * + * @augments Curve + */ +class CubicBezierCurve extends Curve { + + /** + * Constructs a new Cubic Bezier curve. + * + * @param {Vector2} [v0] - The start point. + * @param {Vector2} [v1] - The first control point. + * @param {Vector2} [v2] - The second control point. + * @param {Vector2} [v3] - The end point. + */ + constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) { + + super(); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isCubicBezierCurve = true; + + this.type = 'CubicBezierCurve'; + + /** + * The start point. + * + * @type {Vector2} + */ + this.v0 = v0; + + /** + * The first control point. + * + * @type {Vector2} + */ + this.v1 = v1; + + /** + * The second control point. + * + * @type {Vector2} + */ + this.v2 = v2; + + /** + * The end point. + * + * @type {Vector2} + */ + this.v3 = v3; + + } + + /** + * Returns a point on the curve. + * + * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`. + * @param {Vector2} [optionalTarget] - The optional target vector the result is written to. + * @return {Vector2} The position on the curve. + */ + getPoint( t, optionalTarget = new Vector2() ) { + + const point = optionalTarget; + + const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3; + + point.set( + CubicBezier( t, v0.x, v1.x, v2.x, v3.x ), + CubicBezier( t, v0.y, v1.y, v2.y, v3.y ) + ); + + return point; + + } + + copy( source ) { + + super.copy( source ); + + this.v0.copy( source.v0 ); + this.v1.copy( source.v1 ); + this.v2.copy( source.v2 ); + this.v3.copy( source.v3 ); + + return this; + + } + + toJSON() { + + const data = super.toJSON(); + + data.v0 = this.v0.toArray(); + data.v1 = this.v1.toArray(); + data.v2 = this.v2.toArray(); + data.v3 = this.v3.toArray(); + + return data; + + } + + fromJSON( json ) { + + super.fromJSON( json ); + + this.v0.fromArray( json.v0 ); + this.v1.fromArray( json.v1 ); + this.v2.fromArray( json.v2 ); + this.v3.fromArray( json.v3 ); + + return this; + + } + +} + +/** + * A curve representing a 3D Cubic Bezier curve. + * + * @augments Curve + */ +class CubicBezierCurve3 extends Curve { + + /** + * Constructs a new Cubic Bezier curve. + * + * @param {Vector3} [v0] - The start point. + * @param {Vector3} [v1] - The first control point. + * @param {Vector3} [v2] - The second control point. + * @param {Vector3} [v3] - The end point. + */ + constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) { + + super(); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isCubicBezierCurve3 = true; + + this.type = 'CubicBezierCurve3'; + + /** + * The start point. + * + * @type {Vector3} + */ + this.v0 = v0; + + /** + * The first control point. + * + * @type {Vector3} + */ + this.v1 = v1; + + /** + * The second control point. + * + * @type {Vector3} + */ + this.v2 = v2; + + /** + * The end point. + * + * @type {Vector3} + */ + this.v3 = v3; + + } + + /** + * Returns a point on the curve. + * + * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`. + * @param {Vector3} [optionalTarget] - The optional target vector the result is written to. + * @return {Vector3} The position on the curve. + */ + getPoint( t, optionalTarget = new Vector3() ) { + + const point = optionalTarget; + + const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3; + + point.set( + CubicBezier( t, v0.x, v1.x, v2.x, v3.x ), + CubicBezier( t, v0.y, v1.y, v2.y, v3.y ), + CubicBezier( t, v0.z, v1.z, v2.z, v3.z ) + ); + + return point; + + } + + copy( source ) { + + super.copy( source ); + + this.v0.copy( source.v0 ); + this.v1.copy( source.v1 ); + this.v2.copy( source.v2 ); + this.v3.copy( source.v3 ); + + return this; + + } + + toJSON() { + + const data = super.toJSON(); + + data.v0 = this.v0.toArray(); + data.v1 = this.v1.toArray(); + data.v2 = this.v2.toArray(); + data.v3 = this.v3.toArray(); + + return data; + + } + + fromJSON( json ) { + + super.fromJSON( json ); + + this.v0.fromArray( json.v0 ); + this.v1.fromArray( json.v1 ); + this.v2.fromArray( json.v2 ); + this.v3.fromArray( json.v3 ); + + return this; + + } + +} + +/** + * A curve representing a 2D line segment. + * + * @augments Curve + */ +class LineCurve extends Curve { + + /** + * Constructs a new line curve. + * + * @param {Vector2} [v1] - The start point. + * @param {Vector2} [v2] - The end point. + */ + constructor( v1 = new Vector2(), v2 = new Vector2() ) { + + super(); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isLineCurve = true; + + this.type = 'LineCurve'; + + /** + * The start point. + * + * @type {Vector2} + */ + this.v1 = v1; + + /** + * The end point. + * + * @type {Vector2} + */ + this.v2 = v2; + + } + + /** + * Returns a point on the line. + * + * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`. + * @param {Vector2} [optionalTarget] - The optional target vector the result is written to. + * @return {Vector2} The position on the line. + */ + getPoint( t, optionalTarget = new Vector2() ) { + + const point = optionalTarget; + + if ( t === 1 ) { + + point.copy( this.v2 ); + + } else { + + point.copy( this.v2 ).sub( this.v1 ); + point.multiplyScalar( t ).add( this.v1 ); + + } + + return point; + + } + + // Line curve is linear, so we can overwrite default getPointAt + getPointAt( u, optionalTarget ) { + + return this.getPoint( u, optionalTarget ); + + } + + getTangent( t, optionalTarget = new Vector2() ) { + + return optionalTarget.subVectors( this.v2, this.v1 ).normalize(); + + } + + getTangentAt( u, optionalTarget ) { + + return this.getTangent( u, optionalTarget ); + + } + + copy( source ) { + + super.copy( source ); + + this.v1.copy( source.v1 ); + this.v2.copy( source.v2 ); + + return this; + + } + + toJSON() { + + const data = super.toJSON(); + + data.v1 = this.v1.toArray(); + data.v2 = this.v2.toArray(); + + return data; + + } + + fromJSON( json ) { + + super.fromJSON( json ); + + this.v1.fromArray( json.v1 ); + this.v2.fromArray( json.v2 ); + + return this; + + } + +} + +/** + * A curve representing a 3D line segment. + * + * @augments Curve + */ +class LineCurve3 extends Curve { + + /** + * Constructs a new line curve. + * + * @param {Vector3} [v1] - The start point. + * @param {Vector3} [v2] - The end point. + */ + constructor( v1 = new Vector3(), v2 = new Vector3() ) { + + super(); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isLineCurve3 = true; + + this.type = 'LineCurve3'; + + /** + * The start point. + * + * @type {Vector3} + */ + this.v1 = v1; + + /** + * The end point. + * + * @type {Vector2} + */ + this.v2 = v2; + + } + + /** + * Returns a point on the line. + * + * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`. + * @param {Vector3} [optionalTarget] - The optional target vector the result is written to. + * @return {Vector3} The position on the line. + */ + getPoint( t, optionalTarget = new Vector3() ) { + + const point = optionalTarget; + + if ( t === 1 ) { + + point.copy( this.v2 ); + + } else { + + point.copy( this.v2 ).sub( this.v1 ); + point.multiplyScalar( t ).add( this.v1 ); + + } + + return point; + + } + + // Line curve is linear, so we can overwrite default getPointAt + getPointAt( u, optionalTarget ) { + + return this.getPoint( u, optionalTarget ); + + } + + getTangent( t, optionalTarget = new Vector3() ) { + + return optionalTarget.subVectors( this.v2, this.v1 ).normalize(); + + } + + getTangentAt( u, optionalTarget ) { + + return this.getTangent( u, optionalTarget ); + + } + + copy( source ) { + + super.copy( source ); + + this.v1.copy( source.v1 ); + this.v2.copy( source.v2 ); + + return this; + + } + + toJSON() { + + const data = super.toJSON(); + + data.v1 = this.v1.toArray(); + data.v2 = this.v2.toArray(); + + return data; + + } + + fromJSON( json ) { + + super.fromJSON( json ); + + this.v1.fromArray( json.v1 ); + this.v2.fromArray( json.v2 ); + + return this; + + } + +} + +/** + * A curve representing a 2D Quadratic Bezier curve. + * + * ```js + * const curve = new THREE.QuadraticBezierCurve( + * new THREE.Vector2( - 10, 0 ), + * new THREE.Vector2( 20, 15 ), + * new THREE.Vector2( 10, 0 ) + * ) + * + * const points = curve.getPoints( 50 ); + * const geometry = new THREE.BufferGeometry().setFromPoints( points ); + * + * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } ); + * + * // Create the final object to add to the scene + * const curveObject = new THREE.Line( geometry, material ); + * ``` + * + * @augments Curve + */ +class QuadraticBezierCurve extends Curve { + + /** + * Constructs a new Quadratic Bezier curve. + * + * @param {Vector2} [v0] - The start point. + * @param {Vector2} [v1] - The control point. + * @param {Vector2} [v2] - The end point. + */ + constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) { + + super(); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isQuadraticBezierCurve = true; + + this.type = 'QuadraticBezierCurve'; + + /** + * The start point. + * + * @type {Vector2} + */ + this.v0 = v0; + + /** + * The control point. + * + * @type {Vector2} + */ + this.v1 = v1; + + /** + * The end point. + * + * @type {Vector2} + */ + this.v2 = v2; + + } + + /** + * Returns a point on the curve. + * + * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`. + * @param {Vector2} [optionalTarget] - The optional target vector the result is written to. + * @return {Vector2} The position on the curve. + */ + getPoint( t, optionalTarget = new Vector2() ) { + + const point = optionalTarget; + + const v0 = this.v0, v1 = this.v1, v2 = this.v2; + + point.set( + QuadraticBezier( t, v0.x, v1.x, v2.x ), + QuadraticBezier( t, v0.y, v1.y, v2.y ) + ); + + return point; + + } + + copy( source ) { + + super.copy( source ); + + this.v0.copy( source.v0 ); + this.v1.copy( source.v1 ); + this.v2.copy( source.v2 ); + + return this; + + } + + toJSON() { + + const data = super.toJSON(); + + data.v0 = this.v0.toArray(); + data.v1 = this.v1.toArray(); + data.v2 = this.v2.toArray(); + + return data; + + } + + fromJSON( json ) { + + super.fromJSON( json ); + + this.v0.fromArray( json.v0 ); + this.v1.fromArray( json.v1 ); + this.v2.fromArray( json.v2 ); + + return this; + + } + +} + +/** + * A curve representing a 3D Quadratic Bezier curve. + * + * @augments Curve + */ +class QuadraticBezierCurve3 extends Curve { + + /** + * Constructs a new Quadratic Bezier curve. + * + * @param {Vector3} [v0] - The start point. + * @param {Vector3} [v1] - The control point. + * @param {Vector3} [v2] - The end point. + */ + constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) { + + super(); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isQuadraticBezierCurve3 = true; + + this.type = 'QuadraticBezierCurve3'; + + /** + * The start point. + * + * @type {Vector3} + */ + this.v0 = v0; + + /** + * The control point. + * + * @type {Vector3} + */ + this.v1 = v1; + + /** + * The end point. + * + * @type {Vector3} + */ + this.v2 = v2; + + } + + /** + * Returns a point on the curve. + * + * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`. + * @param {Vector3} [optionalTarget] - The optional target vector the result is written to. + * @return {Vector3} The position on the curve. + */ + getPoint( t, optionalTarget = new Vector3() ) { + + const point = optionalTarget; + + const v0 = this.v0, v1 = this.v1, v2 = this.v2; + + point.set( + QuadraticBezier( t, v0.x, v1.x, v2.x ), + QuadraticBezier( t, v0.y, v1.y, v2.y ), + QuadraticBezier( t, v0.z, v1.z, v2.z ) + ); + + return point; + + } + + copy( source ) { + + super.copy( source ); + + this.v0.copy( source.v0 ); + this.v1.copy( source.v1 ); + this.v2.copy( source.v2 ); + + return this; + + } + + toJSON() { + + const data = super.toJSON(); + + data.v0 = this.v0.toArray(); + data.v1 = this.v1.toArray(); + data.v2 = this.v2.toArray(); + + return data; + + } + + fromJSON( json ) { + + super.fromJSON( json ); + + this.v0.fromArray( json.v0 ); + this.v1.fromArray( json.v1 ); + this.v2.fromArray( json.v2 ); + + return this; + + } + +} + +/** + * A curve representing a 2D spline curve. + * + * ```js + * // Create a sine-like wave + * const curve = new THREE.SplineCurve( [ + * new THREE.Vector2( -10, 0 ), + * new THREE.Vector2( -5, 5 ), + * new THREE.Vector2( 0, 0 ), + * new THREE.Vector2( 5, -5 ), + * new THREE.Vector2( 10, 0 ) + * ] ); + * + * const points = curve.getPoints( 50 ); + * const geometry = new THREE.BufferGeometry().setFromPoints( points ); + * + * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } ); + * + * // Create the final object to add to the scene + * const splineObject = new THREE.Line( geometry, material ); + * ``` + * + * @augments Curve + */ +class SplineCurve extends Curve { + + /** + * Constructs a new 2D spline curve. + * + * @param {Array} [points] - An array of 2D points defining the curve. + */ + constructor( points = [] ) { + + super(); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isSplineCurve = true; + + this.type = 'SplineCurve'; + + /** + * An array of 2D points defining the curve. + * + * @type {Array} + */ + this.points = points; + + } + + /** + * Returns a point on the curve. + * + * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`. + * @param {Vector2} [optionalTarget] - The optional target vector the result is written to. + * @return {Vector2} The position on the curve. + */ + getPoint( t, optionalTarget = new Vector2() ) { + + const point = optionalTarget; + + const points = this.points; + const p = ( points.length - 1 ) * t; + + const intPoint = Math.floor( p ); + const weight = p - intPoint; + + const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ]; + const p1 = points[ intPoint ]; + const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ]; + const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ]; + + point.set( + CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ), + CatmullRom( weight, p0.y, p1.y, p2.y, p3.y ) + ); + + return point; + + } + + copy( source ) { + + super.copy( source ); + + this.points = []; + + for ( let i = 0, l = source.points.length; i < l; i ++ ) { + + const point = source.points[ i ]; + + this.points.push( point.clone() ); + + } + + return this; + + } + + toJSON() { + + const data = super.toJSON(); + + data.points = []; + + for ( let i = 0, l = this.points.length; i < l; i ++ ) { + + const point = this.points[ i ]; + data.points.push( point.toArray() ); + + } + + return data; + + } + + fromJSON( json ) { + + super.fromJSON( json ); + + this.points = []; + + for ( let i = 0, l = json.points.length; i < l; i ++ ) { + + const point = json.points[ i ]; + this.points.push( new Vector2().fromArray( point ) ); + + } + + return this; + + } + +} + +var Curves = /*#__PURE__*/Object.freeze({ + __proto__: null, + ArcCurve: ArcCurve, + CatmullRomCurve3: CatmullRomCurve3, + CubicBezierCurve: CubicBezierCurve, + CubicBezierCurve3: CubicBezierCurve3, + EllipseCurve: EllipseCurve, + LineCurve: LineCurve, + LineCurve3: LineCurve3, + QuadraticBezierCurve: QuadraticBezierCurve, + QuadraticBezierCurve3: QuadraticBezierCurve3, + SplineCurve: SplineCurve +}); + +/** + * A base class extending {@link Curve}. `CurvePath` is simply an + * array of connected curves, but retains the API of a curve. + * + * @augments Curve + */ +class CurvePath extends Curve { + + /** + * Constructs a new curve path. + */ + constructor() { + + super(); + + this.type = 'CurvePath'; + + /** + * An array of curves defining the + * path. + * + * @type {Array} + */ + this.curves = []; + + /** + * Whether the path should automatically be closed + * by a line curve. + * + * @type {boolean} + * @default false + */ + this.autoClose = false; + + } + + /** + * Adds a curve to this curve path. + * + * @param {Curve} curve - The curve to add. + */ + add( curve ) { + + this.curves.push( curve ); + + } + + /** + * Adds a line curve to close the path. + * + * @return {CurvePath} A reference to this curve path. + */ + closePath() { + + // Add a line curve if start and end of lines are not connected + const startPoint = this.curves[ 0 ].getPoint( 0 ); + const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 ); + + if ( ! startPoint.equals( endPoint ) ) { + + const lineType = ( startPoint.isVector2 === true ) ? 'LineCurve' : 'LineCurve3'; + this.curves.push( new Curves[ lineType ]( endPoint, startPoint ) ); + + } + + return this; + + } + + /** + * This method returns a vector in 2D or 3D space (depending on the curve definitions) + * for the given interpolation factor. + * + * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`. + * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to. + * @return {?(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition. + */ + getPoint( t, optionalTarget ) { + + // To get accurate point with reference to + // entire path distance at time t, + // following has to be done: + + // 1. Length of each sub path have to be known + // 2. Locate and identify type of curve + // 3. Get t for the curve + // 4. Return curve.getPointAt(t') + + const d = t * this.getLength(); + const curveLengths = this.getCurveLengths(); + let i = 0; + + // To think about boundaries points. + + while ( i < curveLengths.length ) { + + if ( curveLengths[ i ] >= d ) { + + const diff = curveLengths[ i ] - d; + const curve = this.curves[ i ]; + + const segmentLength = curve.getLength(); + const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength; + + return curve.getPointAt( u, optionalTarget ); + + } + + i ++; + + } + + return null; + + // loop where sum != 0, sum > d , sum+1 } The curve lengths. + */ + getCurveLengths() { + + // Compute lengths and cache them + // We cannot overwrite getLengths() because UtoT mapping uses it. + // We use cache values if curves and cache array are same length + + if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) { + + return this.cacheLengths; + + } + + // Get length of sub-curve + // Push sums into cached array + + const lengths = []; + let sums = 0; + + for ( let i = 0, l = this.curves.length; i < l; i ++ ) { + + sums += this.curves[ i ].getLength(); + lengths.push( sums ); + + } + + this.cacheLengths = lengths; + + return lengths; + + } + + getSpacedPoints( divisions = 40 ) { + + const points = []; + + for ( let i = 0; i <= divisions; i ++ ) { + + points.push( this.getPoint( i / divisions ) ); + + } + + if ( this.autoClose ) { + + points.push( points[ 0 ] ); + + } + + return points; + + } + + getPoints( divisions = 12 ) { + + const points = []; + let last; + + for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) { + + const curve = curves[ i ]; + const resolution = curve.isEllipseCurve ? divisions * 2 + : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1 + : curve.isSplineCurve ? divisions * curve.points.length + : divisions; + + const pts = curve.getPoints( resolution ); + + for ( let j = 0; j < pts.length; j ++ ) { + + const point = pts[ j ]; + + if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates + + points.push( point ); + last = point; + + } + + } + + if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) { + + points.push( points[ 0 ] ); + + } + + return points; + + } + + copy( source ) { + + super.copy( source ); + + this.curves = []; + + for ( let i = 0, l = source.curves.length; i < l; i ++ ) { + + const curve = source.curves[ i ]; + + this.curves.push( curve.clone() ); + + } + + this.autoClose = source.autoClose; + + return this; + + } + + toJSON() { + + const data = super.toJSON(); + + data.autoClose = this.autoClose; + data.curves = []; + + for ( let i = 0, l = this.curves.length; i < l; i ++ ) { + + const curve = this.curves[ i ]; + data.curves.push( curve.toJSON() ); + + } + + return data; + + } + + fromJSON( json ) { + + super.fromJSON( json ); + + this.autoClose = json.autoClose; + this.curves = []; + + for ( let i = 0, l = json.curves.length; i < l; i ++ ) { + + const curve = json.curves[ i ]; + this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) ); + + } + + return this; + + } + +} + +/** + * A 2D path representation. The class provides methods for creating paths + * and contours of 2D shapes similar to the 2D Canvas API. + * + * ```js + * const path = new THREE.Path(); + * + * path.lineTo( 0, 0.8 ); + * path.quadraticCurveTo( 0, 1, 0.2, 1 ); + * path.lineTo( 1, 1 ); + * + * const points = path.getPoints(); + * + * const geometry = new THREE.BufferGeometry().setFromPoints( points ); + * const material = new THREE.LineBasicMaterial( { color: 0xffffff } ); + * + * const line = new THREE.Line( geometry, material ); + * scene.add( line ); + * ``` + * + * @augments CurvePath + */ +class Path extends CurvePath { + + /** + * Constructs a new path. + * + * @param {Array} [points] - An array of 2D points defining the path. + */ + constructor( points ) { + + super(); + + this.type = 'Path'; + + /** + * The current offset of the path. Any new curve added will start here. + * + * @type {Vector2} + */ + this.currentPoint = new Vector2(); + + if ( points ) { + + this.setFromPoints( points ); + + } + + } + + /** + * Creates a path from the given list of points. The points are added + * to the path as instances of {@link LineCurve}. + * + * @param {Array} points - An array of 2D points. + * @return {Path} A reference to this path. + */ + setFromPoints( points ) { + + this.moveTo( points[ 0 ].x, points[ 0 ].y ); + + for ( let i = 1, l = points.length; i < l; i ++ ) { + + this.lineTo( points[ i ].x, points[ i ].y ); + + } + + return this; + + } + + /** + * Moves {@link Path#currentPoint} to the given point. + * + * @param {number} x - The x coordinate. + * @param {number} y - The y coordinate. + * @return {Path} A reference to this path. + */ + moveTo( x, y ) { + + this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying? + + return this; + + } + + /** + * Adds an instance of {@link LineCurve} to the path by connecting + * the current point with the given one. + * + * @param {number} x - The x coordinate of the end point. + * @param {number} y - The y coordinate of the end point. + * @return {Path} A reference to this path. + */ + lineTo( x, y ) { + + const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) ); + this.curves.push( curve ); + + this.currentPoint.set( x, y ); + + return this; + + } + + /** + * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting + * the current point with the given one. + * + * @param {number} aCPx - The x coordinate of the control point. + * @param {number} aCPy - The y coordinate of the control point. + * @param {number} aX - The x coordinate of the end point. + * @param {number} aY - The y coordinate of the end point. + * @return {Path} A reference to this path. + */ + quadraticCurveTo( aCPx, aCPy, aX, aY ) { + + const curve = new QuadraticBezierCurve( + this.currentPoint.clone(), + new Vector2( aCPx, aCPy ), + new Vector2( aX, aY ) + ); + + this.curves.push( curve ); + + this.currentPoint.set( aX, aY ); + + return this; + + } + + /** + * Adds an instance of {@link CubicBezierCurve} to the path by connecting + * the current point with the given one. + * + * @param {number} aCP1x - The x coordinate of the first control point. + * @param {number} aCP1y - The y coordinate of the first control point. + * @param {number} aCP2x - The x coordinate of the second control point. + * @param {number} aCP2y - The y coordinate of the second control point. + * @param {number} aX - The x coordinate of the end point. + * @param {number} aY - The y coordinate of the end point. + * @return {Path} A reference to this path. + */ + bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) { + + const curve = new CubicBezierCurve( + this.currentPoint.clone(), + new Vector2( aCP1x, aCP1y ), + new Vector2( aCP2x, aCP2y ), + new Vector2( aX, aY ) + ); + + this.curves.push( curve ); + + this.currentPoint.set( aX, aY ); + + return this; + + } + + /** + * Adds an instance of {@link SplineCurve} to the path by connecting + * the current point with the given list of points. + * + * @param {Array} pts - An array of points in 2D space. + * @return {Path} A reference to this path. + */ + splineThru( pts ) { + + const npts = [ this.currentPoint.clone() ].concat( pts ); + + const curve = new SplineCurve( npts ); + this.curves.push( curve ); + + this.currentPoint.copy( pts[ pts.length - 1 ] ); + + return this; + + } + + /** + * Adds an arc as an instance of {@link EllipseCurve} to the path, positioned relative + * to the current point. + * + * @param {number} [aX=0] - The x coordinate of the center of the arc offsetted from the previous curve. + * @param {number} [aY=0] - The y coordinate of the center of the arc offsetted from the previous curve. + * @param {number} [aRadius=1] - The radius of the arc. + * @param {number} [aStartAngle=0] - The start angle in radians. + * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians. + * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not. + * @return {Path} A reference to this path. + */ + arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { + + const x0 = this.currentPoint.x; + const y0 = this.currentPoint.y; + + this.absarc( aX + x0, aY + y0, aRadius, + aStartAngle, aEndAngle, aClockwise ); + + return this; + + } + + /** + * Adds an absolutely positioned arc as an instance of {@link EllipseCurve} to the path. + * + * @param {number} [aX=0] - The x coordinate of the center of the arc. + * @param {number} [aY=0] - The y coordinate of the center of the arc. + * @param {number} [aRadius=1] - The radius of the arc. + * @param {number} [aStartAngle=0] - The start angle in radians. + * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians. + * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not. + * @return {Path} A reference to this path. + */ + absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { + + this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise ); + + return this; + + } + + /** + * Adds an ellipse as an instance of {@link EllipseCurve} to the path, positioned relative + * to the current point + * + * @param {number} [aX=0] - The x coordinate of the center of the ellipse offsetted from the previous curve. + * @param {number} [aY=0] - The y coordinate of the center of the ellipse offsetted from the previous curve. + * @param {number} [xRadius=1] - The radius of the ellipse in the x axis. + * @param {number} [yRadius=1] - The radius of the ellipse in the y axis. + * @param {number} [aStartAngle=0] - The start angle in radians. + * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians. + * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not. + * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis. + * @return {Path} A reference to this path. + */ + ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { + + const x0 = this.currentPoint.x; + const y0 = this.currentPoint.y; + + this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ); + + return this; + + } + + /** + * Adds an absolutely positioned ellipse as an instance of {@link EllipseCurve} to the path. + * + * @param {number} [aX=0] - The x coordinate of the absolute center of the ellipse. + * @param {number} [aY=0] - The y coordinate of the absolute center of the ellipse. + * @param {number} [xRadius=1] - The radius of the ellipse in the x axis. + * @param {number} [yRadius=1] - The radius of the ellipse in the y axis. + * @param {number} [aStartAngle=0] - The start angle in radians. + * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians. + * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not. + * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis. + * @return {Path} A reference to this path. + */ + absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { + + const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ); + + if ( this.curves.length > 0 ) { + + // if a previous curve is present, attempt to join + const firstPoint = curve.getPoint( 0 ); + + if ( ! firstPoint.equals( this.currentPoint ) ) { + + this.lineTo( firstPoint.x, firstPoint.y ); + + } + + } + + this.curves.push( curve ); + + const lastPoint = curve.getPoint( 1 ); + this.currentPoint.copy( lastPoint ); + + return this; + + } + + copy( source ) { + + super.copy( source ); + + this.currentPoint.copy( source.currentPoint ); + + return this; + + } + + toJSON() { + + const data = super.toJSON(); + + data.currentPoint = this.currentPoint.toArray(); + + return data; + + } + + fromJSON( json ) { + + super.fromJSON( json ); + + this.currentPoint.fromArray( json.currentPoint ); + + return this; + + } + +} + +/** + * Defines an arbitrary 2d shape plane using paths with optional holes. It + * can be used with {@link ExtrudeGeometry}, {@link ShapeGeometry}, to get + * points, or to get triangulated faces. + * + * ```js + * const heartShape = new THREE.Shape(); + * + * heartShape.moveTo( 25, 25 ); + * heartShape.bezierCurveTo( 25, 25, 20, 0, 0, 0 ); + * heartShape.bezierCurveTo( - 30, 0, - 30, 35, - 30, 35 ); + * heartShape.bezierCurveTo( - 30, 55, - 10, 77, 25, 95 ); + * heartShape.bezierCurveTo( 60, 77, 80, 55, 80, 35 ); + * heartShape.bezierCurveTo( 80, 35, 80, 0, 50, 0 ); + * heartShape.bezierCurveTo( 35, 0, 25, 25, 25, 25 ); + * + * const extrudeSettings = { + * depth: 8, + * bevelEnabled: true, + * bevelSegments: 2, + * steps: 2, + * bevelSize: 1, + * bevelThickness: 1 + * }; + * + * const geometry = new THREE.ExtrudeGeometry( heartShape, extrudeSettings ); + * const mesh = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial() ); + * ``` + * + * @augments Path + */ +class Shape extends Path { + + /** + * Constructs a new shape. + * + * @param {Array} [points] - An array of 2D points defining the shape. + */ + constructor( points ) { + + super( points ); + + /** + * The UUID of the shape. + * + * @type {string} + * @readonly + */ + this.uuid = generateUUID(); + + this.type = 'Shape'; + + /** + * Defines the holes in the shape. Hole definitions must use the + * opposite winding order (CW/CCW) than the outer shape. + * + * @type {Array} + * @readonly + */ + this.holes = []; + + } + + /** + * Returns an array representing each contour of the holes + * as a list of 2D points. + * + * @param {number} divisions - The fineness of the result. + * @return {Array>} The holes as a series of 2D points. + */ + getPointsHoles( divisions ) { + + const holesPts = []; + + for ( let i = 0, l = this.holes.length; i < l; i ++ ) { + + holesPts[ i ] = this.holes[ i ].getPoints( divisions ); + + } + + return holesPts; + + } + + // get points of shape and holes (keypoints based on segments parameter) + + /** + * Returns an object that holds contour data for the shape and its holes as + * arrays of 2D points. + * + * @param {number} divisions - The fineness of the result. + * @return {{shape:Array,holes:Array>}} An object with contour data. + */ + extractPoints( divisions ) { + + return { + + shape: this.getPoints( divisions ), + holes: this.getPointsHoles( divisions ) + + }; + + } + + copy( source ) { + + super.copy( source ); + + this.holes = []; + + for ( let i = 0, l = source.holes.length; i < l; i ++ ) { + + const hole = source.holes[ i ]; + + this.holes.push( hole.clone() ); + + } + + return this; + + } + + toJSON() { + + const data = super.toJSON(); + + data.uuid = this.uuid; + data.holes = []; + + for ( let i = 0, l = this.holes.length; i < l; i ++ ) { + + const hole = this.holes[ i ]; + data.holes.push( hole.toJSON() ); + + } + + return data; + + } + + fromJSON( json ) { + + super.fromJSON( json ); + + this.uuid = json.uuid; + this.holes = []; + + for ( let i = 0, l = json.holes.length; i < l; i ++ ) { + + const hole = json.holes[ i ]; + this.holes.push( new Path().fromJSON( hole ) ); + + } + + return this; + + } + +} + +/* eslint-disable */ +// copy of mapbox/earcut version 3.0.2 +// https://github.com/mapbox/earcut/tree/v3.0.2 + +function earcut(data, holeIndices, dim = 2) { + + const hasHoles = holeIndices && holeIndices.length; + const outerLen = hasHoles ? holeIndices[0] * dim : data.length; + let outerNode = linkedList(data, 0, outerLen, dim, true); + const triangles = []; + + if (!outerNode || outerNode.next === outerNode.prev) return triangles; + + let minX, minY, invSize; + + if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim); + + // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox + if (data.length > 80 * dim) { + minX = data[0]; + minY = data[1]; + let maxX = minX; + let maxY = minY; + + for (let i = dim; i < outerLen; i += dim) { + const x = data[i]; + const y = data[i + 1]; + if (x < minX) minX = x; + if (y < minY) minY = y; + if (x > maxX) maxX = x; + if (y > maxY) maxY = y; + } + + // minX, minY and invSize are later used to transform coords into integers for z-order calculation + invSize = Math.max(maxX - minX, maxY - minY); + invSize = invSize !== 0 ? 32767 / invSize : 0; + } + + earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0); + + return triangles; +} + +// create a circular doubly linked list from polygon points in the specified winding order +function linkedList(data, start, end, dim, clockwise) { + let last; + + if (clockwise === (signedArea(data, start, end, dim) > 0)) { + for (let i = start; i < end; i += dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last); + } else { + for (let i = end - dim; i >= start; i -= dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last); + } + + if (last && equals(last, last.next)) { + removeNode(last); + last = last.next; + } + + return last; +} + +// eliminate colinear or duplicate points +function filterPoints(start, end) { + if (!start) return start; + if (!end) end = start; + + let p = start, + again; + do { + again = false; + + if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) { + removeNode(p); + p = end = p.prev; + if (p === p.next) break; + again = true; + + } else { + p = p.next; + } + } while (again || p !== end); + + return end; +} + +// main ear slicing loop which triangulates a polygon (given as a linked list) +function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) { + if (!ear) return; + + // interlink polygon nodes in z-order + if (!pass && invSize) indexCurve(ear, minX, minY, invSize); + + let stop = ear; + + // iterate through ears, slicing them one by one + while (ear.prev !== ear.next) { + const prev = ear.prev; + const next = ear.next; + + if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) { + triangles.push(prev.i, ear.i, next.i); // cut off the triangle + + removeNode(ear); + + // skipping the next vertex leads to less sliver triangles + ear = next.next; + stop = next.next; + + continue; + } + + ear = next; + + // if we looped through the whole remaining polygon and can't find any more ears + if (ear === stop) { + // try filtering points and slicing again + if (!pass) { + earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); + + // if this didn't work, try curing all small self-intersections locally + } else if (pass === 1) { + ear = cureLocalIntersections(filterPoints(ear), triangles); + earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); + + // as a last resort, try splitting the remaining polygon into two + } else if (pass === 2) { + splitEarcut(ear, triangles, dim, minX, minY, invSize); + } + + break; + } + } +} + +// check whether a polygon node forms a valid ear with adjacent nodes +function isEar(ear) { + const a = ear.prev, + b = ear, + c = ear.next; + + if (area(a, b, c) >= 0) return false; // reflex, can't be an ear + + // now make sure we don't have other points inside the potential ear + const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y; + + // triangle bbox + const x0 = Math.min(ax, bx, cx), + y0 = Math.min(ay, by, cy), + x1 = Math.max(ax, bx, cx), + y1 = Math.max(ay, by, cy); + + let p = c.next; + while (p !== a) { + if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && + pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && + area(p.prev, p, p.next) >= 0) return false; + p = p.next; + } + + return true; +} + +function isEarHashed(ear, minX, minY, invSize) { + const a = ear.prev, + b = ear, + c = ear.next; + + if (area(a, b, c) >= 0) return false; // reflex, can't be an ear + + const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y; + + // triangle bbox + const x0 = Math.min(ax, bx, cx), + y0 = Math.min(ay, by, cy), + x1 = Math.max(ax, bx, cx), + y1 = Math.max(ay, by, cy); + + // z-order range for the current triangle bbox; + const minZ = zOrder(x0, y0, minX, minY, invSize), + maxZ = zOrder(x1, y1, minX, minY, invSize); + + let p = ear.prevZ, + n = ear.nextZ; + + // look for points inside the triangle in both directions + while (p && p.z >= minZ && n && n.z <= maxZ) { + if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c && + pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false; + p = p.prevZ; + + if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c && + pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false; + n = n.nextZ; + } + + // look for remaining points in decreasing z-order + while (p && p.z >= minZ) { + if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c && + pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false; + p = p.prevZ; + } + + // look for remaining points in increasing z-order + while (n && n.z <= maxZ) { + if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c && + pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false; + n = n.nextZ; + } + + return true; +} + +// go through all polygon nodes and cure small local self-intersections +function cureLocalIntersections(start, triangles) { + let p = start; + do { + const a = p.prev, + b = p.next.next; + + if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) { + + triangles.push(a.i, p.i, b.i); + + // remove two nodes involved + removeNode(p); + removeNode(p.next); + + p = start = b; + } + p = p.next; + } while (p !== start); + + return filterPoints(p); +} + +// try splitting polygon into two and triangulate them independently +function splitEarcut(start, triangles, dim, minX, minY, invSize) { + // look for a valid diagonal that divides the polygon into two + let a = start; + do { + let b = a.next.next; + while (b !== a.prev) { + if (a.i !== b.i && isValidDiagonal(a, b)) { + // split the polygon in two by the diagonal + let c = splitPolygon(a, b); + + // filter colinear points around the cuts + a = filterPoints(a, a.next); + c = filterPoints(c, c.next); + + // run earcut on each half + earcutLinked(a, triangles, dim, minX, minY, invSize, 0); + earcutLinked(c, triangles, dim, minX, minY, invSize, 0); + return; + } + b = b.next; + } + a = a.next; + } while (a !== start); +} + +// link every hole into the outer loop, producing a single-ring polygon without holes +function eliminateHoles(data, holeIndices, outerNode, dim) { + const queue = []; + + for (let i = 0, len = holeIndices.length; i < len; i++) { + const start = holeIndices[i] * dim; + const end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; + const list = linkedList(data, start, end, dim, false); + if (list === list.next) list.steiner = true; + queue.push(getLeftmost(list)); + } + + queue.sort(compareXYSlope); + + // process holes from left to right + for (let i = 0; i < queue.length; i++) { + outerNode = eliminateHole(queue[i], outerNode); + } + + return outerNode; +} + +function compareXYSlope(a, b) { + let result = a.x - b.x; + // when the left-most point of 2 holes meet at a vertex, sort the holes counterclockwise so that when we find + // the bridge to the outer shell is always the point that they meet at. + if (result === 0) { + result = a.y - b.y; + if (result === 0) { + const aSlope = (a.next.y - a.y) / (a.next.x - a.x); + const bSlope = (b.next.y - b.y) / (b.next.x - b.x); + result = aSlope - bSlope; + } + } + return result; +} + +// find a bridge between vertices that connects hole with an outer ring and link it +function eliminateHole(hole, outerNode) { + const bridge = findHoleBridge(hole, outerNode); + if (!bridge) { + return outerNode; + } + + const bridgeReverse = splitPolygon(bridge, hole); + + // filter collinear points around the cuts + filterPoints(bridgeReverse, bridgeReverse.next); + return filterPoints(bridge, bridge.next); +} + +// David Eberly's algorithm for finding a bridge between hole and outer polygon +function findHoleBridge(hole, outerNode) { + let p = outerNode; + const hx = hole.x; + const hy = hole.y; + let qx = -Infinity; + let m; + + // find a segment intersected by a ray from the hole's leftmost point to the left; + // segment's endpoint with lesser x will be potential connection point + // unless they intersect at a vertex, then choose the vertex + if (equals(hole, p)) return p; + do { + if (equals(hole, p.next)) return p.next; + else if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) { + const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y); + if (x <= hx && x > qx) { + qx = x; + m = p.x < p.next.x ? p : p.next; + if (x === hx) return m; // hole touches outer segment; pick leftmost endpoint + } + } + p = p.next; + } while (p !== outerNode); + + if (!m) return null; + + // look for points inside the triangle of hole point, segment intersection and endpoint; + // if there are no points found, we have a valid connection; + // otherwise choose the point of the minimum angle with the ray as connection point + + const stop = m; + const mx = m.x; + const my = m.y; + let tanMin = Infinity; + + p = m; + + do { + if (hx >= p.x && p.x >= mx && hx !== p.x && + pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) { + + const tan = Math.abs(hy - p.y) / (hx - p.x); // tangential + + if (locallyInside(p, hole) && + (tan < tanMin || (tan === tanMin && (p.x > m.x || (p.x === m.x && sectorContainsSector(m, p)))))) { + m = p; + tanMin = tan; + } + } + + p = p.next; + } while (p !== stop); + + return m; +} + +// whether sector in vertex m contains sector in vertex p in the same coordinates +function sectorContainsSector(m, p) { + return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0; +} + +// interlink polygon nodes in z-order +function indexCurve(start, minX, minY, invSize) { + let p = start; + do { + if (p.z === 0) p.z = zOrder(p.x, p.y, minX, minY, invSize); + p.prevZ = p.prev; + p.nextZ = p.next; + p = p.next; + } while (p !== start); + + p.prevZ.nextZ = null; + p.prevZ = null; + + sortLinked(p); +} + +// Simon Tatham's linked list merge sort algorithm +// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html +function sortLinked(list) { + let numMerges; + let inSize = 1; + + do { + let p = list; + let e; + list = null; + let tail = null; + numMerges = 0; + + while (p) { + numMerges++; + let q = p; + let pSize = 0; + for (let i = 0; i < inSize; i++) { + pSize++; + q = q.nextZ; + if (!q) break; + } + let qSize = inSize; + + while (pSize > 0 || (qSize > 0 && q)) { + + if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) { + e = p; + p = p.nextZ; + pSize--; + } else { + e = q; + q = q.nextZ; + qSize--; + } + + if (tail) tail.nextZ = e; + else list = e; + + e.prevZ = tail; + tail = e; + } + + p = q; + } + + tail.nextZ = null; + inSize *= 2; + + } while (numMerges > 1); + + return list; +} + +// z-order of a point given coords and inverse of the longer side of data bbox +function zOrder(x, y, minX, minY, invSize) { + // coords are transformed into non-negative 15-bit integer range + x = (x - minX) * invSize | 0; + y = (y - minY) * invSize | 0; + + x = (x | (x << 8)) & 0x00FF00FF; + x = (x | (x << 4)) & 0x0F0F0F0F; + x = (x | (x << 2)) & 0x33333333; + x = (x | (x << 1)) & 0x55555555; + + y = (y | (y << 8)) & 0x00FF00FF; + y = (y | (y << 4)) & 0x0F0F0F0F; + y = (y | (y << 2)) & 0x33333333; + y = (y | (y << 1)) & 0x55555555; + + return x | (y << 1); +} + +// find the leftmost node of a polygon ring +function getLeftmost(start) { + let p = start, + leftmost = start; + do { + if (p.x < leftmost.x || (p.x === leftmost.x && p.y < leftmost.y)) leftmost = p; + p = p.next; + } while (p !== start); + + return leftmost; +} + +// check if a point lies within a convex triangle +function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) { + return (cx - px) * (ay - py) >= (ax - px) * (cy - py) && + (ax - px) * (by - py) >= (bx - px) * (ay - py) && + (bx - px) * (cy - py) >= (cx - px) * (by - py); +} + +// check if a point lies within a convex triangle but false if its equal to the first point of the triangle +function pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, px, py) { + return !(ax === px && ay === py) && pointInTriangle(ax, ay, bx, by, cx, cy, px, py); +} + +// check if a diagonal between two polygon nodes is valid (lies in polygon interior) +function isValidDiagonal(a, b) { + return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && // doesn't intersect other edges + (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && // locally visible + (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors + equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case +} + +// signed area of a triangle +function area(p, q, r) { + return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); +} + +// check if two points are equal +function equals(p1, p2) { + return p1.x === p2.x && p1.y === p2.y; +} + +// check if two segments intersect +function intersects(p1, q1, p2, q2) { + const o1 = sign(area(p1, q1, p2)); + const o2 = sign(area(p1, q1, q2)); + const o3 = sign(area(p2, q2, p1)); + const o4 = sign(area(p2, q2, q1)); + + if (o1 !== o2 && o3 !== o4) return true; // general case + + if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1 + if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1 + if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2 + if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2 + + return false; +} + +// for collinear points p, q, r, check if point q lies on segment pr +function onSegment(p, q, r) { + return q.x <= Math.max(p.x, r.x) && q.x >= Math.min(p.x, r.x) && q.y <= Math.max(p.y, r.y) && q.y >= Math.min(p.y, r.y); +} + +function sign(num) { + return num > 0 ? 1 : num < 0 ? -1 : 0; +} + +// check if a polygon diagonal intersects any polygon segments +function intersectsPolygon(a, b) { + let p = a; + do { + if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && + intersects(p, p.next, a, b)) return true; + p = p.next; + } while (p !== a); + + return false; +} + +// check if a polygon diagonal is locally inside the polygon +function locallyInside(a, b) { + return area(a.prev, a, a.next) < 0 ? + area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 : + area(a, b, a.prev) < 0 || area(a, a.next, b) < 0; +} + +// check if the middle point of a polygon diagonal is inside the polygon +function middleInside(a, b) { + let p = a; + let inside = false; + const px = (a.x + b.x) / 2; + const py = (a.y + b.y) / 2; + do { + if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y && + (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x)) + inside = !inside; + p = p.next; + } while (p !== a); + + return inside; +} + +// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two; +// if one belongs to the outer ring and another to a hole, it merges it into a single ring +function splitPolygon(a, b) { + const a2 = createNode(a.i, a.x, a.y), + b2 = createNode(b.i, b.x, b.y), + an = a.next, + bp = b.prev; + + a.next = b; + b.prev = a; + + a2.next = an; + an.prev = a2; + + b2.next = a2; + a2.prev = b2; + + bp.next = b2; + b2.prev = bp; + + return b2; +} + +// create a node and optionally link it with previous one (in a circular doubly linked list) +function insertNode(i, x, y, last) { + const p = createNode(i, x, y); + + if (!last) { + p.prev = p; + p.next = p; + + } else { + p.next = last.next; + p.prev = last; + last.next.prev = p; + last.next = p; + } + return p; +} + +function removeNode(p) { + p.next.prev = p.prev; + p.prev.next = p.next; + + if (p.prevZ) p.prevZ.nextZ = p.nextZ; + if (p.nextZ) p.nextZ.prevZ = p.prevZ; +} + +function createNode(i, x, y) { + return { + i, // vertex index in coordinates array + x, y, // vertex coordinates + prev: null, // previous and next vertex nodes in a polygon ring + next: null, + z: 0, // z-order curve value + prevZ: null, // previous and next nodes in z-order + nextZ: null, + steiner: false // indicates whether this is a steiner point + }; +} + +function signedArea(data, start, end, dim) { + let sum = 0; + for (let i = start, j = end - dim; i < end; i += dim) { + sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]); + j = i; + } + return sum; +} + +/** + * An implementation of the earcut polygon triangulation algorithm. + * The code is a port of [mapbox/earcut](https://github.com/mapbox/earcut). + * + * @see https://github.com/mapbox/earcut + */ +class Earcut { + + /** + * Triangulates the given shape definition by returning an array of triangles. + * + * @param {Array} data - An array with 2D points. + * @param {Array} holeIndices - An array with indices defining holes. + * @param {number} [dim=2] - The number of coordinates per vertex in the input array. + * @return {Array} An array representing the triangulated faces. Each face is defined by three consecutive numbers + * representing vertex indices. + */ + static triangulate( data, holeIndices, dim = 2 ) { + + return earcut( data, holeIndices, dim ); + + } + +} + +/** + * A class containing utility functions for shapes. + * + * @hideconstructor + */ +class ShapeUtils { + + /** + * Calculate area of a ( 2D ) contour polygon. + * + * @param {Array} contour - An array of 2D points. + * @return {number} The area. + */ + static area( contour ) { + + const n = contour.length; + let a = 0.0; + + for ( let p = n - 1, q = 0; q < n; p = q ++ ) { + + a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y; + + } + + return a * 0.5; + + } + + /** + * Returns `true` if the given contour uses a clockwise winding order. + * + * @param {Array} pts - An array of 2D points defining a polygon. + * @return {boolean} Whether the given contour uses a clockwise winding order or not. + */ + static isClockWise( pts ) { + + return ShapeUtils.area( pts ) < 0; + + } + + /** + * Triangulates the given shape definition. + * + * @param {Array} contour - An array of 2D points defining the contour. + * @param {Array>} holes - An array that holds arrays of 2D points defining the holes. + * @return {Array>} An array that holds for each face definition an array with three indices. + */ + static triangulateShape( contour, holes ) { + + const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ] + const holeIndices = []; // array of hole indices + const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ] + + removeDupEndPts( contour ); + addContour( vertices, contour ); + + // + + let holeIndex = contour.length; + + holes.forEach( removeDupEndPts ); + + for ( let i = 0; i < holes.length; i ++ ) { + + holeIndices.push( holeIndex ); + holeIndex += holes[ i ].length; + addContour( vertices, holes[ i ] ); + + } + + // + + const triangles = Earcut.triangulate( vertices, holeIndices ); + + // + + for ( let i = 0; i < triangles.length; i += 3 ) { + + faces.push( triangles.slice( i, i + 3 ) ); + + } + + return faces; + + } + +} + +function removeDupEndPts( points ) { + + const l = points.length; + + if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) { + + points.pop(); + + } + +} + +function addContour( vertices, contour ) { + + for ( let i = 0; i < contour.length; i ++ ) { + + vertices.push( contour[ i ].x ); + vertices.push( contour[ i ].y ); + + } + +} + +/** + * Creates extruded geometry from a path shape. + * + * ```js + * const length = 12, width = 8; + * + * const shape = new THREE.Shape(); + * shape.moveTo( 0,0 ); + * shape.lineTo( 0, width ); + * shape.lineTo( length, width ); + * shape.lineTo( length, 0 ); + * shape.lineTo( 0, 0 ); + * + * const geometry = new THREE.ExtrudeGeometry( shape ); + * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } ); + * const mesh = new THREE.Mesh( geometry, material ) ; + * scene.add( mesh ); + * ``` + * + * @augments BufferGeometry + * @demo scenes/geometry-browser.html#ExtrudeGeometry + */ +class ExtrudeGeometry extends BufferGeometry { + + /** + * Constructs a new extrude geometry. + * + * @param {Shape|Array} [shapes] - A shape or an array of shapes. + * @param {ExtrudeGeometry~Options} [options] - The extrude settings. + */ + constructor( shapes = new Shape( [ new Vector2( 0.5, 0.5 ), new Vector2( -0.5, 0.5 ), new Vector2( -0.5, -0.5 ), new Vector2( 0.5, -0.5 ) ] ), options = {} ) { + + super(); + + this.type = 'ExtrudeGeometry'; + + /** + * Holds the constructor parameters that have been + * used to generate the geometry. Any modification + * after instantiation does not change the geometry. + * + * @type {Object} + */ + this.parameters = { + shapes: shapes, + options: options + }; + + shapes = Array.isArray( shapes ) ? shapes : [ shapes ]; + + const scope = this; + + const verticesArray = []; + const uvArray = []; + + for ( let i = 0, l = shapes.length; i < l; i ++ ) { + + const shape = shapes[ i ]; + addShape( shape ); + + } + + // build geometry + + this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) ); + + this.computeVertexNormals(); + + // functions + + function addShape( shape ) { + + const placeholder = []; + + // options + + const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12; + const steps = options.steps !== undefined ? options.steps : 1; + const depth = options.depth !== undefined ? options.depth : 1; + + let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; + let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2; + let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1; + let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0; + let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3; + + const extrudePath = options.extrudePath; + + const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator; + + // + + let extrudePts, extrudeByPath = false; + let splineTube, binormal, normal, position2; + + if ( extrudePath ) { + + extrudePts = extrudePath.getSpacedPoints( steps ); + + extrudeByPath = true; + bevelEnabled = false; // bevels not supported for path extrusion + + // SETUP TNB variables + + const isClosed = extrudePath.isCatmullRomCurve3 ? extrudePath.closed : false; + + splineTube = extrudePath.computeFrenetFrames( steps, isClosed ); + + // log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length); + + binormal = new Vector3(); + normal = new Vector3(); + position2 = new Vector3(); + + } + + // Safeguards if bevels are not enabled + + if ( ! bevelEnabled ) { + + bevelSegments = 0; + bevelThickness = 0; + bevelSize = 0; + bevelOffset = 0; + + } + + // Variables initialization + + const shapePoints = shape.extractPoints( curveSegments ); + + let vertices = shapePoints.shape; + const holes = shapePoints.holes; + + const reverse = ! ShapeUtils.isClockWise( vertices ); + + if ( reverse ) { + + vertices = vertices.reverse(); + + // Maybe we should also check if holes are in the opposite direction, just to be safe ... + + for ( let h = 0, hl = holes.length; h < hl; h ++ ) { + + const ahole = holes[ h ]; + + if ( ShapeUtils.isClockWise( ahole ) ) { + + holes[ h ] = ahole.reverse(); + + } + + } + + } + + /**Merges index-adjacent points that are within a threshold distance of each other. Array is modified in-place. Threshold distance is empirical, and scaled based on the magnitude of point coordinates. + * @param {Array} points + */ + function mergeOverlappingPoints( points ) { + + const THRESHOLD = 1e-10; + const THRESHOLD_SQ = THRESHOLD * THRESHOLD; + let prevPos = points[ 0 ]; + for ( let i = 1; i <= points.length; i ++ ) { + + const currentIndex = i % points.length; + const currentPos = points[ currentIndex ]; + const dx = currentPos.x - prevPos.x; + const dy = currentPos.y - prevPos.y; + const distSq = dx * dx + dy * dy; + + const scalingFactorSqrt = Math.max( + Math.abs( currentPos.x ), + Math.abs( currentPos.y ), + Math.abs( prevPos.x ), + Math.abs( prevPos.y ) + ); + const thresholdSqScaled = THRESHOLD_SQ * scalingFactorSqrt * scalingFactorSqrt; + if ( distSq <= thresholdSqScaled ) { + + points.splice( currentIndex, 1 ); + i --; + continue; + + } + + prevPos = currentPos; + + } + + } + + mergeOverlappingPoints( vertices ); + holes.forEach( mergeOverlappingPoints ); + + const numHoles = holes.length; + + /* Vertices */ + + const contour = vertices; // vertices has all points but contour has only points of circumference + + for ( let h = 0; h < numHoles; h ++ ) { + + const ahole = holes[ h ]; + + vertices = vertices.concat( ahole ); + + } + + + function scalePt2( pt, vec, size ) { + + if ( ! vec ) error( 'ExtrudeGeometry: vec does not exist' ); + + return pt.clone().addScaledVector( vec, size ); + + } + + const vlen = vertices.length; + + + // Find directions for point movement + + + function getBevelVec( inPt, inPrev, inNext ) { + + // computes for inPt the corresponding point inPt' on a new contour + // shifted by 1 unit (length of normalized vector) to the left + // if we walk along contour clockwise, this new contour is outside the old one + // + // inPt' is the intersection of the two lines parallel to the two + // adjacent edges of inPt at a distance of 1 unit on the left side. + + let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt + + // good reading for geometry algorithms (here: line-line intersection) + // http://geomalgorithms.com/a05-_intersect-1.html + + const v_prev_x = inPt.x - inPrev.x, + v_prev_y = inPt.y - inPrev.y; + const v_next_x = inNext.x - inPt.x, + v_next_y = inNext.y - inPt.y; + + const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y ); + + // check for collinear edges + const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x ); + + if ( Math.abs( collinear0 ) > Number.EPSILON ) { + + // not collinear + + // length of vectors for normalizing + + const v_prev_len = Math.sqrt( v_prev_lensq ); + const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y ); + + // shift adjacent points by unit vectors to the left + + const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len ); + const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len ); + + const ptNextShift_x = ( inNext.x - v_next_y / v_next_len ); + const ptNextShift_y = ( inNext.y + v_next_x / v_next_len ); + + // scaling factor for v_prev to intersection point + + const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y - + ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) / + ( v_prev_x * v_next_y - v_prev_y * v_next_x ); + + // vector from inPt to intersection point + + v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x ); + v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y ); + + // Don't normalize!, otherwise sharp corners become ugly + // but prevent crazy spikes + const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y ); + if ( v_trans_lensq <= 2 ) { + + return new Vector2( v_trans_x, v_trans_y ); + + } else { + + shrink_by = Math.sqrt( v_trans_lensq / 2 ); + + } + + } else { + + // handle special case of collinear edges + + let direction_eq = false; // assumes: opposite + + if ( v_prev_x > Number.EPSILON ) { + + if ( v_next_x > Number.EPSILON ) { + + direction_eq = true; + + } + + } else { + + if ( v_prev_x < - Number.EPSILON ) { + + if ( v_next_x < - Number.EPSILON ) { + + direction_eq = true; + + } + + } else { + + if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) { + + direction_eq = true; + + } + + } + + } + + if ( direction_eq ) { + + // log("Warning: lines are a straight sequence"); + v_trans_x = - v_prev_y; + v_trans_y = v_prev_x; + shrink_by = Math.sqrt( v_prev_lensq ); + + } else { + + // log("Warning: lines are a straight spike"); + v_trans_x = v_prev_x; + v_trans_y = v_prev_y; + shrink_by = Math.sqrt( v_prev_lensq / 2 ); + + } + + } + + return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by ); + + } + + + const contourMovements = []; + + for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) { + + if ( j === il ) j = 0; + if ( k === il ) k = 0; + + // (j)---(i)---(k) + // log('i,j,k', i, j , k) + + contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] ); + + } + + const holesMovements = []; + let oneHoleMovements, verticesMovements = contourMovements.concat(); + + for ( let h = 0, hl = numHoles; h < hl; h ++ ) { + + const ahole = holes[ h ]; + + oneHoleMovements = []; + + for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) { + + if ( j === il ) j = 0; + if ( k === il ) k = 0; + + // (j)---(i)---(k) + oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] ); + + } + + holesMovements.push( oneHoleMovements ); + verticesMovements = verticesMovements.concat( oneHoleMovements ); + + } + + let faces; + + if ( bevelSegments === 0 ) { + + faces = ShapeUtils.triangulateShape( contour, holes ); + + } else { + + const contractedContourVertices = []; + const expandedHoleVertices = []; + + // Loop bevelSegments, 1 for the front, 1 for the back + + for ( let b = 0; b < bevelSegments; b ++ ) { + + //for ( b = bevelSegments; b > 0; b -- ) { + + const t = b / bevelSegments; + const z = bevelThickness * Math.cos( t * Math.PI / 2 ); + const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset; + + // contract shape + + for ( let i = 0, il = contour.length; i < il; i ++ ) { + + const vert = scalePt2( contour[ i ], contourMovements[ i ], bs ); + + v( vert.x, vert.y, - z ); + if ( t === 0 ) contractedContourVertices.push( vert ); + + } + + // expand holes + + for ( let h = 0, hl = numHoles; h < hl; h ++ ) { + + const ahole = holes[ h ]; + oneHoleMovements = holesMovements[ h ]; + const oneHoleVertices = []; + for ( let i = 0, il = ahole.length; i < il; i ++ ) { + + const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs ); + + v( vert.x, vert.y, - z ); + if ( t === 0 ) oneHoleVertices.push( vert ); + + } + + if ( t === 0 ) expandedHoleVertices.push( oneHoleVertices ); + + } + + } + + faces = ShapeUtils.triangulateShape( contractedContourVertices, expandedHoleVertices ); + + } + + const flen = faces.length; + + const bs = bevelSize + bevelOffset; + + // Back facing vertices + + for ( let i = 0; i < vlen; i ++ ) { + + const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ]; + + if ( ! extrudeByPath ) { + + v( vert.x, vert.y, 0 ); + + } else { + + // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x ); + + normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x ); + binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y ); + + position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal ); + + v( position2.x, position2.y, position2.z ); + + } + + } + + // Add stepped vertices... + // Including front facing vertices + + for ( let s = 1; s <= steps; s ++ ) { + + for ( let i = 0; i < vlen; i ++ ) { + + const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ]; + + if ( ! extrudeByPath ) { + + v( vert.x, vert.y, depth / steps * s ); + + } else { + + // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x ); + + normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x ); + binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y ); + + position2.copy( extrudePts[ s ] ).add( normal ).add( binormal ); + + v( position2.x, position2.y, position2.z ); + + } + + } + + } + + + // Add bevel segments planes + + //for ( b = 1; b <= bevelSegments; b ++ ) { + for ( let b = bevelSegments - 1; b >= 0; b -- ) { + + const t = b / bevelSegments; + const z = bevelThickness * Math.cos( t * Math.PI / 2 ); + const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset; + + // contract shape + + for ( let i = 0, il = contour.length; i < il; i ++ ) { + + const vert = scalePt2( contour[ i ], contourMovements[ i ], bs ); + v( vert.x, vert.y, depth + z ); + + } + + // expand holes + + for ( let h = 0, hl = holes.length; h < hl; h ++ ) { + + const ahole = holes[ h ]; + oneHoleMovements = holesMovements[ h ]; + + for ( let i = 0, il = ahole.length; i < il; i ++ ) { + + const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs ); + + if ( ! extrudeByPath ) { + + v( vert.x, vert.y, depth + z ); + + } else { + + v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z ); + + } + + } + + } + + } + + /* Faces */ + + // Top and bottom faces + + buildLidFaces(); + + // Sides faces + + buildSideFaces(); + + + ///// Internal functions + + function buildLidFaces() { + + const start = verticesArray.length / 3; + + if ( bevelEnabled ) { + + let layer = 0; // steps + 1 + let offset = vlen * layer; + + // Bottom faces + + for ( let i = 0; i < flen; i ++ ) { + + const face = faces[ i ]; + f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset ); + + } + + layer = steps + bevelSegments * 2; + offset = vlen * layer; + + // Top faces + + for ( let i = 0; i < flen; i ++ ) { + + const face = faces[ i ]; + f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset ); + + } + + } else { + + // Bottom faces + + for ( let i = 0; i < flen; i ++ ) { + + const face = faces[ i ]; + f3( face[ 2 ], face[ 1 ], face[ 0 ] ); + + } + + // Top faces + + for ( let i = 0; i < flen; i ++ ) { + + const face = faces[ i ]; + f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps ); + + } + + } + + scope.addGroup( start, verticesArray.length / 3 - start, 0 ); + + } + + // Create faces for the z-sides of the shape + + function buildSideFaces() { + + const start = verticesArray.length / 3; + let layeroffset = 0; + sidewalls( contour, layeroffset ); + layeroffset += contour.length; + + for ( let h = 0, hl = holes.length; h < hl; h ++ ) { + + const ahole = holes[ h ]; + sidewalls( ahole, layeroffset ); + + //, true + layeroffset += ahole.length; + + } + + + scope.addGroup( start, verticesArray.length / 3 - start, 1 ); + + + } + + function sidewalls( contour, layeroffset ) { + + let i = contour.length; + + while ( -- i >= 0 ) { + + const j = i; + let k = i - 1; + if ( k < 0 ) k = contour.length - 1; + + //log('b', i,j, i-1, k,vertices.length); + + for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) { + + const slen1 = vlen * s; + const slen2 = vlen * ( s + 1 ); + + const a = layeroffset + j + slen1, + b = layeroffset + k + slen1, + c = layeroffset + k + slen2, + d = layeroffset + j + slen2; + + f4( a, b, c, d ); + + } + + } + + } + + function v( x, y, z ) { + + placeholder.push( x ); + placeholder.push( y ); + placeholder.push( z ); + + } + + + function f3( a, b, c ) { + + addVertex( a ); + addVertex( b ); + addVertex( c ); + + const nextIndex = verticesArray.length / 3; + const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 ); + + addUV( uvs[ 0 ] ); + addUV( uvs[ 1 ] ); + addUV( uvs[ 2 ] ); + + } + + function f4( a, b, c, d ) { + + addVertex( a ); + addVertex( b ); + addVertex( d ); + + addVertex( b ); + addVertex( c ); + addVertex( d ); + + + const nextIndex = verticesArray.length / 3; + const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 ); + + addUV( uvs[ 0 ] ); + addUV( uvs[ 1 ] ); + addUV( uvs[ 3 ] ); + + addUV( uvs[ 1 ] ); + addUV( uvs[ 2 ] ); + addUV( uvs[ 3 ] ); + + } + + function addVertex( index ) { + + verticesArray.push( placeholder[ index * 3 + 0 ] ); + verticesArray.push( placeholder[ index * 3 + 1 ] ); + verticesArray.push( placeholder[ index * 3 + 2 ] ); + + } + + + function addUV( vector2 ) { + + uvArray.push( vector2.x ); + uvArray.push( vector2.y ); + + } + + } + + } + + copy( source ) { + + super.copy( source ); + + this.parameters = Object.assign( {}, source.parameters ); + + return this; + + } + + toJSON() { + + const data = super.toJSON(); + + const shapes = this.parameters.shapes; + const options = this.parameters.options; + + return toJSON$1( shapes, options, data ); + + } + + /** + * Factory method for creating an instance of this class from the given + * JSON object. + * + * @param {Object} data - A JSON object representing the serialized geometry. + * @param {Array} shapes - An array of shapes. + * @return {ExtrudeGeometry} A new instance. + */ + static fromJSON( data, shapes ) { + + const geometryShapes = []; + + for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) { + + const shape = shapes[ data.shapes[ j ] ]; + + geometryShapes.push( shape ); + + } + + const extrudePath = data.options.extrudePath; + + if ( extrudePath !== undefined ) { + + data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath ); + + } + + return new ExtrudeGeometry( geometryShapes, data.options ); + + } + +} + +const WorldUVGenerator = { + + generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) { + + const a_x = vertices[ indexA * 3 ]; + const a_y = vertices[ indexA * 3 + 1 ]; + const b_x = vertices[ indexB * 3 ]; + const b_y = vertices[ indexB * 3 + 1 ]; + const c_x = vertices[ indexC * 3 ]; + const c_y = vertices[ indexC * 3 + 1 ]; + + return [ + new Vector2( a_x, a_y ), + new Vector2( b_x, b_y ), + new Vector2( c_x, c_y ) + ]; + + }, + + generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) { + + const a_x = vertices[ indexA * 3 ]; + const a_y = vertices[ indexA * 3 + 1 ]; + const a_z = vertices[ indexA * 3 + 2 ]; + const b_x = vertices[ indexB * 3 ]; + const b_y = vertices[ indexB * 3 + 1 ]; + const b_z = vertices[ indexB * 3 + 2 ]; + const c_x = vertices[ indexC * 3 ]; + const c_y = vertices[ indexC * 3 + 1 ]; + const c_z = vertices[ indexC * 3 + 2 ]; + const d_x = vertices[ indexD * 3 ]; + const d_y = vertices[ indexD * 3 + 1 ]; + const d_z = vertices[ indexD * 3 + 2 ]; + + if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) { + + return [ + new Vector2( a_x, 1 - a_z ), + new Vector2( b_x, 1 - b_z ), + new Vector2( c_x, 1 - c_z ), + new Vector2( d_x, 1 - d_z ) + ]; + + } else { + + return [ + new Vector2( a_y, 1 - a_z ), + new Vector2( b_y, 1 - b_z ), + new Vector2( c_y, 1 - c_z ), + new Vector2( d_y, 1 - d_z ) + ]; + + } + + } + +}; + +function toJSON$1( shapes, options, data ) { + + data.shapes = []; + + if ( Array.isArray( shapes ) ) { + + for ( let i = 0, l = shapes.length; i < l; i ++ ) { + + const shape = shapes[ i ]; + + data.shapes.push( shape.uuid ); + + } + + } else { + + data.shapes.push( shapes.uuid ); + + } + + data.options = Object.assign( {}, options ); + + if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON(); + + return data; + +} + +/** + * A geometry class for representing an icosahedron. + * + * ```js + * const geometry = new THREE.IcosahedronGeometry(); + * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } ); + * const icosahedron = new THREE.Mesh( geometry, material ); + * scene.add( icosahedron ); + * ``` + * + * @augments PolyhedronGeometry + * @demo scenes/geometry-browser.html#IcosahedronGeometry + */ +class IcosahedronGeometry extends PolyhedronGeometry { + + /** + * Constructs a new icosahedron geometry. + * + * @param {number} [radius=1] - Radius of the icosahedron. + * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a icosahedron. + */ + constructor( radius = 1, detail = 0 ) { + + const t = ( 1 + Math.sqrt( 5 ) ) / 2; + + const vertices = [ + -1, t, 0, 1, t, 0, -1, - t, 0, 1, - t, 0, + 0, -1, t, 0, 1, t, 0, -1, - t, 0, 1, - t, + t, 0, -1, t, 0, 1, - t, 0, -1, - t, 0, 1 + ]; + + const indices = [ + 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11, + 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8, + 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9, + 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1 + ]; + + super( vertices, indices, radius, detail ); + + this.type = 'IcosahedronGeometry'; + + /** + * Holds the constructor parameters that have been + * used to generate the geometry. Any modification + * after instantiation does not change the geometry. + * + * @type {Object} + */ + this.parameters = { + radius: radius, + detail: detail + }; + + } + + /** + * Factory method for creating an instance of this class from the given + * JSON object. + * + * @param {Object} data - A JSON object representing the serialized geometry. + * @return {IcosahedronGeometry} A new instance. + */ + static fromJSON( data ) { + + return new IcosahedronGeometry( data.radius, data.detail ); + + } + +} + +/** + * Creates meshes with axial symmetry like vases. The lathe rotates around the Y axis. + * + * ```js + * const points = []; + * for ( let i = 0; i < 10; i ++ ) { + * points.push( new THREE.Vector2( Math.sin( i * 0.2 ) * 10 + 5, ( i - 5 ) * 2 ) ); + * } + * const geometry = new THREE.LatheGeometry( points ); + * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } ); + * const lathe = new THREE.Mesh( geometry, material ); + * scene.add( lathe ); + * ``` + * + * @augments BufferGeometry + * @demo scenes/geometry-browser.html#LatheGeometry + */ +class LatheGeometry extends BufferGeometry { + + /** + * Constructs a new lathe geometry. + * + * @param {Array} [points] - An array of points in 2D space. The x-coordinate of each point + * must be greater than zero. + * @param {number} [segments=12] - The number of circumference segments to generate. + * @param {number} [phiStart=0] - The starting angle in radians. + * @param {number} [phiLength=Math.PI*2] - The radian (0 to 2PI) range of the lathed section 2PI is a + * closed lathe, less than 2PI is a portion. + */ + constructor( points = [ new Vector2( 0, -0.5 ), new Vector2( 0.5, 0 ), new Vector2( 0, 0.5 ) ], segments = 12, phiStart = 0, phiLength = Math.PI * 2 ) { + + super(); + + this.type = 'LatheGeometry'; + + /** + * Holds the constructor parameters that have been + * used to generate the geometry. Any modification + * after instantiation does not change the geometry. + * + * @type {Object} + */ + this.parameters = { + points: points, + segments: segments, + phiStart: phiStart, + phiLength: phiLength + }; + + segments = Math.floor( segments ); + + // clamp phiLength so it's in range of [ 0, 2PI ] + + phiLength = clamp( phiLength, 0, Math.PI * 2 ); + + // buffers + + const indices = []; + const vertices = []; + const uvs = []; + const initNormals = []; + const normals = []; + + // helper variables + + const inverseSegments = 1.0 / segments; + const vertex = new Vector3(); + const uv = new Vector2(); + const normal = new Vector3(); + const curNormal = new Vector3(); + const prevNormal = new Vector3(); + let dx = 0; + let dy = 0; + + // pre-compute normals for initial "meridian" + + for ( let j = 0; j <= ( points.length - 1 ); j ++ ) { + + switch ( j ) { + + case 0: // special handling for 1st vertex on path + + dx = points[ j + 1 ].x - points[ j ].x; + dy = points[ j + 1 ].y - points[ j ].y; + + normal.x = dy * 1.0; + normal.y = - dx; + normal.z = dy * 0.0; + + prevNormal.copy( normal ); + + normal.normalize(); + + initNormals.push( normal.x, normal.y, normal.z ); + + break; + + case ( points.length - 1 ): // special handling for last Vertex on path + + initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z ); + + break; + + default: // default handling for all vertices in between + + dx = points[ j + 1 ].x - points[ j ].x; + dy = points[ j + 1 ].y - points[ j ].y; + + normal.x = dy * 1.0; + normal.y = - dx; + normal.z = dy * 0.0; + + curNormal.copy( normal ); + + normal.x += prevNormal.x; + normal.y += prevNormal.y; + normal.z += prevNormal.z; + + normal.normalize(); + + initNormals.push( normal.x, normal.y, normal.z ); + + prevNormal.copy( curNormal ); + + } + + } + + // generate vertices, uvs and normals + + for ( let i = 0; i <= segments; i ++ ) { + + const phi = phiStart + i * inverseSegments * phiLength; + + const sin = Math.sin( phi ); + const cos = Math.cos( phi ); + + for ( let j = 0; j <= ( points.length - 1 ); j ++ ) { + + // vertex + + vertex.x = points[ j ].x * sin; + vertex.y = points[ j ].y; + vertex.z = points[ j ].x * cos; + + vertices.push( vertex.x, vertex.y, vertex.z ); + + // uv + + uv.x = i / segments; + uv.y = j / ( points.length - 1 ); + + uvs.push( uv.x, uv.y ); + + // normal + + const x = initNormals[ 3 * j + 0 ] * sin; + const y = initNormals[ 3 * j + 1 ]; + const z = initNormals[ 3 * j + 0 ] * cos; + + normals.push( x, y, z ); + + } + + } + + // indices + + for ( let i = 0; i < segments; i ++ ) { + + for ( let j = 0; j < ( points.length - 1 ); j ++ ) { + + const base = j + i * points.length; + + const a = base; + const b = base + points.length; + const c = base + points.length + 1; + const d = base + 1; + + // faces + + indices.push( a, b, d ); + indices.push( c, d, b ); + + } + + } + + // build geometry + + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + + } + + copy( source ) { + + super.copy( source ); + + this.parameters = Object.assign( {}, source.parameters ); + + return this; + + } + + /** + * Factory method for creating an instance of this class from the given + * JSON object. + * + * @param {Object} data - A JSON object representing the serialized geometry. + * @return {LatheGeometry} A new instance. + */ + static fromJSON( data ) { + + return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength ); + + } + +} + +/** + * A geometry class for representing an octahedron. + * + * ```js + * const geometry = new THREE.OctahedronGeometry(); + * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } ); + * const octahedron = new THREE.Mesh( geometry, material ); + * scene.add( octahedron ); + * ``` + * + * @augments PolyhedronGeometry + * @demo scenes/geometry-browser.html#OctahedronGeometry + */ +class OctahedronGeometry extends PolyhedronGeometry { + + /** + * Constructs a new octahedron geometry. + * + * @param {number} [radius=1] - Radius of the octahedron. + * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a octahedron. + */ + constructor( radius = 1, detail = 0 ) { + + const vertices = [ + 1, 0, 0, -1, 0, 0, 0, 1, 0, + 0, -1, 0, 0, 0, 1, 0, 0, -1 + ]; + + const indices = [ + 0, 2, 4, 0, 4, 3, 0, 3, 5, + 0, 5, 2, 1, 2, 5, 1, 5, 3, + 1, 3, 4, 1, 4, 2 + ]; + + super( vertices, indices, radius, detail ); + + this.type = 'OctahedronGeometry'; + + /** + * Holds the constructor parameters that have been + * used to generate the geometry. Any modification + * after instantiation does not change the geometry. + * + * @type {Object} + */ + this.parameters = { + radius: radius, + detail: detail + }; + + } + + /** + * Factory method for creating an instance of this class from the given + * JSON object. + * + * @param {Object} data - A JSON object representing the serialized geometry. + * @return {OctahedronGeometry} A new instance. + */ + static fromJSON( data ) { + + return new OctahedronGeometry( data.radius, data.detail ); + + } + +} + +/** + * A geometry class for representing a plane. + * + * ```js + * const geometry = new THREE.PlaneGeometry( 1, 1 ); + * const material = new THREE.MeshBasicMaterial( { color: 0xffff00, side: THREE.DoubleSide } ); + * const plane = new THREE.Mesh( geometry, material ); + * scene.add( plane ); + * ``` + * + * @augments BufferGeometry + * @demo scenes/geometry-browser.html#PlaneGeometry + */ +class PlaneGeometry extends BufferGeometry { + + /** + * Constructs a new plane geometry. + * + * @param {number} [width=1] - The width along the X axis. + * @param {number} [height=1] - The height along the Y axis + * @param {number} [widthSegments=1] - The number of segments along the X axis. + * @param {number} [heightSegments=1] - The number of segments along the Y axis. + */ + constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) { + + super(); + + this.type = 'PlaneGeometry'; + + /** + * Holds the constructor parameters that have been + * used to generate the geometry. Any modification + * after instantiation does not change the geometry. + * + * @type {Object} + */ + this.parameters = { + width: width, + height: height, + widthSegments: widthSegments, + heightSegments: heightSegments + }; + + const width_half = width / 2; + const height_half = height / 2; + + const gridX = Math.floor( widthSegments ); + const gridY = Math.floor( heightSegments ); + + const gridX1 = gridX + 1; + const gridY1 = gridY + 1; + + const segment_width = width / gridX; + const segment_height = height / gridY; + + // + + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + + for ( let iy = 0; iy < gridY1; iy ++ ) { + + const y = iy * segment_height - height_half; + + for ( let ix = 0; ix < gridX1; ix ++ ) { + + const x = ix * segment_width - width_half; + + vertices.push( x, - y, 0 ); + + normals.push( 0, 0, 1 ); + + uvs.push( ix / gridX ); + uvs.push( 1 - ( iy / gridY ) ); + + } + + } + + for ( let iy = 0; iy < gridY; iy ++ ) { + + for ( let ix = 0; ix < gridX; ix ++ ) { + + const a = ix + gridX1 * iy; + const b = ix + gridX1 * ( iy + 1 ); + const c = ( ix + 1 ) + gridX1 * ( iy + 1 ); + const d = ( ix + 1 ) + gridX1 * iy; + + indices.push( a, b, d ); + indices.push( b, c, d ); + + } + + } + + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + + } + + copy( source ) { + + super.copy( source ); + + this.parameters = Object.assign( {}, source.parameters ); + + return this; + + } + + /** + * Factory method for creating an instance of this class from the given + * JSON object. + * + * @param {Object} data - A JSON object representing the serialized geometry. + * @return {PlaneGeometry} A new instance. + */ + static fromJSON( data ) { + + return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments ); + + } + +} + +/** + * A class for generating a two-dimensional ring geometry. + * + * ```js + * const geometry = new THREE.RingGeometry( 1, 5, 32 ); + * const material = new THREE.MeshBasicMaterial( { color: 0xffff00, side: THREE.DoubleSide } ); + * const mesh = new THREE.Mesh( geometry, material ); + * scene.add( mesh ); + * ``` + * + * @augments BufferGeometry + * @demo scenes/geometry-browser.html#RingGeometry + */ +class RingGeometry extends BufferGeometry { + + /** + * Constructs a new ring geometry. + * + * @param {number} [innerRadius=0.5] - The inner radius of the ring. + * @param {number} [outerRadius=1] - The outer radius of the ring. + * @param {number} [thetaSegments=32] - Number of segments. A higher number means the ring will be more round. Minimum is `3`. + * @param {number} [phiSegments=1] - Number of segments per ring segment. Minimum is `1`. + * @param {number} [thetaStart=0] - Starting angle in radians. + * @param {number} [thetaLength=Math.PI*2] - Central angle in radians. + */ + constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) { + + super(); + + this.type = 'RingGeometry'; + + /** + * Holds the constructor parameters that have been + * used to generate the geometry. Any modification + * after instantiation does not change the geometry. + * + * @type {Object} + */ + this.parameters = { + innerRadius: innerRadius, + outerRadius: outerRadius, + thetaSegments: thetaSegments, + phiSegments: phiSegments, + thetaStart: thetaStart, + thetaLength: thetaLength + }; + + thetaSegments = Math.max( 3, thetaSegments ); + phiSegments = Math.max( 1, phiSegments ); + + // buffers + + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + + // some helper variables + + let radius = innerRadius; + const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments ); + const vertex = new Vector3(); + const uv = new Vector2(); + + // generate vertices, normals and uvs + + for ( let j = 0; j <= phiSegments; j ++ ) { + + for ( let i = 0; i <= thetaSegments; i ++ ) { + + // values are generate from the inside of the ring to the outside + + const segment = thetaStart + i / thetaSegments * thetaLength; + + // vertex + + vertex.x = radius * Math.cos( segment ); + vertex.y = radius * Math.sin( segment ); + + vertices.push( vertex.x, vertex.y, vertex.z ); + + // normal + + normals.push( 0, 0, 1 ); + + // uv + + uv.x = ( vertex.x / outerRadius + 1 ) / 2; + uv.y = ( vertex.y / outerRadius + 1 ) / 2; + + uvs.push( uv.x, uv.y ); + + } + + // increase the radius for next row of vertices + + radius += radiusStep; + + } + + // indices + + for ( let j = 0; j < phiSegments; j ++ ) { + + const thetaSegmentLevel = j * ( thetaSegments + 1 ); + + for ( let i = 0; i < thetaSegments; i ++ ) { + + const segment = i + thetaSegmentLevel; + + const a = segment; + const b = segment + thetaSegments + 1; + const c = segment + thetaSegments + 2; + const d = segment + 1; + + // faces + + indices.push( a, b, d ); + indices.push( b, c, d ); + + } + + } + + // build geometry + + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + + } + + copy( source ) { + + super.copy( source ); + + this.parameters = Object.assign( {}, source.parameters ); + + return this; + + } + + /** + * Factory method for creating an instance of this class from the given + * JSON object. + * + * @param {Object} data - A JSON object representing the serialized geometry. + * @return {RingGeometry} A new instance. + */ + static fromJSON( data ) { + + return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength ); + + } + +} + +/** + * Creates an one-sided polygonal geometry from one or more path shapes. + * + * ```js + * const arcShape = new THREE.Shape() + * .moveTo( 5, 1 ) + * .absarc( 1, 1, 4, 0, Math.PI * 2, false ); + * + * const geometry = new THREE.ShapeGeometry( arcShape ); + * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00, side: THREE.DoubleSide } ); + * const mesh = new THREE.Mesh( geometry, material ) ; + * scene.add( mesh ); + * ``` + * + * @augments BufferGeometry + * @demo scenes/geometry-browser.html#ShapeGeometry + */ +class ShapeGeometry extends BufferGeometry { + + /** + * Constructs a new shape geometry. + * + * @param {Shape|Array} [shapes] - A shape or an array of shapes. + * @param {number} [curveSegments=12] - Number of segments per shape. + */ + constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( -0.5, -0.5 ), new Vector2( 0.5, -0.5 ) ] ), curveSegments = 12 ) { + + super(); + + this.type = 'ShapeGeometry'; + + /** + * Holds the constructor parameters that have been + * used to generate the geometry. Any modification + * after instantiation does not change the geometry. + * + * @type {Object} + */ + this.parameters = { + shapes: shapes, + curveSegments: curveSegments + }; + + // buffers + + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + + // helper variables + + let groupStart = 0; + let groupCount = 0; + + // allow single and array values for "shapes" parameter + + if ( Array.isArray( shapes ) === false ) { + + addShape( shapes ); + + } else { + + for ( let i = 0; i < shapes.length; i ++ ) { + + addShape( shapes[ i ] ); + + this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support + + groupStart += groupCount; + groupCount = 0; + + } + + } + + // build geometry + + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + + + // helper functions + + function addShape( shape ) { + + const indexOffset = vertices.length / 3; + const points = shape.extractPoints( curveSegments ); + + let shapeVertices = points.shape; + const shapeHoles = points.holes; + + // check direction of vertices + + if ( ShapeUtils.isClockWise( shapeVertices ) === false ) { + + shapeVertices = shapeVertices.reverse(); + + } + + for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) { + + const shapeHole = shapeHoles[ i ]; + + if ( ShapeUtils.isClockWise( shapeHole ) === true ) { + + shapeHoles[ i ] = shapeHole.reverse(); + + } + + } + + const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles ); + + // join vertices of inner and outer paths to a single array + + for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) { + + const shapeHole = shapeHoles[ i ]; + shapeVertices = shapeVertices.concat( shapeHole ); + + } + + // vertices, normals, uvs + + for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) { + + const vertex = shapeVertices[ i ]; + + vertices.push( vertex.x, vertex.y, 0 ); + normals.push( 0, 0, 1 ); + uvs.push( vertex.x, vertex.y ); // world uvs + + } + + // indices + + for ( let i = 0, l = faces.length; i < l; i ++ ) { + + const face = faces[ i ]; + + const a = face[ 0 ] + indexOffset; + const b = face[ 1 ] + indexOffset; + const c = face[ 2 ] + indexOffset; + + indices.push( a, b, c ); + groupCount += 3; + + } + + } + + } + + copy( source ) { + + super.copy( source ); + + this.parameters = Object.assign( {}, source.parameters ); + + return this; + + } + + toJSON() { + + const data = super.toJSON(); + + const shapes = this.parameters.shapes; + + return toJSON( shapes, data ); + + } + + /** + * Factory method for creating an instance of this class from the given + * JSON object. + * + * @param {Object} data - A JSON object representing the serialized geometry. + * @param {Array} shapes - An array of shapes. + * @return {ShapeGeometry} A new instance. + */ + static fromJSON( data, shapes ) { + + const geometryShapes = []; + + for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) { + + const shape = shapes[ data.shapes[ j ] ]; + + geometryShapes.push( shape ); + + } + + return new ShapeGeometry( geometryShapes, data.curveSegments ); + + } + +} + +function toJSON( shapes, data ) { + + data.shapes = []; + + if ( Array.isArray( shapes ) ) { + + for ( let i = 0, l = shapes.length; i < l; i ++ ) { + + const shape = shapes[ i ]; + + data.shapes.push( shape.uuid ); + + } + + } else { + + data.shapes.push( shapes.uuid ); + + } + + return data; + +} + +/** + * A class for generating a sphere geometry. + * + * ```js + * const geometry = new THREE.SphereGeometry( 15, 32, 16 ); + * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } ); + * const sphere = new THREE.Mesh( geometry, material ); + * scene.add( sphere ); + * ``` + * + * @augments BufferGeometry + * @demo scenes/geometry-browser.html#SphereGeometry + */ +class SphereGeometry extends BufferGeometry { + + /** + * Constructs a new sphere geometry. + * + * @param {number} [radius=1] - The sphere radius. + * @param {number} [widthSegments=32] - The number of horizontal segments. Minimum value is `3`. + * @param {number} [heightSegments=16] - The number of vertical segments. Minimum value is `2`. + * @param {number} [phiStart=0] - The horizontal starting angle in radians. + * @param {number} [phiLength=Math.PI*2] - The horizontal sweep angle size. + * @param {number} [thetaStart=0] - The vertical starting angle in radians. + * @param {number} [thetaLength=Math.PI] - The vertical sweep angle size. + */ + constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) { + + super(); + + this.type = 'SphereGeometry'; + + /** + * Holds the constructor parameters that have been + * used to generate the geometry. Any modification + * after instantiation does not change the geometry. + * + * @type {Object} + */ + this.parameters = { + radius: radius, + widthSegments: widthSegments, + heightSegments: heightSegments, + phiStart: phiStart, + phiLength: phiLength, + thetaStart: thetaStart, + thetaLength: thetaLength + }; + + widthSegments = Math.max( 3, Math.floor( widthSegments ) ); + heightSegments = Math.max( 2, Math.floor( heightSegments ) ); + + const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI ); + + let index = 0; + const grid = []; + + const vertex = new Vector3(); + const normal = new Vector3(); + + // buffers + + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + + // generate vertices, normals and uvs + + for ( let iy = 0; iy <= heightSegments; iy ++ ) { + + const verticesRow = []; + + const v = iy / heightSegments; + const theta = thetaStart + v * thetaLength; + + const y = radius * Math.cos( theta ); + const ringRadius = Math.sqrt( radius * radius - y * y ); + + // special case for the poles + + let uOffset = 0; + + if ( iy === 0 && thetaStart === 0 ) { + + uOffset = 0.5 / widthSegments; + + } else if ( iy === heightSegments && thetaEnd === Math.PI ) { + + uOffset = -0.5 / widthSegments; + + } + + for ( let ix = 0; ix <= widthSegments; ix ++ ) { + + const u = ix / widthSegments; + const phi = phiStart + u * phiLength; + + // vertex + + vertex.x = - ringRadius * Math.cos( phi ); + vertex.y = y; + vertex.z = ringRadius * Math.sin( phi ); + + vertices.push( vertex.x, vertex.y, vertex.z ); + + // normal + + normal.copy( vertex ).normalize(); + normals.push( normal.x, normal.y, normal.z ); + + // uv + + uvs.push( u + uOffset, 1 - v ); + + verticesRow.push( index ++ ); + + } + + grid.push( verticesRow ); + + } + + // indices + + for ( let iy = 0; iy < heightSegments; iy ++ ) { + + for ( let ix = 0; ix < widthSegments; ix ++ ) { + + const a = grid[ iy ][ ix + 1 ]; + const b = grid[ iy ][ ix ]; + const c = grid[ iy + 1 ][ ix ]; + const d = grid[ iy + 1 ][ ix + 1 ]; + + if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d ); + if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d ); + + } + + } + + // build geometry + + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + + } + + copy( source ) { + + super.copy( source ); + + this.parameters = Object.assign( {}, source.parameters ); + + return this; + + } + + /** + * Factory method for creating an instance of this class from the given + * JSON object. + * + * @param {Object} data - A JSON object representing the serialized geometry. + * @return {SphereGeometry} A new instance. + */ + static fromJSON( data ) { + + return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength ); + + } + +} + +/** + * A geometry class for representing an tetrahedron. + * + * ```js + * const geometry = new THREE.TetrahedronGeometry(); + * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } ); + * const tetrahedron = new THREE.Mesh( geometry, material ); + * scene.add( tetrahedron ); + * ``` + * + * @augments PolyhedronGeometry + * @demo scenes/geometry-browser.html#TetrahedronGeometry + */ +class TetrahedronGeometry extends PolyhedronGeometry { + + /** + * Constructs a new tetrahedron geometry. + * + * @param {number} [radius=1] - Radius of the tetrahedron. + * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a tetrahedron. + */ + constructor( radius = 1, detail = 0 ) { + + const vertices = [ + 1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1 + ]; + + const indices = [ + 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1 + ]; + + super( vertices, indices, radius, detail ); + + this.type = 'TetrahedronGeometry'; + + /** + * Holds the constructor parameters that have been + * used to generate the geometry. Any modification + * after instantiation does not change the geometry. + * + * @type {Object} + */ + this.parameters = { + radius: radius, + detail: detail + }; + + } + + /** + * Factory method for creating an instance of this class from the given + * JSON object. + * + * @param {Object} data - A JSON object representing the serialized geometry. + * @return {TetrahedronGeometry} A new instance. + */ + static fromJSON( data ) { + + return new TetrahedronGeometry( data.radius, data.detail ); + + } + +} + +/** + * A geometry class for representing an torus. + * + * ```js + * const geometry = new THREE.TorusGeometry( 10, 3, 16, 100 ); + * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } ); + * const torus = new THREE.Mesh( geometry, material ); + * scene.add( torus ); + * ``` + * + * @augments BufferGeometry + * @demo scenes/geometry-browser.html#TorusGeometry + */ +class TorusGeometry extends BufferGeometry { + + /** + * Constructs a new torus geometry. + * + * @param {number} [radius=1] - Radius of the torus, from the center of the torus to the center of the tube. + * @param {number} [tube=0.4] - Radius of the tube. Must be smaller than `radius`. + * @param {number} [radialSegments=12] - The number of radial segments. + * @param {number} [tubularSegments=48] - The number of tubular segments. + * @param {number} [arc=Math.PI*2] - Central angle in radians. + * @param {number} [thetaStart=0] - Start of the tubular sweep in radians. + * @param {number} [thetaLength=Math.PI*2] - Length of the tubular sweep in radians. + */ + constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI * 2 ) { + + super(); + + this.type = 'TorusGeometry'; + + /** + * Holds the constructor parameters that have been + * used to generate the geometry. Any modification + * after instantiation does not change the geometry. + * + * @type {Object} + */ + this.parameters = { + radius: radius, + tube: tube, + radialSegments: radialSegments, + tubularSegments: tubularSegments, + arc: arc, + thetaStart: thetaStart, + thetaLength: thetaLength, + }; + + radialSegments = Math.floor( radialSegments ); + tubularSegments = Math.floor( tubularSegments ); + + // buffers + + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + + // helper variables + + const center = new Vector3(); + const vertex = new Vector3(); + const normal = new Vector3(); + + // generate vertices, normals and uvs + + for ( let j = 0; j <= radialSegments; j ++ ) { + + const v = thetaStart + ( j / radialSegments ) * thetaLength; + + for ( let i = 0; i <= tubularSegments; i ++ ) { + + const u = i / tubularSegments * arc; + + // vertex + + vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u ); + vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u ); + vertex.z = tube * Math.sin( v ); + + vertices.push( vertex.x, vertex.y, vertex.z ); + + // normal + + center.x = radius * Math.cos( u ); + center.y = radius * Math.sin( u ); + normal.subVectors( vertex, center ).normalize(); + + normals.push( normal.x, normal.y, normal.z ); + + // uv + + uvs.push( i / tubularSegments ); + uvs.push( j / radialSegments ); + + } + + } + + // generate indices + + for ( let j = 1; j <= radialSegments; j ++ ) { + + for ( let i = 1; i <= tubularSegments; i ++ ) { + + // indices + + const a = ( tubularSegments + 1 ) * j + i - 1; + const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1; + const c = ( tubularSegments + 1 ) * ( j - 1 ) + i; + const d = ( tubularSegments + 1 ) * j + i; + + // faces + + indices.push( a, b, d ); + indices.push( b, c, d ); + + } + + } + + // build geometry + + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + + } + + copy( source ) { + + super.copy( source ); + + this.parameters = Object.assign( {}, source.parameters ); + + return this; + + } + + /** + * Factory method for creating an instance of this class from the given + * JSON object. + * + * @param {Object} data - A JSON object representing the serialized geometry. + * @return {TorusGeometry} A new instance. + */ + static fromJSON( data ) { + + return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc, data.thetaStart, data.thetaLength ); + + } + +} + +/** + * Creates a torus knot, the particular shape of which is defined by a pair + * of coprime integers, p and q. If p and q are not coprime, the result will + * be a torus link. + * + * ```js + * const geometry = new THREE.TorusKnotGeometry( 10, 3, 100, 16 ); + * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } ); + * const torusKnot = new THREE.Mesh( geometry, material ); + * scene.add( torusKnot ); + * ``` + * + * @augments BufferGeometry + * @demo scenes/geometry-browser.html#TorusKnotGeometry + */ +class TorusKnotGeometry extends BufferGeometry { + + /** + * Constructs a new torus knot geometry. + * + * @param {number} [radius=1] - Radius of the torus knot. + * @param {number} [tube=0.4] - Radius of the tube. + * @param {number} [tubularSegments=64] - The number of tubular segments. + * @param {number} [radialSegments=8] - The number of radial segments. + * @param {number} [p=2] - This value determines, how many times the geometry winds around its axis of rotational symmetry. + * @param {number} [q=3] - This value determines, how many times the geometry winds around a circle in the interior of the torus. + */ + constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) { + + super(); + + this.type = 'TorusKnotGeometry'; + + /** + * Holds the constructor parameters that have been + * used to generate the geometry. Any modification + * after instantiation does not change the geometry. + * + * @type {Object} + */ + this.parameters = { + radius: radius, + tube: tube, + tubularSegments: tubularSegments, + radialSegments: radialSegments, + p: p, + q: q + }; + + tubularSegments = Math.floor( tubularSegments ); + radialSegments = Math.floor( radialSegments ); + + // buffers + + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + + // helper variables + + const vertex = new Vector3(); + const normal = new Vector3(); + + const P1 = new Vector3(); + const P2 = new Vector3(); + + const B = new Vector3(); + const T = new Vector3(); + const N = new Vector3(); + + // generate vertices, normals and uvs + + for ( let i = 0; i <= tubularSegments; ++ i ) { + + // the radian "u" is used to calculate the position on the torus curve of the current tubular segment + + const u = i / tubularSegments * p * Math.PI * 2; + + // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead. + // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions + + calculatePositionOnCurve( u, p, q, radius, P1 ); + calculatePositionOnCurve( u + 0.01, p, q, radius, P2 ); + + // calculate orthonormal basis + + T.subVectors( P2, P1 ); + N.addVectors( P2, P1 ); + B.crossVectors( T, N ); + N.crossVectors( B, T ); + + // normalize B, N. T can be ignored, we don't use it + + B.normalize(); + N.normalize(); + + for ( let j = 0; j <= radialSegments; ++ j ) { + + // now calculate the vertices. they are nothing more than an extrusion of the torus curve. + // because we extrude a shape in the xy-plane, there is no need to calculate a z-value. + + const v = j / radialSegments * Math.PI * 2; + const cx = - tube * Math.cos( v ); + const cy = tube * Math.sin( v ); + + // now calculate the final vertex position. + // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve + + vertex.x = P1.x + ( cx * N.x + cy * B.x ); + vertex.y = P1.y + ( cx * N.y + cy * B.y ); + vertex.z = P1.z + ( cx * N.z + cy * B.z ); + + vertices.push( vertex.x, vertex.y, vertex.z ); + + // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal) + + normal.subVectors( vertex, P1 ).normalize(); + + normals.push( normal.x, normal.y, normal.z ); + + // uv + + uvs.push( i / tubularSegments ); + uvs.push( j / radialSegments ); + + } + + } + + // generate indices + + for ( let j = 1; j <= tubularSegments; j ++ ) { + + for ( let i = 1; i <= radialSegments; i ++ ) { + + // indices + + const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 ); + const b = ( radialSegments + 1 ) * j + ( i - 1 ); + const c = ( radialSegments + 1 ) * j + i; + const d = ( radialSegments + 1 ) * ( j - 1 ) + i; + + // faces + + indices.push( a, b, d ); + indices.push( b, c, d ); + + } + + } + + // build geometry + + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + + // this function calculates the current position on the torus curve + + function calculatePositionOnCurve( u, p, q, radius, position ) { + + const cu = Math.cos( u ); + const su = Math.sin( u ); + const quOverP = q / p * u; + const cs = Math.cos( quOverP ); + + position.x = radius * ( 2 + cs ) * 0.5 * cu; + position.y = radius * ( 2 + cs ) * su * 0.5; + position.z = radius * Math.sin( quOverP ) * 0.5; + + } + + } + + copy( source ) { + + super.copy( source ); + + this.parameters = Object.assign( {}, source.parameters ); + + return this; + + } + + /** + * Factory method for creating an instance of this class from the given + * JSON object. + * + * @param {Object} data - A JSON object representing the serialized geometry. + * @return {TorusKnotGeometry} A new instance. + */ + static fromJSON( data ) { + + return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q ); + + } + +} + +/** + * Creates a tube that extrudes along a 3D curve. + * + * ```js + * class CustomSinCurve extends THREE.Curve { + * + * getPoint( t, optionalTarget = new THREE.Vector3() ) { + * + * const tx = t * 3 - 1.5; + * const ty = Math.sin( 2 * Math.PI * t ); + * const tz = 0; + * + * return optionalTarget.set( tx, ty, tz ); + * } + * + * } + * + * const path = new CustomSinCurve( 10 ); + * const geometry = new THREE.TubeGeometry( path, 20, 2, 8, false ); + * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } ); + * const mesh = new THREE.Mesh( geometry, material ); + * scene.add( mesh ); + * ``` + * + * @augments BufferGeometry + * @demo scenes/geometry-browser.html#TubeGeometry + */ +class TubeGeometry extends BufferGeometry { + + /** + * Constructs a new tube geometry. + * + * @param {Curve} [path=QuadraticBezierCurve3] - A 3D curve defining the path of the tube. + * @param {number} [tubularSegments=64] - The number of segments that make up the tube. + * @param {number} [radius=1] -The radius of the tube. + * @param {number} [radialSegments=8] - The number of segments that make up the cross-section. + * @param {boolean} [closed=false] - Whether the tube is closed or not. + */ + constructor( path = new QuadraticBezierCurve3( new Vector3( -1, -1, 0 ), new Vector3( -1, 1, 0 ), new Vector3( 1, 1, 0 ) ), tubularSegments = 64, radius = 1, radialSegments = 8, closed = false ) { + + super(); + + this.type = 'TubeGeometry'; + + /** + * Holds the constructor parameters that have been + * used to generate the geometry. Any modification + * after instantiation does not change the geometry. + * + * @type {Object} + */ + this.parameters = { + path: path, + tubularSegments: tubularSegments, + radius: radius, + radialSegments: radialSegments, + closed: closed + }; + + const frames = path.computeFrenetFrames( tubularSegments, closed ); + + // expose internals + + this.tangents = frames.tangents; + this.normals = frames.normals; + this.binormals = frames.binormals; + + // helper variables + + const vertex = new Vector3(); + const normal = new Vector3(); + const uv = new Vector2(); + let P = new Vector3(); + + // buffer + + const vertices = []; + const normals = []; + const uvs = []; + const indices = []; + + // create buffer data + + generateBufferData(); + + // build geometry + + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + + // functions + + function generateBufferData() { + + for ( let i = 0; i < tubularSegments; i ++ ) { + + generateSegment( i ); + + } + + // if the geometry is not closed, generate the last row of vertices and normals + // at the regular position on the given path + // + // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ) + + generateSegment( ( closed === false ) ? tubularSegments : 0 ); + + // uvs are generated in a separate function. + // this makes it easy compute correct values for closed geometries + + generateUVs(); + + // finally create faces + + generateIndices(); + + } + + function generateSegment( i ) { + + // we use getPointAt to sample evenly distributed points from the given path + + P = path.getPointAt( i / tubularSegments, P ); + + // retrieve corresponding normal and binormal + + const N = frames.normals[ i ]; + const B = frames.binormals[ i ]; + + // generate normals and vertices for the current segment + + for ( let j = 0; j <= radialSegments; j ++ ) { + + const v = j / radialSegments * Math.PI * 2; + + const sin = Math.sin( v ); + const cos = - Math.cos( v ); + + // normal + + normal.x = ( cos * N.x + sin * B.x ); + normal.y = ( cos * N.y + sin * B.y ); + normal.z = ( cos * N.z + sin * B.z ); + normal.normalize(); + + normals.push( normal.x, normal.y, normal.z ); + + // vertex + + vertex.x = P.x + radius * normal.x; + vertex.y = P.y + radius * normal.y; + vertex.z = P.z + radius * normal.z; + + vertices.push( vertex.x, vertex.y, vertex.z ); + + } + + } + + function generateIndices() { + + for ( let j = 1; j <= tubularSegments; j ++ ) { + + for ( let i = 1; i <= radialSegments; i ++ ) { + + const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 ); + const b = ( radialSegments + 1 ) * j + ( i - 1 ); + const c = ( radialSegments + 1 ) * j + i; + const d = ( radialSegments + 1 ) * ( j - 1 ) + i; + + // faces + + indices.push( a, b, d ); + indices.push( b, c, d ); + + } + + } + + } + + function generateUVs() { + + for ( let i = 0; i <= tubularSegments; i ++ ) { + + for ( let j = 0; j <= radialSegments; j ++ ) { + + uv.x = i / tubularSegments; + uv.y = j / radialSegments; + + uvs.push( uv.x, uv.y ); + + } + + } + + } + + } + + copy( source ) { + + super.copy( source ); + + this.parameters = Object.assign( {}, source.parameters ); + + return this; + + } + + toJSON() { + + const data = super.toJSON(); + + data.path = this.parameters.path.toJSON(); + + return data; + + } + + /** + * Factory method for creating an instance of this class from the given + * JSON object. + * + * @param {Object} data - A JSON object representing the serialized geometry. + * @return {TubeGeometry} A new instance. + */ + static fromJSON( data ) { + + // This only works for built-in curves (e.g. CatmullRomCurve3). + // User defined curves or instances of CurvePath will not be deserialized. + return new TubeGeometry( + new Curves[ data.path.type ]().fromJSON( data.path ), + data.tubularSegments, + data.radius, + data.radialSegments, + data.closed + ); + + } + +} + +/** + * Can be used as a helper object to visualize a geometry as a wireframe. + * + * ```js + * const geometry = new THREE.SphereGeometry(); + * + * const wireframe = new THREE.WireframeGeometry( geometry ); + * + * const line = new THREE.LineSegments( wireframe ); + * line.material.depthWrite = false; + * line.material.opacity = 0.25; + * line.material.transparent = true; + * + * scene.add( line ); + * ``` + * + * Note: It is not yet possible to serialize/deserialize instances of this class. + * + * @augments BufferGeometry + */ +class WireframeGeometry extends BufferGeometry { + + /** + * Constructs a new wireframe geometry. + * + * @param {?BufferGeometry} [geometry=null] - The geometry. + */ + constructor( geometry = null ) { + + super(); + + this.type = 'WireframeGeometry'; + + /** + * Holds the constructor parameters that have been + * used to generate the geometry. Any modification + * after instantiation does not change the geometry. + * + * @type {Object} + */ + this.parameters = { + geometry: geometry + }; + + if ( geometry !== null ) { + + // buffer + + const vertices = []; + const edges = new Set(); + + // helper variables + + const start = new Vector3(); + const end = new Vector3(); + + if ( geometry.index !== null ) { + + // indexed BufferGeometry + + const position = geometry.attributes.position; + const indices = geometry.index; + let groups = geometry.groups; + + if ( groups.length === 0 ) { + + groups = [ { start: 0, count: indices.count, materialIndex: 0 } ]; + + } + + // create a data structure that contains all edges without duplicates + + for ( let o = 0, ol = groups.length; o < ol; ++ o ) { + + const group = groups[ o ]; + + const groupStart = group.start; + const groupCount = group.count; + + for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) { + + for ( let j = 0; j < 3; j ++ ) { + + const index1 = indices.getX( i + j ); + const index2 = indices.getX( i + ( j + 1 ) % 3 ); + + start.fromBufferAttribute( position, index1 ); + end.fromBufferAttribute( position, index2 ); + + if ( isUniqueEdge( start, end, edges ) === true ) { + + vertices.push( start.x, start.y, start.z ); + vertices.push( end.x, end.y, end.z ); + + } + + } + + } + + } + + } else { + + // non-indexed BufferGeometry + + const position = geometry.attributes.position; + + for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) { + + for ( let j = 0; j < 3; j ++ ) { + + // three edges per triangle, an edge is represented as (index1, index2) + // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0) + + const index1 = 3 * i + j; + const index2 = 3 * i + ( ( j + 1 ) % 3 ); + + start.fromBufferAttribute( position, index1 ); + end.fromBufferAttribute( position, index2 ); + + if ( isUniqueEdge( start, end, edges ) === true ) { + + vertices.push( start.x, start.y, start.z ); + vertices.push( end.x, end.y, end.z ); + + } + + } + + } + + } + + // build geometry + + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + + } + + } + + copy( source ) { + + super.copy( source ); + + this.parameters = Object.assign( {}, source.parameters ); + + return this; + + } + +} + +function isUniqueEdge( start, end, edges ) { + + const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`; + const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge + + if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) { + + return false; + + } else { + + edges.add( hash1 ); + edges.add( hash2 ); + return true; + + } + +} + +var Geometries = /*#__PURE__*/Object.freeze({ + __proto__: null, + BoxGeometry: BoxGeometry, + CapsuleGeometry: CapsuleGeometry, + CircleGeometry: CircleGeometry, + ConeGeometry: ConeGeometry, + CylinderGeometry: CylinderGeometry, + DodecahedronGeometry: DodecahedronGeometry, + EdgesGeometry: EdgesGeometry, + ExtrudeGeometry: ExtrudeGeometry, + IcosahedronGeometry: IcosahedronGeometry, + LatheGeometry: LatheGeometry, + OctahedronGeometry: OctahedronGeometry, + PlaneGeometry: PlaneGeometry, + PolyhedronGeometry: PolyhedronGeometry, + RingGeometry: RingGeometry, + ShapeGeometry: ShapeGeometry, + SphereGeometry: SphereGeometry, + TetrahedronGeometry: TetrahedronGeometry, + TorusGeometry: TorusGeometry, + TorusKnotGeometry: TorusKnotGeometry, + TubeGeometry: TubeGeometry, + WireframeGeometry: WireframeGeometry +}); + +/** + * This material can receive shadows, but otherwise is completely transparent. + * + * ```js + * const geometry = new THREE.PlaneGeometry( 2000, 2000 ); + * geometry.rotateX( - Math.PI / 2 ); + * + * const material = new THREE.ShadowMaterial(); + * material.opacity = 0.2; + * + * const plane = new THREE.Mesh( geometry, material ); + * plane.position.y = -200; + * plane.receiveShadow = true; + * scene.add( plane ); + * ``` + * + * @augments Material + */ +class ShadowMaterial extends Material { + + /** + * Constructs a new shadow material. + * + * @param {Object} [parameters] - An object with one or more properties + * defining the material's appearance. Any property of the material + * (including any property from inherited materials) can be passed + * in here. Color values can be passed any type of value accepted + * by {@link Color#set}. + */ + constructor( parameters ) { + + super(); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isShadowMaterial = true; + + this.type = 'ShadowMaterial'; + + /** + * Color of the material. + * + * @type {Color} + * @default (0,0,0) + */ + this.color = new Color( 0x000000 ); + + /** + * Overwritten since shadow materials are transparent + * by default. + * + * @type {boolean} + * @default true + */ + this.transparent = true; + + /** + * Whether the material is affected by fog or not. + * + * @type {boolean} + * @default true + */ + this.fog = true; + + this.setValues( parameters ); + + } + + copy( source ) { + + super.copy( source ); + + this.color.copy( source.color ); + + this.fog = source.fog; + + return this; + + } + +} + +/** + * Provides utility functions for managing uniforms. + * + * @module UniformsUtils + */ + +/** + * Clones the given uniform definitions by performing a deep-copy. That means + * if the value of a uniform refers to an object like a Vector3 or Texture, + * the cloned uniform will refer to a new object reference. + * + * @param {Object} src - An object representing uniform definitions. + * @return {Object} The cloned uniforms. + */ +function cloneUniforms( src ) { + + const dst = {}; + + for ( const u in src ) { + + dst[ u ] = {}; + + for ( const p in src[ u ] ) { + + const property = src[ u ][ p ]; + + if ( isThreeObject( property ) ) { + + if ( property.isRenderTargetTexture ) { + + warn( 'UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().' ); + dst[ u ][ p ] = null; + + } else { + + dst[ u ][ p ] = property.clone(); + + } + + } else if ( Array.isArray( property ) ) { + + if ( isThreeObject( property[ 0 ] ) ) { + + const clonedProperty = []; + + for ( let i = 0, l = property.length; i < l; i ++ ) { + + clonedProperty[ i ] = property[ i ].clone(); + + } + + dst[ u ][ p ] = clonedProperty; + + } else { + + dst[ u ][ p ] = property.slice(); + + } + + } else { + + dst[ u ][ p ] = property; + + } + + } + + } + + return dst; + +} + +/** + * Merges the given uniform definitions into a single object. Since the + * method internally uses cloneUniforms(), it performs a deep-copy when + * producing the merged uniform definitions. + * + * @param {Array} uniforms - An array of objects containing uniform definitions. + * @return {Object} The merged uniforms. + */ +function mergeUniforms( uniforms ) { + + const merged = {}; + + for ( let u = 0; u < uniforms.length; u ++ ) { + + const tmp = cloneUniforms( uniforms[ u ] ); + + for ( const p in tmp ) { + + merged[ p ] = tmp[ p ]; + + } + + } + + return merged; + +} + +function isThreeObject( property ) { + + return ( property && ( property.isColor || + property.isMatrix3 || property.isMatrix4 || + property.isVector2 || property.isVector3 || property.isVector4 || + property.isTexture || property.isQuaternion ) ); + +} + +function cloneUniformsGroups( src ) { + + const dst = []; + + for ( let u = 0; u < src.length; u ++ ) { + + dst.push( src[ u ].clone() ); + + } + + return dst; + +} + +function getUnlitUniformColorSpace( renderer ) { + + const currentRenderTarget = renderer.getRenderTarget(); + + if ( currentRenderTarget === null ) { + + // https://github.com/mrdoob/three.js/pull/23937#issuecomment-1111067398 + return renderer.outputColorSpace; + + } + + // https://github.com/mrdoob/three.js/issues/27868 + if ( currentRenderTarget.isXRRenderTarget === true ) { + + return currentRenderTarget.texture.colorSpace; + + } + + return ColorManagement.workingColorSpace; + +} + +// Legacy + +const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms }; + +var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}"; + +var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}"; + +/** + * A material rendered with custom shaders. A shader is a small program written in GLSL. + * that runs on the GPU. You may want to use a custom shader if you need to implement an + * effect not included with any of the built-in materials. + * + * There are the following notes to bear in mind when using a `ShaderMaterial`: + * + * - `ShaderMaterial` can only be used with {@link WebGLRenderer}. + * - Built in attributes and uniforms are passed to the shaders along with your code. If + * you don't want that, use {@link RawShaderMaterial} instead. + * - You can use the directive `#pragma unroll_loop_start` and `#pragma unroll_loop_end` + * in order to unroll a `for` loop in GLSL by the shader preprocessor. The directive has + * to be placed right above the loop. The loop formatting has to correspond to a defined standard. + * - The loop has to be [normalized](https://en.wikipedia.org/wiki/Normalized_loop). + * - The loop variable has to be *i*. + * - The value `UNROLLED_LOOP_INDEX` will be replaced with the explicitly + * value of *i* for the given iteration and can be used in preprocessor + * statements. + * + * ```js + * const material = new THREE.ShaderMaterial( { + * uniforms: { + * time: { value: 1.0 }, + * resolution: { value: new THREE.Vector2() } + * }, + * vertexShader: document.getElementById( 'vertexShader' ).textContent, + * fragmentShader: document.getElementById( 'fragmentShader' ).textContent + * } ); + * ``` + * + * @augments Material + */ +class ShaderMaterial extends Material { + + /** + * Constructs a new shader material. + * + * @param {Object} [parameters] - An object with one or more properties + * defining the material's appearance. Any property of the material + * (including any property from inherited materials) can be passed + * in here. Color values can be passed any type of value accepted + * by {@link Color#set}. + */ + constructor( parameters ) { + + super(); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isShaderMaterial = true; + + this.type = 'ShaderMaterial'; + + /** + * Defines custom constants using `#define` directives within the GLSL code + * for both the vertex shader and the fragment shader; each key/value pair + * yields another directive. + * ```js + * defines: { + * FOO: 15, + * BAR: true + * } + * ``` + * Yields the lines: + * ``` + * #define FOO 15 + * #define BAR true + * ``` + * + * @type {Object} + */ + this.defines = {}; + + /** + * An object of the form: + * ```js + * { + * "uniform1": { value: 1.0 }, + * "uniform2": { value: 2 } + * } + * ``` + * specifying the uniforms to be passed to the shader code; keys are uniform + * names, values are definitions of the form + * ``` + * { + * value: 1.0 + * } + * ``` + * where `value` is the value of the uniform. Names must match the name of + * the uniform, as defined in the GLSL code. Note that uniforms are refreshed + * on every frame, so updating the value of the uniform will immediately + * update the value available to the GLSL code. + * + * @type {Object} + */ + this.uniforms = {}; + + /** + * An array holding uniforms groups for configuring UBOs. + * + * @type {Array} + */ + this.uniformsGroups = []; + + /** + * Vertex shader GLSL code. This is the actual code for the shader. + * + * @type {string} + */ + this.vertexShader = default_vertex; + + /** + * Fragment shader GLSL code. This is the actual code for the shader. + * + * @type {string} + */ + this.fragmentShader = default_fragment; + + /** + * Controls line thickness or lines. + * + * WebGL and WebGPU ignore this setting and always render line primitives with a + * width of one pixel. + * + * @type {number} + * @default 1 + */ + this.linewidth = 1; + + /** + * Renders the geometry as a wireframe. + * + * @type {boolean} + * @default false + */ + this.wireframe = false; + + /** + * Controls the thickness of the wireframe. + * + * WebGL and WebGPU ignore this property and always render + * 1 pixel wide lines. + * + * @type {number} + * @default 1 + */ + this.wireframeLinewidth = 1; + + /** + * Defines whether the material color is affected by global fog settings; `true` + * to pass fog uniforms to the shader. + * + * Setting this property to `true` requires the definition of fog uniforms. It is + * recommended to use `UniformsUtils.merge()` to combine the custom shader uniforms + * with predefined fog uniforms. + * + * ```js + * const material = new ShaderMaterial( { + * uniforms: UniformsUtils.merge( [ UniformsLib[ 'fog' ], shaderUniforms ] ); + * vertexShader: vertexShader, + * fragmentShader: fragmentShader, + * fog: true + * } ); + * ``` + * + * @type {boolean} + * @default false + */ + this.fog = false; + + /** + * Defines whether this material uses lighting; `true` to pass uniform data + * related to lighting to this shader. + * + * @type {boolean} + * @default false + */ + this.lights = false; + + /** + * Defines whether this material supports clipping; `true` to let the renderer + * pass the clippingPlanes uniform. + * + * @type {boolean} + * @default false + */ + this.clipping = false; + + /** + * Overwritten and set to `true` by default. + * + * @type {boolean} + * @default true + */ + this.forceSinglePass = true; + + /** + * This object allows to enable certain WebGL 2 extensions. + * + * - clipCullDistance: set to `true` to use vertex shader clipping + * - multiDraw: set to `true` to use vertex shader multi_draw / enable gl_DrawID + * + * @type {{clipCullDistance:false,multiDraw:false}} + */ + this.extensions = { + clipCullDistance: false, // set to use vertex shader clipping + multiDraw: false // set to use vertex shader multi_draw / enable gl_DrawID + }; + + /** + * When the rendered geometry doesn't include these attributes but the + * material does, these default values will be passed to the shaders. This + * avoids errors when buffer data is missing. + * + * - color: [ 1, 1, 1 ] + * - uv: [ 0, 0 ] + * - uv1: [ 0, 0 ] + * + * @type {Object} + */ + this.defaultAttributeValues = { + 'color': [ 1, 1, 1 ], + 'uv': [ 0, 0 ], + 'uv1': [ 0, 0 ] + }; + + /** + * If set, this calls [gl.bindAttribLocation](https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/bindAttribLocation) + * to bind a generic vertex index to an attribute variable. + * + * @type {string|undefined} + * @default undefined + */ + this.index0AttributeName = undefined; + + /** + * Can be used to force a uniform update while changing uniforms in + * {@link Object3D#onBeforeRender}. + * + * @type {boolean} + * @default false + */ + this.uniformsNeedUpdate = false; + + /** + * Defines the GLSL version of custom shader code. + * + * @type {?(GLSL1|GLSL3)} + * @default null + */ + this.glslVersion = null; + + if ( parameters !== undefined ) { + + this.setValues( parameters ); + + } + + } + + copy( source ) { + + super.copy( source ); + + this.fragmentShader = source.fragmentShader; + this.vertexShader = source.vertexShader; + + this.uniforms = cloneUniforms( source.uniforms ); + this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups ); + + this.defines = Object.assign( {}, source.defines ); + + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + + this.fog = source.fog; + this.lights = source.lights; + this.clipping = source.clipping; + + this.extensions = Object.assign( {}, source.extensions ); + + this.glslVersion = source.glslVersion; + + this.defaultAttributeValues = Object.assign( {}, source.defaultAttributeValues ); + + this.index0AttributeName = source.index0AttributeName; + + this.uniformsNeedUpdate = source.uniformsNeedUpdate; + + return this; + + } + + toJSON( meta ) { + + const data = super.toJSON( meta ); + + data.glslVersion = this.glslVersion; + data.uniforms = {}; + + for ( const name in this.uniforms ) { + + const uniform = this.uniforms[ name ]; + const value = uniform.value; + + if ( value && value.isTexture ) { + + data.uniforms[ name ] = { + type: 't', + value: value.toJSON( meta ).uuid + }; + + } else if ( value && value.isColor ) { + + data.uniforms[ name ] = { + type: 'c', + value: value.getHex() + }; + + } else if ( value && value.isVector2 ) { + + data.uniforms[ name ] = { + type: 'v2', + value: value.toArray() + }; + + } else if ( value && value.isVector3 ) { + + data.uniforms[ name ] = { + type: 'v3', + value: value.toArray() + }; + + } else if ( value && value.isVector4 ) { + + data.uniforms[ name ] = { + type: 'v4', + value: value.toArray() + }; + + } else if ( value && value.isMatrix3 ) { + + data.uniforms[ name ] = { + type: 'm3', + value: value.toArray() + }; + + } else if ( value && value.isMatrix4 ) { + + data.uniforms[ name ] = { + type: 'm4', + value: value.toArray() + }; + + } else { + + data.uniforms[ name ] = { + value: value + }; + + // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far + + } + + } + + if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines; + + data.vertexShader = this.vertexShader; + data.fragmentShader = this.fragmentShader; + + data.lights = this.lights; + data.clipping = this.clipping; + + const extensions = {}; + + for ( const key in this.extensions ) { + + if ( this.extensions[ key ] === true ) extensions[ key ] = true; + + } + + if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions; + + return data; + + } + + /** + * Deserializes the material from the given JSON. + * + * @param {Object} json - The JSON holding the serialized material. + * @param {Object} textures - A dictionary holding textures referenced by the material. + * @return {ShaderMaterial} A reference to this material. + */ + fromJSON( json, textures ) { + + super.fromJSON( json, textures ); + + if ( json.uniforms !== undefined ) { + + for ( const name in json.uniforms ) { + + const uniform = json.uniforms[ name ]; + + this.uniforms[ name ] = {}; + + switch ( uniform.type ) { + + case 't': + this.uniforms[ name ].value = textures[ uniform.value ] || null; + break; + + case 'c': + this.uniforms[ name ].value = new Color().setHex( uniform.value ); + break; + + case 'v2': + this.uniforms[ name ].value = new Vector2().fromArray( uniform.value ); + break; + + case 'v3': + this.uniforms[ name ].value = new Vector3().fromArray( uniform.value ); + break; + + case 'v4': + this.uniforms[ name ].value = new Vector4().fromArray( uniform.value ); + break; + + case 'm3': + this.uniforms[ name ].value = new Matrix3().fromArray( uniform.value ); + break; + + case 'm4': + this.uniforms[ name ].value = new Matrix4().fromArray( uniform.value ); + break; + + default: + this.uniforms[ name ].value = uniform.value; + + } + + } + + } + + if ( json.defines !== undefined ) this.defines = json.defines; + if ( json.vertexShader !== undefined ) this.vertexShader = json.vertexShader; + if ( json.fragmentShader !== undefined ) this.fragmentShader = json.fragmentShader; + if ( json.glslVersion !== undefined ) this.glslVersion = json.glslVersion; + + if ( json.extensions !== undefined ) { + + for ( const key in json.extensions ) { + + this.extensions[ key ] = json.extensions[ key ]; + + } + + } + + if ( json.lights !== undefined ) this.lights = json.lights; + if ( json.clipping !== undefined ) this.clipping = json.clipping; + + return this; + + } + +} + +/** + * This class works just like {@link ShaderMaterial}, except that definitions + * of built-in uniforms and attributes are not automatically prepended to the + * GLSL shader code. + * + * `RawShaderMaterial` can only be used with {@link WebGLRenderer}. + * + * @augments ShaderMaterial + */ +class RawShaderMaterial extends ShaderMaterial { + + /** + * Constructs a new raw shader material. + * + * @param {Object} [parameters] - An object with one or more properties + * defining the material's appearance. Any property of the material + * (including any property from inherited materials) can be passed + * in here. Color values can be passed any type of value accepted + * by {@link Color#set}. + */ + constructor( parameters ) { + + super( parameters ); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isRawShaderMaterial = true; + + this.type = 'RawShaderMaterial'; + + } + +} + +/** + * A standard physically based material, using Metallic-Roughness workflow. + * + * Physically based rendering (PBR) has recently become the standard in many + * 3D applications, such as [Unity](https://blogs.unity3d.com/2014/10/29/physically-based-shading-in-unity-5-a-primer/), + * [Unreal](https://docs.unrealengine.com/latest/INT/Engine/Rendering/Materials/PhysicallyBased/) and + * [3D Studio Max](http://area.autodesk.com/blogs/the-3ds-max-blog/what039s-new-for-rendering-in-3ds-max-2017). + * + * This approach differs from older approaches in that instead of using + * approximations for the way in which light interacts with a surface, a + * physically correct model is used. The idea is that, instead of tweaking + * materials to look good under specific lighting, a material can be created + * that will react 'correctly' under all lighting scenarios. + * + * In practice this gives a more accurate and realistic looking result than + * the {@link MeshLambertMaterial} or {@link MeshPhongMaterial}, at the cost of + * being somewhat more computationally expensive. `MeshStandardMaterial` uses per-fragment + * shading. + * + * Note that for best results you should always specify an environment map when using this material. + * + * For a non-technical introduction to the concept of PBR and how to set up a + * PBR material, check out these articles by the people at [marmoset](https://www.marmoset.co): + * + * - [Basic Theory of Physically Based Rendering](https://www.marmoset.co/posts/basic-theory-of-physically-based-rendering/) + * - [Physically Based Rendering and You Can Too](https://www.marmoset.co/posts/physically-based-rendering-and-you-can-too/) + * + * Technical details of the approach used in three.js (and most other PBR systems) can be found is this + * [paper from Disney](https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf) + * (pdf), by Brent Burley. + * + * @augments Material + * @demo scenes/material-browser.html#MeshStandardMaterial + */ +class MeshStandardMaterial extends Material { + + /** + * Constructs a new mesh standard material. + * + * @param {Object} [parameters] - An object with one or more properties + * defining the material's appearance. Any property of the material + * (including any property from inherited materials) can be passed + * in here. Color values can be passed any type of value accepted + * by {@link Color#set}. + */ + constructor( parameters ) { + + super(); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isMeshStandardMaterial = true; + + this.type = 'MeshStandardMaterial'; + + this.defines = { 'STANDARD': '' }; + + /** + * Color of the material. + * + * @type {Color} + * @default (1,1,1) + */ + this.color = new Color( 0xffffff ); // diffuse + + /** + * How rough the material appears. `0.0` means a smooth mirror reflection, `1.0` + * means fully diffuse. If `roughnessMap` is also provided, + * both values are multiplied. + * + * @type {number} + * @default 1 + */ + this.roughness = 1.0; + + /** + * How much the material is like a metal. Non-metallic materials such as wood + * or stone use `0.0`, metallic use `1.0`, with nothing (usually) in between. + * A value between `0.0` and `1.0` could be used for a rusty metal look. + * If `metalnessMap` is also provided, both values are multiplied. + * + * @type {number} + * @default 0 + */ + this.metalness = 0.0; + + /** + * The color map. May optionally include an alpha channel, typically combined + * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map + * color is modulated by the diffuse `color`. + * + * `map` represents color data, and the texture must be assigned a + * {@link Texture#colorSpace}. Most `map` textures set + * `texture.colorSpace = SRGBColorSpace`. + * + * @type {?Texture} + * @default null + */ + this.map = null; + + /** + * The light map. Requires a second set of UVs. + * + * `lightMap` represents pre-baked illuminance data, and the texture must be assigned + * a {@link Texture#colorSpace}. Most `lightMap` textures set + * `texture.colorSpace = LinearSRGBColorSpace` and use float-type formats + * such as `.exr` or `.hdr`. + * + * @type {?Texture} + * @default null + */ + this.lightMap = null; + + /** + * Intensity of the baked light. + * + * @type {number} + * @default 1 + */ + this.lightMapIntensity = 1.0; + + /** + * The red channel of this texture is used as the ambient occlusion map. + * Requires a second set of UVs. + * + * `aoMap` represents non-color data. Any texture assigned must have + * `texture.colorSpace = NoColorSpace` (default). + * + * @type {?Texture} + * @default null + */ + this.aoMap = null; + + /** + * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0` + * disables ambient occlusion. Where intensity is `1` and the AO map's + * red channel is also `1`, ambient light is fully occluded on a surface. + * + * @type {number} + * @default 1 + */ + this.aoMapIntensity = 1.0; + + /** + * Emissive (light) color of the material, essentially a solid color + * unaffected by other lighting. + * + * @type {Color} + * @default (0,0,0) + */ + this.emissive = new Color( 0x000000 ); + + /** + * Intensity of the emissive light. Modulates the emissive color. + * + * @type {number} + * @default 1 + */ + this.emissiveIntensity = 1.0; + + /** + * Set emissive (glow) map. The emissive map color is modulated by the + * emissive color and the emissive intensity. If you have an emissive map, + * be sure to set the emissive color to something other than black. + * + * `emissiveMap` represents color data, and the texture must be assigned a + * {@link Texture#colorSpace}. Most `emissiveMap` textures set + * `texture.colorSpace = SRGBColorSpace`. + * + * @type {?Texture} + * @default null + */ + this.emissiveMap = null; + + /** + * The texture to create a bump map. The black and white values map to the + * perceived depth in relation to the lights. Bump doesn't actually affect + * the geometry of the object, only the lighting. If a normal map is defined + * this will be ignored. + * + * `bumpMap` represents non-color data. Any texture assigned must have + * `texture.colorSpace = NoColorSpace` (default). + * + * @type {?Texture} + * @default null + */ + this.bumpMap = null; + + /** + * How much the bump map affects the material. Typical range is `[0,1]`. + * + * @type {number} + * @default 1 + */ + this.bumpScale = 1; + + /** + * The texture to create a normal map. The RGB values affect the surface + * normal for each pixel fragment and change the way the color is lit. Normal + * maps do not change the actual shape of the surface, only the lighting. In + * case the material has a normal map authored using the left handed + * convention, the `y` component of `normalScale` should be negated to compensate + * for the different handedness. + * + * `normalMap` represents non-color data. Any texture assigned must have + * `texture.colorSpace = NoColorSpace` (default). + * + * @type {?Texture} + * @default null + */ + this.normalMap = null; + + /** + * The type of normal map. + * + * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)} + * @default TangentSpaceNormalMap + */ + this.normalMapType = TangentSpaceNormalMap; + + /** + * How much the normal map affects the material. Typical value range is `[0,1]`. + * + * @type {Vector2} + * @default (1,1) + */ + this.normalScale = new Vector2( 1, 1 ); + + /** + * The displacement map affects the position of the mesh's vertices. Unlike + * other maps which only affect the light and shade of the material the + * displaced vertices can cast shadows, block other objects, and otherwise + * act as real geometry. The displacement texture is an image where the value + * of each pixel (white being the highest) is mapped against, and + * repositions, the vertices of the mesh. For best results, pair a + * displacement map with a matching normal map, since the renderer can + * not recompute surface normals from the displaced vertices. + * + * `displacementMap` represents non-color data. Any texture assigned must have + * `texture.colorSpace = NoColorSpace` (default). + * + * @type {?Texture} + * @default null + */ + this.displacementMap = null; + + /** + * How much the displacement map affects the mesh (where black is no + * displacement, and white is maximum displacement). Without a displacement + * map set, this value is not applied. + * + * @type {number} + * @default 0 + */ + this.displacementScale = 1; + + /** + * The offset of the displacement map's values on the mesh's vertices. + * The bias is added to the scaled sample of the displacement map. + * Without a displacement map set, this value is not applied. + * + * @type {number} + * @default 0 + */ + this.displacementBias = 0; + + /** + * The green channel of this texture is used to alter the roughness of the + * material. + * + * `roughnessMap` represents non-color data. Any texture assigned must have + * `texture.colorSpace = NoColorSpace` (default). + * + * @type {?Texture} + * @default null + */ + this.roughnessMap = null; + + /** + * The blue channel of this texture is used to alter the metalness of the + * material. + * + * `metalnessMap` represents non-color data. Any texture assigned must have + * `texture.colorSpace = NoColorSpace` (default). + * + * @type {?Texture} + * @default null + */ + this.metalnessMap = null; + + /** + * The alpha map is a grayscale texture that controls the opacity across the + * surface (black: fully transparent; white: fully opaque). + * + * Only the color of the texture is used, ignoring the alpha channel if one + * exists. For RGB and RGBA textures, the renderer will use the green channel + * when sampling this texture due to the extra bit of precision provided for + * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and + * luminance/alpha textures will also still work as expected. + * + * `alphaMap` represents non-color data. Any texture assigned must have + * `texture.colorSpace = NoColorSpace` (default). + * + * @type {?Texture} + * @default null + */ + this.alphaMap = null; + + /** + * The environment map. To ensure a physically correct rendering, environment maps + * are internally pre-processed with {@link PMREMGenerator}. + * + * `envMap` represents luminance data, and the texture must be assigned + * a {@link Texture#colorSpace}. Most `envMap` textures set + * `texture.colorSpace = LinearSRGBColorSpace` and use float-type formats + * such as `.exr` or `.hdr`. + * + * @type {?Texture} + * @default null + */ + this.envMap = null; + + /** + * The rotation of the environment map in radians. + * + * @type {Euler} + * @default (0,0,0) + */ + this.envMapRotation = new Euler(); + + /** + * Scales the effect of the environment map by multiplying its color. + * + * @type {number} + * @default 1 + */ + this.envMapIntensity = 1.0; + + /** + * Renders the geometry as a wireframe. + * + * @type {boolean} + * @default false + */ + this.wireframe = false; + + /** + * Controls the thickness of the wireframe. + * + * Can only be used with {@link SVGRenderer}. + * + * @type {number} + * @default 1 + */ + this.wireframeLinewidth = 1; + + /** + * Defines appearance of wireframe ends. + * + * Can only be used with {@link SVGRenderer}. + * + * @type {('round'|'bevel'|'miter')} + * @default 'round' + */ + this.wireframeLinecap = 'round'; + + /** + * Defines appearance of wireframe joints. + * + * Can only be used with {@link SVGRenderer}. + * + * @type {('round'|'bevel'|'miter')} + * @default 'round' + */ + this.wireframeLinejoin = 'round'; + + /** + * Whether the material is rendered with flat shading or not. + * + * @type {boolean} + * @default false + */ + this.flatShading = false; + + /** + * Whether the material is affected by fog or not. + * + * @type {boolean} + * @default true + */ + this.fog = true; + + this.setValues( parameters ); + + } + + copy( source ) { + + super.copy( source ); + + this.defines = { 'STANDARD': '' }; + + this.color.copy( source.color ); + this.roughness = source.roughness; + this.metalness = source.metalness; + + this.map = source.map; + + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; + + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + + this.emissive.copy( source.emissive ); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; + + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy( source.normalScale ); + + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + + this.roughnessMap = source.roughnessMap; + + this.metalnessMap = source.metalnessMap; + + this.alphaMap = source.alphaMap; + + this.envMap = source.envMap; + this.envMapRotation.copy( source.envMapRotation ); + this.envMapIntensity = source.envMapIntensity; + + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + + this.flatShading = source.flatShading; + + this.fog = source.fog; + + return this; + + } + +} + +/** + * An extension of the {@link MeshStandardMaterial}, providing more advanced + * physically-based rendering properties: + * + * - Anisotropy: Ability to represent the anisotropic property of materials + * as observable with brushed metals. + * - Clearcoat: Some materials — like car paints, carbon fiber, and wet surfaces — require + * a clear, reflective layer on top of another layer that may be irregular or rough. + * Clearcoat approximates this effect, without the need for a separate transparent surface. + * - Iridescence: Allows to render the effect where hue varies depending on the viewing + * angle and illumination angle. This can be seen on soap bubbles, oil films, or on the + * wings of many insects. + * - Physically-based transparency: One limitation of {@link Material#opacity} is that highly + * transparent materials are less reflective. Physically-based transmission provides a more + * realistic option for thin, transparent surfaces like glass. + * - Advanced reflectivity: More flexible reflectivity for non-metallic materials. + * - Retroreflection: Redirects specular light back toward the light source for + * safety materials like road markings and reflective tape. + * - Sheen: Can be used for representing cloth and fabric materials. + * + * As a result of these complex shading features, `MeshPhysicalMaterial` has a + * higher performance cost, per pixel, than other three.js materials. Most + * effects are disabled by default, and add cost as they are enabled. For + * best results, always specify an environment map when using this material. + * + * @augments MeshStandardMaterial + * @demo scenes/material-browser.html#MeshPhysicalMaterial + */ +class MeshPhysicalMaterial extends MeshStandardMaterial { + + /** + * Constructs a new mesh physical material. + * + * @param {Object} [parameters] - An object with one or more properties + * defining the material's appearance. Any property of the material + * (including any property from inherited materials) can be passed + * in here. Color values can be passed any type of value accepted + * by {@link Color#set}. + */ + constructor( parameters ) { + + super(); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isMeshPhysicalMaterial = true; + + this.defines = { + + 'STANDARD': '', + 'PHYSICAL': '' + + }; + + this.type = 'MeshPhysicalMaterial'; + + /** + * The rotation of the anisotropy in tangent, bitangent space, measured in radians + * counter-clockwise from the tangent. When `anisotropyMap` is present, this + * property provides additional rotation to the vectors in the texture. + * + * @type {number} + * @default 1 + */ + this.anisotropyRotation = 0; + + /** + * Red and green channels represent the anisotropy direction in `[-1, 1]` tangent, + * bitangent space, to be rotated by `anisotropyRotation`. The blue channel + * contains strength as `[0, 1]` to be multiplied by `anisotropy`. + * + * `anisotropyMap` represents non-color data. Any texture assigned must have + * `texture.colorSpace = NoColorSpace` (default). + * + * @type {?Texture} + * @default null + */ + this.anisotropyMap = null; + + /** + * The red channel of this texture is multiplied against `clearcoat`, + * for per-pixel control over a coating's intensity. + * + * `clearcoatMap` represents non-color data. Any texture assigned must have + * `texture.colorSpace = NoColorSpace` (default). + * + * @type {?Texture} + * @default null + */ + this.clearcoatMap = null; + + /** + * Roughness of the clear coat layer, from `0.0` to `1.0`. + * + * @type {number} + * @default 0 + */ + this.clearcoatRoughness = 0.0; + + /** + * The green channel of this texture is multiplied against + * `clearcoatRoughness`, for per-pixel control over a coating's roughness. + * + * `clearcoatRoughnessMap` represents non-color data. Any texture assigned must have + * `texture.colorSpace = NoColorSpace` (default). + * + * @type {?Texture} + * @default null + */ + this.clearcoatRoughnessMap = null; + + /** + * How much `clearcoatNormalMap` affects the clear coat layer, from + * `(0,0)` to `(1,1)`. + * + * @type {Vector2} + * @default (1,1) + */ + this.clearcoatNormalScale = new Vector2( 1, 1 ); + + /** + * Can be used to enable independent normals for the clear coat layer. + * + * `clearcoatNormalMap` represents non-color data. Any texture assigned must have + * `texture.colorSpace = NoColorSpace` (default). + * + * @type {?Texture} + * @default null + */ + this.clearcoatNormalMap = null; + + /** + * Index-of-refraction for non-metallic materials, from `1.0` to `2.333`. + * + * @type {number} + * @default 1.5 + */ + this.ior = 1.5; + + /** + * Degree of reflectivity, from `0.0` to `1.0`. Default is `0.5`, which + * corresponds to an index-of-refraction of `1.5`. + * + * This models the reflectivity of non-metallic materials. It has no effect + * when `metalness` is `1.0` + * + * @name MeshPhysicalMaterial#reflectivity + * @type {number} + * @default 0.5 + */ + Object.defineProperty( this, 'reflectivity', { + get: function () { + + return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) ); + + }, + set: function ( reflectivity ) { + + this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity ); + + } + } ); + + /** + * The red channel of this texture is multiplied against `iridescence`, for per-pixel + * control over iridescence. + * + * `iridescenceMap` represents non-color data. Any texture assigned must have + * `texture.colorSpace = NoColorSpace` (default). + * + * @type {?Texture} + * @default null + */ + this.iridescenceMap = null; + + /** + * Strength of the iridescence RGB color shift effect, represented by an index-of-refraction. + * Between `1.0` to `2.333`. + * + * @type {number} + * @default 1.3 + */ + this.iridescenceIOR = 1.3; + + /** + *Array of exactly 2 elements, specifying minimum and maximum thickness of the iridescence layer. + Thickness of iridescence layer has an equivalent effect of the one `thickness` has on `ior`. + * + * @type {Array} + * @default [100,400] + */ + this.iridescenceThicknessRange = [ 100, 400 ]; + + /** + * A texture that defines the thickness of the iridescence layer, stored in the green channel. + * Minimum and maximum values of thickness are defined by `iridescenceThicknessRange` array: + * - `0.0` in the green channel will result in thickness equal to first element of the array. + * - `1.0` in the green channel will result in thickness equal to second element of the array. + * - Values in-between will linearly interpolate between the elements of the array. + * + * `iridescenceThicknessMap` represents non-color data. Any texture assigned must have + * `texture.colorSpace = NoColorSpace` (default). + * + * @type {?Texture} + * @default null + */ + this.iridescenceThicknessMap = null; + + /** + * The sheen tint. + * + * @type {Color} + * @default (0,0,0) + */ + this.sheenColor = new Color( 0x000000 ); + + /** + * The RGB channels of this texture are multiplied against `sheenColor`, for per-pixel control + * over sheen tint. + * + * `sheenColorMap` represents color data, and the texture must be assigned a + * {@link Texture#colorSpace}. Most `sheenColorMap` textures set + * `texture.colorSpace = SRGBColorSpace`. + * + * @type {?Texture} + * @default null + */ + this.sheenColorMap = null; + + /** + * Roughness of the sheen layer, from `0.0` to `1.0`. + * + * @type {number} + * @default 1 + */ + this.sheenRoughness = 1.0; + + /** + * The alpha channel of this texture is multiplied against `sheenRoughness`, for per-pixel control + * over sheen roughness. + * + * `sheenRoughnessMap` represents non-color data. Any texture assigned must have + * `texture.colorSpace = NoColorSpace` (default). + * + * @type {?Texture} + * @default null + */ + this.sheenRoughnessMap = null; + + /** + * The red channel of this texture is multiplied against `transmission`, for per-pixel control over + * optical transparency. + * + * `transmissionMap` represents non-color data. Any texture assigned must have + * `texture.colorSpace = NoColorSpace` (default). + * + * @type {?Texture} + * @default null + */ + this.transmissionMap = null; + + /** + * The thickness of the volume beneath the surface. The value is given in the + * coordinate space of the mesh. If the value is `0` the material is + * thin-walled. Otherwise the material is a volume boundary. + * + * @type {number} + * @default 0 + */ + this.thickness = 0; + + /** + * A texture that defines the thickness, stored in the green channel. This will + * be multiplied by `thickness`. + * + * `thicknessMap` represents non-color data. Any texture assigned must have + * `texture.colorSpace = NoColorSpace` (default). + * + * @type {?Texture} + * @default null + */ + this.thicknessMap = null; + + /** + * Density of the medium given as the average distance that light travels in + * the medium before interacting with a particle. The value is given in world + * space units, and must be greater than zero. + * + * @type {number} + * @default Infinity + */ + this.attenuationDistance = Infinity; + + /** + * The color that white light turns into due to absorption when reaching the + * attenuation distance. + * + * @type {Color} + * @default (1,1,1) + */ + this.attenuationColor = new Color( 1, 1, 1 ); + + /** + * A float that scales the amount of specular reflection for non-metals only. + * When set to zero, the model is effectively Lambertian. From `0.0` to `1.0`. + * + * @type {number} + * @default 1 + */ + this.specularIntensity = 1.0; + + /** + * The alpha channel of this texture is multiplied against `specularIntensity`, + * for per-pixel control over specular intensity. + * + * `specularIntensityMap` represents non-color data. Any texture assigned must have + * `texture.colorSpace = NoColorSpace` (default). + * + * @type {?Texture} + * @default null + */ + this.specularIntensityMap = null; + + /** + * Tints the specular reflection at normal incidence for non-metals only. + * + * @type {Color} + * @default (1,1,1) + */ + this.specularColor = new Color( 1, 1, 1 ); + + /** + * The RGB channels of this texture are multiplied against `specularColor`, + * for per-pixel control over specular color. + * + * `specularColorMap` represents color data, and the texture must be assigned a + * {@link Texture#colorSpace}. Most `specularColorMap` textures set + * `texture.colorSpace = SRGBColorSpace`. + * + * @type {?Texture} + * @default null + */ + this.specularColorMap = null; + + this._anisotropy = 0; + this._clearcoat = 0; + this._dispersion = 0; + this._iridescence = 0; + this._retroreflectivity = 0; + this._sheen = 0.0; + this._transmission = 0; + + this.setValues( parameters ); + + } + + /** + * The anisotropy strength, from `0.0` to `1.0`. + * + * @type {number} + * @default 0 + */ + get anisotropy() { + + return this._anisotropy; + + } + + set anisotropy( value ) { + + if ( this._anisotropy > 0 !== value > 0 ) { + + this.version ++; + + } + + this._anisotropy = value; + + } + + /** + * Represents the intensity of the clear coat layer, from `0.0` to `1.0`. Use + * clear coat related properties to enable multilayer materials that have a + * thin translucent layer over the base layer. + * + * @type {number} + * @default 0 + */ + get clearcoat() { + + return this._clearcoat; + + } + + set clearcoat( value ) { + + if ( this._clearcoat > 0 !== value > 0 ) { + + this.version ++; + + } + + this._clearcoat = value; + + } + /** + * The intensity of the iridescence layer, simulating RGB color shift based on the angle between + * the surface and the viewer, from `0.0` to `1.0`. + * + * @type {number} + * @default 0 + */ + get iridescence() { + + return this._iridescence; + + } + + set iridescence( value ) { + + if ( this._iridescence > 0 !== value > 0 ) { + + this.version ++; + + } + + this._iridescence = value; + + } + + /** + * Defines the strength of the angular separation of colors (chromatic aberration) transmitting + * through a relatively clear volume. Any value zero or larger is valid, the typical range of + * realistic values is `[0, 1]`. This property can be only be used with transmissive objects. + * + * @type {number} + * @default 0 + */ + get dispersion() { + + return this._dispersion; + + } + + set dispersion( value ) { + + if ( this._dispersion > 0 !== value > 0 ) { + + this.version ++; + + } + + this._dispersion = value; + + } + + /** + * The strength of retroreflection, from `0.0` to `1.0`. A value of `1.0` + * evaluates the material's microfacet reflection with the view direction + * reflected about the surface normal, redirecting the specular lobe back + * toward the light source. + * + * @type {number} + * @default 0 + */ + get retroreflectivity() { + + return this._retroreflectivity; + + } + + set retroreflectivity( value ) { + + if ( this._retroreflectivity > 0 !== value > 0 ) { + + this.version ++; + + } + + this._retroreflectivity = value; + + } + + /** + * The intensity of the sheen layer, from `0.0` to `1.0`. + * + * @type {number} + * @default 0 + */ + get sheen() { + + return this._sheen; + + } + + set sheen( value ) { + + if ( this._sheen > 0 !== value > 0 ) { + + this.version ++; + + } + + this._sheen = value; + + } + + /** + * Degree of transmission (or optical transparency), from `0.0` to `1.0`. + * + * Thin, transparent or semitransparent, plastic or glass materials remain + * largely reflective even if they are fully transmissive. The transmission + * property can be used to model these materials. + * + * When transmission is non-zero, `opacity` should be set to `1`. + * + * @type {number} + * @default 0 + */ + get transmission() { + + return this._transmission; + + } + + set transmission( value ) { + + if ( this._transmission > 0 !== value > 0 ) { + + this.version ++; + + } + + this._transmission = value; + + } + + copy( source ) { + + super.copy( source ); + + this.defines = { + + 'STANDARD': '', + 'PHYSICAL': '' + + }; + + this.anisotropy = source.anisotropy; + this.anisotropyRotation = source.anisotropyRotation; + this.anisotropyMap = source.anisotropyMap; + + this.clearcoat = source.clearcoat; + this.clearcoatMap = source.clearcoatMap; + this.clearcoatRoughness = source.clearcoatRoughness; + this.clearcoatRoughnessMap = source.clearcoatRoughnessMap; + this.clearcoatNormalMap = source.clearcoatNormalMap; + this.clearcoatNormalScale.copy( source.clearcoatNormalScale ); + + this.dispersion = source.dispersion; + this.ior = source.ior; + + this.iridescence = source.iridescence; + this.iridescenceMap = source.iridescenceMap; + this.iridescenceIOR = source.iridescenceIOR; + this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ]; + this.iridescenceThicknessMap = source.iridescenceThicknessMap; + + this.retroreflectivity = source.retroreflectivity; + + this.sheen = source.sheen; + this.sheenColor.copy( source.sheenColor ); + this.sheenColorMap = source.sheenColorMap; + this.sheenRoughness = source.sheenRoughness; + this.sheenRoughnessMap = source.sheenRoughnessMap; + + this.transmission = source.transmission; + this.transmissionMap = source.transmissionMap; + + this.thickness = source.thickness; + this.thicknessMap = source.thicknessMap; + this.attenuationDistance = source.attenuationDistance; + this.attenuationColor.copy( source.attenuationColor ); + + this.specularIntensity = source.specularIntensity; + this.specularIntensityMap = source.specularIntensityMap; + this.specularColor.copy( source.specularColor ); + this.specularColorMap = source.specularColorMap; + + return this; + + } + +} + +/** + * A material for shiny surfaces with specular highlights. + * + * The material uses a non-physically based [Blinn-Phong](https://en.wikipedia.org/wiki/Blinn-Phong_shading_model) + * model for calculating reflectance. Unlike the Lambertian model used in the + * {@link MeshLambertMaterial} this can simulate shiny surfaces with specular + * highlights (such as varnished wood). `MeshPhongMaterial` uses per-fragment shading. + * + * Performance will generally be greater when using this material over the + * {@link MeshStandardMaterial} or {@link MeshPhysicalMaterial}, at the cost of + * some graphical accuracy. + * + * @augments Material + * @demo scenes/material-browser.html#MeshPhongMaterial + */ +class MeshPhongMaterial extends Material { + + /** + * Constructs a new mesh phong material. + * + * @param {Object} [parameters] - An object with one or more properties + * defining the material's appearance. Any property of the material + * (including any property from inherited materials) can be passed + * in here. Color values can be passed any type of value accepted + * by {@link Color#set}. + */ + constructor( parameters ) { + + super(); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isMeshPhongMaterial = true; + + this.type = 'MeshPhongMaterial'; + + /** + * Color of the material. + * + * @type {Color} + * @default (1,1,1) + */ + this.color = new Color( 0xffffff ); // diffuse + + /** + * Specular color of the material. The default color is set to `0x111111` (very dark grey) + * + * This defines how shiny the material is and the color of its shine. + * + * @type {Color} + */ + this.specular = new Color( 0x111111 ); + + /** + * How shiny the specular highlight is; a higher value gives a sharper highlight. + * + * @type {number} + * @default 30 + */ + this.shininess = 30; + + /** + * The color map. May optionally include an alpha channel, typically combined + * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map + * color is modulated by the diffuse `color`. + * + * `map` represents color data, and the texture must be assigned a + * {@link Texture#colorSpace}. Most `map` textures set + * `texture.colorSpace = SRGBColorSpace`. + * + * @type {?Texture} + * @default null + */ + this.map = null; + + /** + * The light map. Requires a second set of UVs. + * + * `lightMap` represents pre-baked illuminance data, and the texture must be assigned + * a {@link Texture#colorSpace}. Most `lightMap` textures set + * `texture.colorSpace = LinearSRGBColorSpace` and use float-type formats + * such as `.exr` or `.hdr`. + * + * @type {?Texture} + * @default null + */ + this.lightMap = null; + + /** + * Intensity of the baked light. + * + * @type {number} + * @default 1 + */ + this.lightMapIntensity = 1.0; + + /** + * The red channel of this texture is used as the ambient occlusion map. + * Requires a second set of UVs. + * + * `aoMap` represents non-color data. Any texture assigned must have + * `texture.colorSpace = NoColorSpace` (default). + * + * @type {?Texture} + * @default null + */ + this.aoMap = null; + + /** + * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0` + * disables ambient occlusion. Where intensity is `1` and the AO map's + * red channel is also `1`, ambient light is fully occluded on a surface. + * + * @type {number} + * @default 1 + */ + this.aoMapIntensity = 1.0; + + /** + * Emissive (light) color of the material, essentially a solid color + * unaffected by other lighting. + * + * @type {Color} + * @default (0,0,0) + */ + this.emissive = new Color( 0x000000 ); + + /** + * Intensity of the emissive light. Modulates the emissive color. + * + * @type {number} + * @default 1 + */ + this.emissiveIntensity = 1.0; + + /** + * Set emissive (glow) map. The emissive map color is modulated by the + * emissive color and the emissive intensity. If you have an emissive map, + * be sure to set the emissive color to something other than black. + * + * `emissiveMap` represents color data, and the texture must be assigned a + * {@link Texture#colorSpace}. Most `emissiveMap` textures set + * `texture.colorSpace = SRGBColorSpace`. + * + * @type {?Texture} + * @default null + */ + this.emissiveMap = null; + + /** + * The texture to create a bump map. The black and white values map to the + * perceived depth in relation to the lights. Bump doesn't actually affect + * the geometry of the object, only the lighting. If a normal map is defined + * this will be ignored. + * + * `bumpMap` represents non-color data. Any texture assigned must have + * `texture.colorSpace = NoColorSpace` (default). + * + * @type {?Texture} + * @default null + */ + this.bumpMap = null; + + /** + * How much the bump map affects the material. Typical range is `[0,1]`. + * + * @type {number} + * @default 1 + */ + this.bumpScale = 1; + + /** + * The texture to create a normal map. The RGB values affect the surface + * normal for each pixel fragment and change the way the color is lit. Normal + * maps do not change the actual shape of the surface, only the lighting. In + * case the material has a normal map authored using the left handed + * convention, the `y` component of `normalScale` should be negated to compensate + * for the different handedness. + * + * `normalMap` represents non-color data. Any texture assigned must have + * `texture.colorSpace = NoColorSpace` (default). + * + * @type {?Texture} + * @default null + */ + this.normalMap = null; + + /** + * The type of normal map. + * + * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)} + * @default TangentSpaceNormalMap + */ + this.normalMapType = TangentSpaceNormalMap; + + /** + * How much the normal map affects the material. Typical value range is `[0,1]`. + * + * @type {Vector2} + * @default (1,1) + */ + this.normalScale = new Vector2( 1, 1 ); + + /** + * The displacement map affects the position of the mesh's vertices. Unlike + * other maps which only affect the light and shade of the material the + * displaced vertices can cast shadows, block other objects, and otherwise + * act as real geometry. The displacement texture is an image where the value + * of each pixel (white being the highest) is mapped against, and + * repositions, the vertices of the mesh. For best results, pair a + * displacement map with a matching normal map, since the renderer can + * not recompute surface normals from the displaced vertices. + * + * `displacementMap` represents non-color data. Any texture assigned must have + * `texture.colorSpace = NoColorSpace` (default). + * + * @type {?Texture} + * @default null + */ + this.displacementMap = null; + + /** + * How much the displacement map affects the mesh (where black is no + * displacement, and white is maximum displacement). Without a displacement + * map set, this value is not applied. + * + * @type {number} + * @default 0 + */ + this.displacementScale = 1; + + /** + * The offset of the displacement map's values on the mesh's vertices. + * The bias is added to the scaled sample of the displacement map. + * Without a displacement map set, this value is not applied. + * + * @type {number} + * @default 0 + */ + this.displacementBias = 0; + + /** + * The specular map value affects both how much the specular surface + * highlight contributes and how much of the environment map affects the + * surface. + * + * `specularMap` represents color data, and the texture must be assigned a + * {@link Texture#colorSpace}. Most `specularMap` textures set + * `texture.colorSpace = SRGBColorSpace`. + * + * @type {?Texture} + * @default null + */ + this.specularMap = null; + + /** + * The alpha map is a grayscale texture that controls the opacity across the + * surface (black: fully transparent; white: fully opaque). + * + * Only the color of the texture is used, ignoring the alpha channel if one + * exists. For RGB and RGBA textures, the renderer will use the green channel + * when sampling this texture due to the extra bit of precision provided for + * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and + * luminance/alpha textures will also still work as expected. + * + * `alphaMap` represents non-color data. Any texture assigned must have + * `texture.colorSpace = NoColorSpace` (default). + * + * @type {?Texture} + * @default null + */ + this.alphaMap = null; + + /** + * The environment map. + * + * `envMap` represents luminance data, and the texture must be assigned + * a {@link Texture#colorSpace}. Most `envMap` textures set + * `texture.colorSpace = LinearSRGBColorSpace` and use float-type formats + * such as `.exr` or `.hdr`. + * + * @type {?Texture} + * @default null + */ + this.envMap = null; + + /** + * The rotation of the environment map in radians. + * + * @type {Euler} + * @default (0,0,0) + */ + this.envMapRotation = new Euler(); + + /** + * How to combine the result of the surface's color with the environment map, if any. + * + * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to + * blend between the two colors. + * + * @type {(MultiplyOperation|MixOperation|AddOperation)} + * @default MultiplyOperation + */ + this.combine = MultiplyOperation; + + /** + * How much the environment map affects the surface. + * The valid range is between `0` (no reflections) and `1` (full reflections). + * + * @type {number} + * @default 1 + */ + this.reflectivity = 1; + + /** + * Scales the effect of the environment map by multiplying its color. + * + * @type {number} + * @default 1 + */ + this.envMapIntensity = 1.0; + + /** + * The index of refraction (IOR) of air (approximately 1) divided by the + * index of refraction of the material. It is used with environment mapping + * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}. + * The refraction ratio should not exceed `1`. + * + * @type {number} + * @default 0.98 + */ + this.refractionRatio = 0.98; + + /** + * Renders the geometry as a wireframe. + * + * @type {boolean} + * @default false + */ + this.wireframe = false; + + /** + * Controls the thickness of the wireframe. + * + * Can only be used with {@link SVGRenderer}. + * + * @type {number} + * @default 1 + */ + this.wireframeLinewidth = 1; + + /** + * Defines appearance of wireframe ends. + * + * Can only be used with {@link SVGRenderer}. + * + * @type {('round'|'bevel'|'miter')} + * @default 'round' + */ + this.wireframeLinecap = 'round'; + + /** + * Defines appearance of wireframe joints. + * + * Can only be used with {@link SVGRenderer}. + * + * @type {('round'|'bevel'|'miter')} + * @default 'round' + */ + this.wireframeLinejoin = 'round'; + + /** + * Whether the material is rendered with flat shading or not. + * + * @type {boolean} + * @default false + */ + this.flatShading = false; + + /** + * Whether the material is affected by fog or not. + * + * @type {boolean} + * @default true + */ + this.fog = true; + + this.setValues( parameters ); + + } + + copy( source ) { + + super.copy( source ); + + this.color.copy( source.color ); + this.specular.copy( source.specular ); + this.shininess = source.shininess; + + this.map = source.map; + + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; + + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + + this.emissive.copy( source.emissive ); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; + + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy( source.normalScale ); + + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + + this.specularMap = source.specularMap; + + this.alphaMap = source.alphaMap; + + this.envMap = source.envMap; + this.envMapRotation.copy( source.envMapRotation ); + this.combine = source.combine; + this.reflectivity = source.reflectivity; + this.envMapIntensity = source.envMapIntensity; + this.refractionRatio = source.refractionRatio; + + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + + this.flatShading = source.flatShading; + + this.fog = source.fog; + + return this; + + } + +} + +/** + * A material implementing toon shading. + * + * @augments Material + * @demo scenes/material-browser.html#MeshToonMaterial + */ +class MeshToonMaterial extends Material { + + /** + * Constructs a new mesh toon material. + * + * @param {Object} [parameters] - An object with one or more properties + * defining the material's appearance. Any property of the material + * (including any property from inherited materials) can be passed + * in here. Color values can be passed any type of value accepted + * by {@link Color#set}. + */ + constructor( parameters ) { + + super(); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isMeshToonMaterial = true; + + this.defines = { 'TOON': '' }; + + this.type = 'MeshToonMaterial'; + + /** + * Color of the material. + * + * @type {Color} + * @default (1,1,1) + */ + this.color = new Color( 0xffffff ); + + /** + * The color map. May optionally include an alpha channel, typically combined + * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map + * color is modulated by the diffuse `color`. + * + * `map` represents color data, and the texture must be assigned a + * {@link Texture#colorSpace}. Most `map` textures set + * `texture.colorSpace = SRGBColorSpace`. + * + * @type {?Texture} + * @default null + */ + this.map = null; + + /** + * Gradient map for toon shading. It's required to set + * {@link Texture#minFilter} and {@link Texture#magFilter} to {@link NearestFilter} + * when using this type of texture. + * + * `gradientMap` represents non-color data. Any texture assigned must have + * `texture.colorSpace = NoColorSpace` (default). + * + * @type {?Texture} + * @default null + */ + this.gradientMap = null; + + /** + * The light map. Requires a second set of UVs. + * + * `lightMap` represents pre-baked illuminance data, and the texture must be assigned + * a {@link Texture#colorSpace}. Most `lightMap` textures set + * `texture.colorSpace = LinearSRGBColorSpace` and use float-type formats + * such as `.exr` or `.hdr`. + * + * @type {?Texture} + * @default null + */ + this.lightMap = null; + + /** + * Intensity of the baked light. + * + * @type {number} + * @default 1 + */ + this.lightMapIntensity = 1.0; + + /** + * The red channel of this texture is used as the ambient occlusion map. + * Requires a second set of UVs. + * + * `aoMap` represents non-color data. Any texture assigned must have + * `texture.colorSpace = NoColorSpace` (default). + * + * @type {?Texture} + * @default null + */ + this.aoMap = null; + + /** + * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0` + * disables ambient occlusion. Where intensity is `1` and the AO map's + * red channel is also `1`, ambient light is fully occluded on a surface. + * + * @type {number} + * @default 1 + */ + this.aoMapIntensity = 1.0; + + /** + * Emissive (light) color of the material, essentially a solid color + * unaffected by other lighting. + * + * @type {Color} + * @default (0,0,0) + */ + this.emissive = new Color( 0x000000 ); + + /** + * Intensity of the emissive light. Modulates the emissive color. + * + * @type {number} + * @default 1 + */ + this.emissiveIntensity = 1.0; + + /** + * Set emissive (glow) map. The emissive map color is modulated by the + * emissive color and the emissive intensity. If you have an emissive map, + * be sure to set the emissive color to something other than black. + * + * `emissiveMap` represents color data, and the texture must be assigned a + * {@link Texture#colorSpace}. Most `emissiveMap` textures set + * `texture.colorSpace = SRGBColorSpace`. + * + * @type {?Texture} + * @default null + */ + this.emissiveMap = null; + + /** + * The texture to create a bump map. The black and white values map to the + * perceived depth in relation to the lights. Bump doesn't actually affect + * the geometry of the object, only the lighting. If a normal map is defined + * this will be ignored. + * + * `bumpMap` represents non-color data. Any texture assigned must have + * `texture.colorSpace = NoColorSpace` (default). + * + * @type {?Texture} + * @default null + */ + this.bumpMap = null; + + /** + * How much the bump map affects the material. Typical range is `[0,1]`. + * + * @type {number} + * @default 1 + */ + this.bumpScale = 1; + + /** + * The texture to create a normal map. The RGB values affect the surface + * normal for each pixel fragment and change the way the color is lit. Normal + * maps do not change the actual shape of the surface, only the lighting. In + * case the material has a normal map authored using the left handed + * convention, the `y` component of `normalScale` should be negated to compensate + * for the different handedness. + * + * `normalMap` represents non-color data. Any texture assigned must have + * `texture.colorSpace = NoColorSpace` (default). + * + * @type {?Texture} + * @default null + */ + this.normalMap = null; + + /** + * The type of normal map. + * + * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)} + * @default TangentSpaceNormalMap + */ + this.normalMapType = TangentSpaceNormalMap; + + /** + * How much the normal map affects the material. Typical value range is `[0,1]`. + * + * @type {Vector2} + * @default (1,1) + */ + this.normalScale = new Vector2( 1, 1 ); + + /** + * The displacement map affects the position of the mesh's vertices. Unlike + * other maps which only affect the light and shade of the material the + * displaced vertices can cast shadows, block other objects, and otherwise + * act as real geometry. The displacement texture is an image where the value + * of each pixel (white being the highest) is mapped against, and + * repositions, the vertices of the mesh. For best results, pair a + * displacement map with a matching normal map, since the renderer can + * not recompute surface normals from the displaced vertices. + * + * `displacementMap` represents non-color data. Any texture assigned must have + * `texture.colorSpace = NoColorSpace` (default). + * + * @type {?Texture} + * @default null + */ + this.displacementMap = null; + + /** + * How much the displacement map affects the mesh (where black is no + * displacement, and white is maximum displacement). Without a displacement + * map set, this value is not applied. + * + * @type {number} + * @default 0 + */ + this.displacementScale = 1; + + /** + * The offset of the displacement map's values on the mesh's vertices. + * The bias is added to the scaled sample of the displacement map. + * Without a displacement map set, this value is not applied. + * + * @type {number} + * @default 0 + */ + this.displacementBias = 0; + + /** + * The alpha map is a grayscale texture that controls the opacity across the + * surface (black: fully transparent; white: fully opaque). + * + * Only the color of the texture is used, ignoring the alpha channel if one + * exists. For RGB and RGBA textures, the renderer will use the green channel + * when sampling this texture due to the extra bit of precision provided for + * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and + * luminance/alpha textures will also still work as expected. + * + * `alphaMap` represents non-color data. Any texture assigned must have + * `texture.colorSpace = NoColorSpace` (default). + * + * @type {?Texture} + * @default null + */ + this.alphaMap = null; + + /** + * Renders the geometry as a wireframe. + * + * @type {boolean} + * @default false + */ + this.wireframe = false; + + /** + * Controls the thickness of the wireframe. + * + * Can only be used with {@link SVGRenderer}. + * + * @type {number} + * @default 1 + */ + this.wireframeLinewidth = 1; + + /** + * Defines appearance of wireframe ends. + * + * Can only be used with {@link SVGRenderer}. + * + * @type {('round'|'bevel'|'miter')} + * @default 'round' + */ + this.wireframeLinecap = 'round'; + + /** + * Defines appearance of wireframe joints. + * + * Can only be used with {@link SVGRenderer}. + * + * @type {('round'|'bevel'|'miter')} + * @default 'round' + */ + this.wireframeLinejoin = 'round'; + + /** + * Whether the material is affected by fog or not. + * + * @type {boolean} + * @default true + */ + this.fog = true; + + this.setValues( parameters ); + + } + + copy( source ) { + + super.copy( source ); + + this.color.copy( source.color ); + + this.map = source.map; + this.gradientMap = source.gradientMap; + + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; + + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + + this.emissive.copy( source.emissive ); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; + + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy( source.normalScale ); + + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + + this.alphaMap = source.alphaMap; + + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + + this.fog = source.fog; + + return this; + + } + +} + +/** + * A material that maps the normal vectors to RGB colors. + * + * @augments Material + * @demo scenes/material-browser.html#MeshNormalMaterial + */ +class MeshNormalMaterial extends Material { + + /** + * Constructs a new mesh normal material. + * + * @param {Object} [parameters] - An object with one or more properties + * defining the material's appearance. Any property of the material + * (including any property from inherited materials) can be passed + * in here. Color values can be passed any type of value accepted + * by {@link Color#set}. + */ + constructor( parameters ) { + + super(); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isMeshNormalMaterial = true; + + this.type = 'MeshNormalMaterial'; + + /** + * The texture to create a bump map. The black and white values map to the + * perceived depth in relation to the lights. Bump doesn't actually affect + * the geometry of the object, only the lighting. If a normal map is defined + * this will be ignored. + * + * `bumpMap` represents non-color data. Any texture assigned must have + * `texture.colorSpace = NoColorSpace` (default). + * + * @type {?Texture} + * @default null + */ + this.bumpMap = null; + + /** + * How much the bump map affects the material. Typical range is `[0,1]`. + * + * @type {number} + * @default 1 + */ + this.bumpScale = 1; + + /** + * The texture to create a normal map. The RGB values affect the surface + * normal for each pixel fragment and change the way the color is lit. Normal + * maps do not change the actual shape of the surface, only the lighting. In + * case the material has a normal map authored using the left handed + * convention, the `y` component of `normalScale` should be negated to compensate + * for the different handedness. + * + * `normalMap` represents non-color data. Any texture assigned must have + * `texture.colorSpace = NoColorSpace` (default). + * + * @type {?Texture} + * @default null + */ + this.normalMap = null; + + /** + * The type of normal map. + * + * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)} + * @default TangentSpaceNormalMap + */ + this.normalMapType = TangentSpaceNormalMap; + + /** + * How much the normal map affects the material. Typical value range is `[0,1]`. + * + * @type {Vector2} + * @default (1,1) + */ + this.normalScale = new Vector2( 1, 1 ); + + /** + * The displacement map affects the position of the mesh's vertices. Unlike + * other maps which only affect the light and shade of the material the + * displaced vertices can cast shadows, block other objects, and otherwise + * act as real geometry. The displacement texture is an image where the value + * of each pixel (white being the highest) is mapped against, and + * repositions, the vertices of the mesh. For best results, pair a + * displacement map with a matching normal map, since the renderer can + * not recompute surface normals from the displaced vertices. + * + * @type {?Texture} + * @default null + */ + this.displacementMap = null; + + /** + * How much the displacement map affects the mesh (where black is no + * displacement, and white is maximum displacement). Without a displacement + * map set, this value is not applied. + * + * @type {number} + * @default 0 + */ + this.displacementScale = 1; + + /** + * The offset of the displacement map's values on the mesh's vertices. + * The bias is added to the scaled sample of the displacement map. + * Without a displacement map set, this value is not applied. + * + * @type {number} + * @default 0 + */ + this.displacementBias = 0; + + /** + * Renders the geometry as a wireframe. + * + * @type {boolean} + * @default false + */ + this.wireframe = false; + + /** + * Controls the thickness of the wireframe. + * + * WebGL and WebGPU ignore this property and always render + * 1 pixel wide lines. + * + * @type {number} + * @default 1 + */ + this.wireframeLinewidth = 1; + + /** + * Whether the material is rendered with flat shading or not. + * + * @type {boolean} + * @default false + */ + this.flatShading = false; + + this.setValues( parameters ); + + } + + copy( source ) { + + super.copy( source ); + + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy( source.normalScale ); + + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + + this.flatShading = source.flatShading; + + return this; + + } + +} + +/** + * A material for non-shiny surfaces, without specular highlights. + * + * The material uses a non-physically based [Lambertian](https://en.wikipedia.org/wiki/Lambertian_reflectance) + * model for calculating reflectance. This can simulate some surfaces (such + * as untreated wood or stone) well, but cannot simulate shiny surfaces with + * specular highlights (such as varnished wood). `MeshLambertMaterial` uses per-fragment + * shading. + * + * Due to the simplicity of the reflectance and illumination models, + * performance will be greater when using this material over the + * {@link MeshPhongMaterial}, {@link MeshStandardMaterial} or + * {@link MeshPhysicalMaterial}, at the cost of some graphical accuracy. + * + * @augments Material + * @demo scenes/material-browser.html#MeshLambertMaterial + */ +class MeshLambertMaterial extends Material { + + /** + * Constructs a new mesh lambert material. + * + * @param {Object} [parameters] - An object with one or more properties + * defining the material's appearance. Any property of the material + * (including any property from inherited materials) can be passed + * in here. Color values can be passed any type of value accepted + * by {@link Color#set}. + */ + constructor( parameters ) { + + super(); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isMeshLambertMaterial = true; + + this.type = 'MeshLambertMaterial'; + + /** + * Color of the material. + * + * @type {Color} + * @default (1,1,1) + */ + this.color = new Color( 0xffffff ); // diffuse + + /** + * The color map. May optionally include an alpha channel, typically combined + * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map + * color is modulated by the diffuse `color`. + * + * `map` represents color data, and the texture must be assigned a + * {@link Texture#colorSpace}. Most `map` textures set + * `texture.colorSpace = SRGBColorSpace`. + * + * @type {?Texture} + * @default null + */ + this.map = null; + + /** + * The light map. Requires a second set of UVs. + * + * `lightMap` represents pre-baked illuminance data, and the texture must be assigned + * a {@link Texture#colorSpace}. Most `lightMap` textures set + * `texture.colorSpace = LinearSRGBColorSpace` and use float-type formats + * such as `.exr` or `.hdr`. + * + * @type {?Texture} + * @default null + */ + this.lightMap = null; + + /** + * Intensity of the baked light. + * + * @type {number} + * @default 1 + */ + this.lightMapIntensity = 1.0; + + /** + * The red channel of this texture is used as the ambient occlusion map. + * Requires a second set of UVs. + * + * `aoMap` represents non-color data. Any texture assigned must have + * `texture.colorSpace = NoColorSpace` (default). + * + * @type {?Texture} + * @default null + */ + this.aoMap = null; + + /** + * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0` + * disables ambient occlusion. Where intensity is `1` and the AO map's + * red channel is also `1`, ambient light is fully occluded on a surface. + * + * @type {number} + * @default 1 + */ + this.aoMapIntensity = 1.0; + + /** + * Emissive (light) color of the material, essentially a solid color + * unaffected by other lighting. + * + * @type {Color} + * @default (0,0,0) + */ + this.emissive = new Color( 0x000000 ); + + /** + * Intensity of the emissive light. Modulates the emissive color. + * + * @type {number} + * @default 1 + */ + this.emissiveIntensity = 1.0; + + /** + * Set emissive (glow) map. The emissive map color is modulated by the + * emissive color and the emissive intensity. If you have an emissive map, + * be sure to set the emissive color to something other than black. + * + * `emissiveMap` represents color data, and the texture must be assigned a + * {@link Texture#colorSpace}. Most `emissiveMap` textures set + * `texture.colorSpace = SRGBColorSpace`. + * + * @type {?Texture} + * @default null + */ + this.emissiveMap = null; + + /** + * The texture to create a bump map. The black and white values map to the + * perceived depth in relation to the lights. Bump doesn't actually affect + * the geometry of the object, only the lighting. If a normal map is defined + * this will be ignored. + * + * `bumpMap` represents non-color data. Any texture assigned must have + * `texture.colorSpace = NoColorSpace` (default). + * + * @type {?Texture} + * @default null + */ + this.bumpMap = null; + + /** + * How much the bump map affects the material. Typical range is `[0,1]`. + * + * @type {number} + * @default 1 + */ + this.bumpScale = 1; + + /** + * The texture to create a normal map. The RGB values affect the surface + * normal for each pixel fragment and change the way the color is lit. Normal + * maps do not change the actual shape of the surface, only the lighting. In + * case the material has a normal map authored using the left handed + * convention, the `y` component of `normalScale` should be negated to compensate + * for the different handedness. + * + * `normalMap` represents non-color data. Any texture assigned must have + * `texture.colorSpace = NoColorSpace` (default). + * + * @type {?Texture} + * @default null + */ + this.normalMap = null; + + /** + * The type of normal map. + * + * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)} + * @default TangentSpaceNormalMap + */ + this.normalMapType = TangentSpaceNormalMap; + + /** + * How much the normal map affects the material. Typical value range is `[0,1]`. + * + * @type {Vector2} + * @default (1,1) + */ + this.normalScale = new Vector2( 1, 1 ); + + /** + * The displacement map affects the position of the mesh's vertices. Unlike + * other maps which only affect the light and shade of the material the + * displaced vertices can cast shadows, block other objects, and otherwise + * act as real geometry. The displacement texture is an image where the value + * of each pixel (white being the highest) is mapped against, and + * repositions, the vertices of the mesh. For best results, pair a + * displacement map with a matching normal map, since the renderer can + * not recompute surface normals from the displaced vertices. + * + * `displacementMap` represents non-color data. Any texture assigned must have + * `texture.colorSpace = NoColorSpace` (default). + * + * @type {?Texture} + * @default null + */ + this.displacementMap = null; + + /** + * How much the displacement map affects the mesh (where black is no + * displacement, and white is maximum displacement). Without a displacement + * map set, this value is not applied. + * + * @type {number} + * @default 0 + */ + this.displacementScale = 1; + + /** + * The offset of the displacement map's values on the mesh's vertices. + * The bias is added to the scaled sample of the displacement map. + * Without a displacement map set, this value is not applied. + * + * @type {number} + * @default 0 + */ + this.displacementBias = 0; + + /** + * Specular map used by the material. + * + * `specularMap` represents color data, and the texture must be assigned a + * {@link Texture#colorSpace}. Most `specularMap` textures set + * `texture.colorSpace = SRGBColorSpace`. + * + * @type {?Texture} + * @default null + */ + this.specularMap = null; + + /** + * The alpha map is a grayscale texture that controls the opacity across the + * surface (black: fully transparent; white: fully opaque). + * + * Only the color of the texture is used, ignoring the alpha channel if one + * exists. For RGB and RGBA textures, the renderer will use the green channel + * when sampling this texture due to the extra bit of precision provided for + * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and + * luminance/alpha textures will also still work as expected. + * + * `alphaMap` represents non-color data. Any texture assigned must have + * `texture.colorSpace = NoColorSpace` (default). + * + * @type {?Texture} + * @default null + */ + this.alphaMap = null; + + /** + * The environment map. + * + * `envMap` represents luminance data, and the texture must be assigned + * a {@link Texture#colorSpace}. Most `envMap` textures set + * `texture.colorSpace = LinearSRGBColorSpace` and use float-type formats + * such as `.exr` or `.hdr`. + * + * @type {?Texture} + * @default null + */ + this.envMap = null; + + /** + * The rotation of the environment map in radians. + * + * @type {Euler} + * @default (0,0,0) + */ + this.envMapRotation = new Euler(); + + /** + * How to combine the result of the surface's color with the environment map, if any. + * + * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to + * blend between the two colors. + * + * @type {(MultiplyOperation|MixOperation|AddOperation)} + * @default MultiplyOperation + */ + this.combine = MultiplyOperation; + + /** + * How much the environment map affects the surface. + * The valid range is between `0` (no reflections) and `1` (full reflections). + * + * @type {number} + * @default 1 + */ + this.reflectivity = 1; + + /** + * Scales the effect of the environment map by multiplying its color. + * + * @type {number} + * @default 1 + */ + this.envMapIntensity = 1.0; + + /** + * The index of refraction (IOR) of air (approximately 1) divided by the + * index of refraction of the material. It is used with environment mapping + * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}. + * The refraction ratio should not exceed `1`. + * + * @type {number} + * @default 0.98 + */ + this.refractionRatio = 0.98; + + /** + * Renders the geometry as a wireframe. + * + * @type {boolean} + * @default false + */ + this.wireframe = false; + + /** + * Controls the thickness of the wireframe. + * + * Can only be used with {@link SVGRenderer}. + * + * @type {number} + * @default 1 + */ + this.wireframeLinewidth = 1; + + /** + * Defines appearance of wireframe ends. + * + * Can only be used with {@link SVGRenderer}. + * + * @type {('round'|'bevel'|'miter')} + * @default 'round' + */ + this.wireframeLinecap = 'round'; + + /** + * Defines appearance of wireframe joints. + * + * Can only be used with {@link SVGRenderer}. + * + * @type {('round'|'bevel'|'miter')} + * @default 'round' + */ + this.wireframeLinejoin = 'round'; + + /** + * Whether the material is rendered with flat shading or not. + * + * @type {boolean} + * @default false + */ + this.flatShading = false; + + /** + * Whether the material is affected by fog or not. + * + * @type {boolean} + * @default true + */ + this.fog = true; + + this.setValues( parameters ); + + } + + copy( source ) { + + super.copy( source ); + + this.color.copy( source.color ); + + this.map = source.map; + + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; + + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + + this.emissive.copy( source.emissive ); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; + + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy( source.normalScale ); + + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + + this.specularMap = source.specularMap; + + this.alphaMap = source.alphaMap; + + this.envMap = source.envMap; + this.envMapRotation.copy( source.envMapRotation ); + this.combine = source.combine; + this.reflectivity = source.reflectivity; + this.envMapIntensity = source.envMapIntensity; + this.refractionRatio = source.refractionRatio; + + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + + this.flatShading = source.flatShading; + + this.fog = source.fog; + + return this; + + } + +} + +/** + * A material for drawing geometry by depth. Depth is based off of the camera + * near and far plane. White is nearest, black is farthest. + * + * @augments Material + * @demo scenes/material-browser.html#MeshDepthMaterial + */ +class MeshDepthMaterial extends Material { + + /** + * Constructs a new mesh depth material. + * + * @param {Object} [parameters] - An object with one or more properties + * defining the material's appearance. Any property of the material + * (including any property from inherited materials) can be passed + * in here. Color values can be passed any type of value accepted + * by {@link Color#set}. + */ + constructor( parameters ) { + + super(); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isMeshDepthMaterial = true; + + this.type = 'MeshDepthMaterial'; + + /** + * Type for depth packing. + * + * @type {(BasicDepthPacking|RGBADepthPacking|RGBDepthPacking|RGDepthPacking)} + * @default BasicDepthPacking + */ + this.depthPacking = BasicDepthPacking; + + /** + * The color map. May optionally include an alpha channel, typically combined + * with {@link Material#transparent} or {@link Material#alphaTest}. + * + * `map` represents color data, and the texture must be assigned a + * {@link Texture#colorSpace}. Most `map` textures set + * `texture.colorSpace = SRGBColorSpace`. + * + * @type {?Texture} + * @default null + */ + this.map = null; + + /** + * The alpha map is a grayscale texture that controls the opacity across the + * surface (black: fully transparent; white: fully opaque). + * + * Only the color of the texture is used, ignoring the alpha channel if one + * exists. For RGB and RGBA textures, the renderer will use the green channel + * when sampling this texture due to the extra bit of precision provided for + * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and + * luminance/alpha textures will also still work as expected. + * + * `alphaMap` represents non-color data. Any texture assigned must have + * `texture.colorSpace = NoColorSpace` (default). + * + * @type {?Texture} + * @default null + */ + this.alphaMap = null; + + /** + * The displacement map affects the position of the mesh's vertices. Unlike + * other maps which only affect the light and shade of the material the + * displaced vertices can cast shadows, block other objects, and otherwise + * act as real geometry. The displacement texture is an image where the value + * of each pixel (white being the highest) is mapped against, and + * repositions, the vertices of the mesh. + * + * `displacementMap` represents non-color data. Any texture assigned must have + * `texture.colorSpace = NoColorSpace` (default). + * + * @type {?Texture} + * @default null + */ + this.displacementMap = null; + + /** + * How much the displacement map affects the mesh (where black is no + * displacement, and white is maximum displacement). Without a displacement + * map set, this value is not applied. + * + * @type {number} + * @default 0 + */ + this.displacementScale = 1; + + /** + * The offset of the displacement map's values on the mesh's vertices. + * The bias is added to the scaled sample of the displacement map. + * Without a displacement map set, this value is not applied. + * + * @type {number} + * @default 0 + */ + this.displacementBias = 0; + + /** + * Renders the geometry as a wireframe. + * + * @type {boolean} + * @default false + */ + this.wireframe = false; + + /** + * Controls the thickness of the wireframe. + * + * WebGL and WebGPU ignore this property and always render + * 1 pixel wide lines. + * + * @type {number} + * @default 1 + */ + this.wireframeLinewidth = 1; + + this.setValues( parameters ); + + } + + copy( source ) { + + super.copy( source ); + + this.depthPacking = source.depthPacking; + + this.map = source.map; + + this.alphaMap = source.alphaMap; + + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + + return this; + + } + +} + +/** + * A material used internally for implementing shadow mapping with + * point lights. + * + * Can also be used to customize the shadow casting of an object by assigning + * an instance of `MeshDistanceMaterial` to {@link Object3D#customDistanceMaterial}. + * The following examples demonstrates this approach in order to ensure + * transparent parts of objects do not cast shadows. + * + * @augments Material + */ +class MeshDistanceMaterial extends Material { + + /** + * Constructs a new mesh distance material. + * + * @param {Object} [parameters] - An object with one or more properties + * defining the material's appearance. Any property of the material + * (including any property from inherited materials) can be passed + * in here. Color values can be passed any type of value accepted + * by {@link Color#set}. + */ + constructor( parameters ) { + + super(); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isMeshDistanceMaterial = true; + + this.type = 'MeshDistanceMaterial'; + + /** + * The color map. May optionally include an alpha channel, typically combined + * with {@link Material#transparent} or {@link Material#alphaTest}. + * + * `map` represents color data, and the texture must be assigned a + * {@link Texture#colorSpace}. Most `map` textures set + * `texture.colorSpace = SRGBColorSpace`. + * + * @type {?Texture} + * @default null + */ + this.map = null; + + /** + * The alpha map is a grayscale texture that controls the opacity across the + * surface (black: fully transparent; white: fully opaque). + * + * Only the color of the texture is used, ignoring the alpha channel if one + * exists. For RGB and RGBA textures, the renderer will use the green channel + * when sampling this texture due to the extra bit of precision provided for + * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and + * luminance/alpha textures will also still work as expected. + * + * `alphaMap` represents non-color data. Any texture assigned must have + * `texture.colorSpace = NoColorSpace` (default). + * + * @type {?Texture} + * @default null + */ + this.alphaMap = null; + + /** + * The displacement map affects the position of the mesh's vertices. Unlike + * other maps which only affect the light and shade of the material the + * displaced vertices can cast shadows, block other objects, and otherwise + * act as real geometry. The displacement texture is an image where the value + * of each pixel (white being the highest) is mapped against, and + * repositions, the vertices of the mesh. + * + * `displacementMap` represents non-color data. Any texture assigned must have + * `texture.colorSpace = NoColorSpace` (default). + * + * @type {?Texture} + * @default null + */ + this.displacementMap = null; + + /** + * How much the displacement map affects the mesh (where black is no + * displacement, and white is maximum displacement). Without a displacement + * map set, this value is not applied. + * + * @type {number} + * @default 0 + */ + this.displacementScale = 1; + + /** + * The offset of the displacement map's values on the mesh's vertices. + * The bias is added to the scaled sample of the displacement map. + * Without a displacement map set, this value is not applied. + * + * @type {number} + * @default 0 + */ + this.displacementBias = 0; + + this.setValues( parameters ); + + } + + copy( source ) { + + super.copy( source ); + + this.map = source.map; + + this.alphaMap = source.alphaMap; + + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + + return this; + + } + +} + +/** + * This material is defined by a MatCap (or Lit Sphere) texture, which encodes the + * material color and shading. + * + * `MeshMatcapMaterial` does not respond to lights since the matcap image file encodes + * baked lighting. It will cast a shadow onto an object that receives shadows + * (and shadow clipping works), but it will not self-shadow or receive + * shadows. + * + * @augments Material + * @demo scenes/material-browser.html#MeshMatcapMaterial + */ +class MeshMatcapMaterial extends Material { + + /** + * Constructs a new mesh matcap material. + * + * @param {Object} [parameters] - An object with one or more properties + * defining the material's appearance. Any property of the material + * (including any property from inherited materials) can be passed + * in here. Color values can be passed any type of value accepted + * by {@link Color#set}. + */ + constructor( parameters ) { + + super(); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isMeshMatcapMaterial = true; + + this.defines = { 'MATCAP': '' }; + + this.type = 'MeshMatcapMaterial'; + + /** + * Color of the material. + * + * @type {Color} + * @default (1,1,1) + */ + this.color = new Color( 0xffffff ); // diffuse + + /** + * The matcap map. + * + * `matcap` represents luminance data, and the texture must be assigned + * a {@link Texture#colorSpace}. HDR `matcap` textures (e.g. `.exr`) + * typically set `texture.colorSpace = LinearSRGBColorSpace`, while LDR + * `matcap` textures (e.g. `.png`, `.jpg`, `.webp`) typically set + * `texture.colorSpace = SRGBColorSpace`. + * + * @type {?Texture} + * @default null + */ + this.matcap = null; + + /** + * The color map. May optionally include an alpha channel, typically combined + * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map + * color is modulated by the diffuse `color`. + * + * `map` represents color data, and the texture must be assigned a + * {@link Texture#colorSpace}. Most `map` textures set + * `texture.colorSpace = SRGBColorSpace`. + * + * @type {?Texture} + * @default null + */ + this.map = null; + + /** + * The texture to create a bump map. The black and white values map to the + * perceived depth in relation to the lights. Bump doesn't actually affect + * the geometry of the object, only the lighting. If a normal map is defined + * this will be ignored. + * + * `bumpMap` represents non-color data. Any texture assigned must have + * `texture.colorSpace = NoColorSpace` (default). + * + * @type {?Texture} + * @default null + */ + this.bumpMap = null; + + /** + * How much the bump map affects the material. Typical range is `[0,1]`. + * + * @type {number} + * @default 1 + */ + this.bumpScale = 1; + + /** + * The texture to create a normal map. The RGB values affect the surface + * normal for each pixel fragment and change the way the color is lit. Normal + * maps do not change the actual shape of the surface, only the lighting. In + * case the material has a normal map authored using the left handed + * convention, the `y` component of `normalScale` should be negated to compensate + * for the different handedness. + * + * `normalMap` represents non-color data. Any texture assigned must have + * `texture.colorSpace = NoColorSpace` (default). + * + * @type {?Texture} + * @default null + */ + this.normalMap = null; + + /** + * The type of normal map. + * + * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)} + * @default TangentSpaceNormalMap + */ + this.normalMapType = TangentSpaceNormalMap; + + /** + * How much the normal map affects the material. Typical value range is `[0,1]`. + * + * @type {Vector2} + * @default (1,1) + */ + this.normalScale = new Vector2( 1, 1 ); + + /** + * The displacement map affects the position of the mesh's vertices. Unlike + * other maps which only affect the light and shade of the material the + * displaced vertices can cast shadows, block other objects, and otherwise + * act as real geometry. The displacement texture is an image where the value + * of each pixel (white being the highest) is mapped against, and + * repositions, the vertices of the mesh. For best results, pair a + * displacement map with a matching normal map, since the renderer can + * not recompute surface normals from the displaced vertices. + * + * `displacementMap` represents non-color data. Any texture assigned must have + * `texture.colorSpace = NoColorSpace` (default). + * + * @type {?Texture} + * @default null + */ + this.displacementMap = null; + + /** + * How much the displacement map affects the mesh (where black is no + * displacement, and white is maximum displacement). Without a displacement + * map set, this value is not applied. + * + * @type {number} + * @default 0 + */ + this.displacementScale = 1; + + /** + * The offset of the displacement map's values on the mesh's vertices. + * The bias is added to the scaled sample of the displacement map. + * Without a displacement map set, this value is not applied. + * + * @type {number} + * @default 0 + */ + this.displacementBias = 0; + + /** + * The alpha map is a grayscale texture that controls the opacity across the + * surface (black: fully transparent; white: fully opaque). + * + * Only the color of the texture is used, ignoring the alpha channel if one + * exists. For RGB and RGBA textures, the renderer will use the green channel + * when sampling this texture due to the extra bit of precision provided for + * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and + * luminance/alpha textures will also still work as expected. + * + * `alphaMap` represents non-color data. Any texture assigned must have + * `texture.colorSpace = NoColorSpace` (default). + * + * @type {?Texture} + * @default null + */ + this.alphaMap = null; + + /** + * Renders the geometry as a wireframe. + * + * @type {boolean} + * @default false + */ + this.wireframe = false; + + /** + * Controls the thickness of the wireframe. + * + * Can only be used with {@link SVGRenderer}. + * + * @type {number} + * @default 1 + */ + this.wireframeLinewidth = 1; + + /** + * Whether the material is rendered with flat shading or not. + * + * @type {boolean} + * @default false + */ + this.flatShading = false; + + /** + * Whether the material is affected by fog or not. + * + * @type {boolean} + * @default true + */ + this.fog = true; + + this.setValues( parameters ); + + } + + + copy( source ) { + + super.copy( source ); + + this.defines = { 'MATCAP': '' }; + + this.color.copy( source.color ); + + this.matcap = source.matcap; + + this.map = source.map; + + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy( source.normalScale ); + + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + + this.alphaMap = source.alphaMap; + + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + + this.flatShading = source.flatShading; + + this.fog = source.fog; + + return this; + + } + +} + +/** + * A material for rendering line primitives. + * + * Materials define the appearance of renderable 3D objects. + * + * ```js + * const material = new THREE.LineDashedMaterial( { + * color: 0xffffff, + * scale: 1, + * dashSize: 3, + * gapSize: 1, + * } ); + * ``` + * + * @augments LineBasicMaterial + */ +class LineDashedMaterial extends LineBasicMaterial { + + /** + * Constructs a new line dashed material. + * + * @param {Object} [parameters] - An object with one or more properties + * defining the material's appearance. Any property of the material + * (including any property from inherited materials) can be passed + * in here. Color values can be passed any type of value accepted + * by {@link Color#set}. + */ + constructor( parameters ) { + + super(); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isLineDashedMaterial = true; + this.type = 'LineDashedMaterial'; + + /** + * The scale of the dashed part of a line. + * + * @type {number} + * @default 1 + */ + this.scale = 1; + + /** + * The size of the dash. This is both the gap with the stroke. + * + * @type {number} + * @default 3 + */ + this.dashSize = 3; + + /** + * The size of the gap. + * + * @type {number} + * @default 1 + */ + this.gapSize = 1; + + this.setValues( parameters ); + + } + + copy( source ) { + + super.copy( source ); + + this.scale = source.scale; + this.dashSize = source.dashSize; + this.gapSize = source.gapSize; + + return this; + + } + +} + +/** + * Converts an array to a specific type. + * + * @param {TypedArray|Array} array - The array to convert. + * @param {TypedArray.constructor} type - The constructor of a typed array that defines the new type. + * @return {TypedArray} The converted array. + */ +function convertArray( array, type ) { + + if ( ! array || array.constructor === type ) return array; + + if ( typeof type.BYTES_PER_ELEMENT === 'number' ) { + + return new type( array ); // create typed array + + } + + return Array.prototype.slice.call( array ); // create Array + +} + +/** + * Returns `true` if the given keyframe track settings hold Bezier tangent data. + * + * @param {?Object} settings - The settings of a keyframe track. + * @return {boolean} Whether both tangent arrays are defined or not. + */ +function hasTangents( settings ) { + + return settings !== undefined && settings.inTangents !== undefined && settings.outTangents !== undefined; + +} + +/** + * Returns an array by which times and values can be sorted. + * + * @param {Array} times - The keyframe time values. + * @return {Array} The array. + */ +function getKeyframeOrder( times ) { + + function compareTime( i, j ) { + + return times[ i ] - times[ j ]; + + } + + const n = times.length; + const result = new Array( n ); + for ( let i = 0; i !== n; ++ i ) result[ i ] = i; + + result.sort( compareTime ); + + return result; + +} + +/** + * Sorts the given array by the previously computed order via `getKeyframeOrder()`. + * + * @param {Array} values - The values to sort. + * @param {number} stride - The stride. + * @param {Array} order - The sort order. + * @return {Array} The sorted values. + */ +function sortedArray( values, stride, order ) { + + const nValues = values.length; + const result = new values.constructor( nValues ); + + for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) { + + const srcOffset = order[ i ] * stride; + + for ( let j = 0; j !== stride; ++ j ) { + + result[ dstOffset ++ ] = values[ srcOffset + j ]; + + } + + } + + return result; + +} + +/** + * Used for parsing AOS keyframe formats. + * + * @param {Array} jsonKeys - A list of JSON keyframes. + * @param {Array} times - This array will be filled with keyframe times by this function. + * @param {Array} values - This array will be filled with keyframe values by this function. + * @param {string} valuePropertyName - The name of the property to use. + */ +function flattenJSON( jsonKeys, times, values, valuePropertyName ) { + + let i = 1, key = jsonKeys[ 0 ]; + + while ( key !== undefined && key[ valuePropertyName ] === undefined ) { + + key = jsonKeys[ i ++ ]; + + } + + if ( key === undefined ) return; // no data + + let value = key[ valuePropertyName ]; + if ( value === undefined ) return; // no data + + if ( Array.isArray( value ) ) { + + do { + + value = key[ valuePropertyName ]; + + if ( value !== undefined ) { + + times.push( key.time ); + values.push( ...value ); // push all elements + + } + + key = jsonKeys[ i ++ ]; + + } while ( key !== undefined ); + + } else if ( value.toArray !== undefined ) { + + // ...assume THREE.Math-ish + + do { + + value = key[ valuePropertyName ]; + + if ( value !== undefined ) { + + times.push( key.time ); + value.toArray( values, values.length ); + + } + + key = jsonKeys[ i ++ ]; + + } while ( key !== undefined ); + + } else { + + // otherwise push as-is + + do { + + value = key[ valuePropertyName ]; + + if ( value !== undefined ) { + + times.push( key.time ); + values.push( value ); + + } + + key = jsonKeys[ i ++ ]; + + } while ( key !== undefined ); + + } + +} + +/** + * Creates a new clip, containing only the segment of the original clip between the given frames. + * + * @param {AnimationClip} sourceClip - The values to sort. + * @param {string} name - The name of the clip. + * @param {number} startFrame - The start frame. + * @param {number} endFrame - The end frame. + * @param {number} [fps=30] - The FPS. + * @return {AnimationClip} The new sub clip. + */ +function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) { + + const clip = sourceClip.clone(); + + clip.name = name; + + const tracks = []; + + for ( let i = 0; i < clip.tracks.length; ++ i ) { + + const track = clip.tracks[ i ]; + const valueSize = track.getValueSize(); + + const times = []; + const values = []; + + for ( let j = 0; j < track.times.length; ++ j ) { + + const frame = track.times[ j ] * fps; + + if ( frame < startFrame || frame >= endFrame ) continue; + + times.push( track.times[ j ] ); + + for ( let k = 0; k < valueSize; ++ k ) { + + values.push( track.values[ j * valueSize + k ] ); + + } + + } + + if ( times.length === 0 ) continue; + + track.times = convertArray( times, track.times.constructor ); + track.values = convertArray( values, track.values.constructor ); + + tracks.push( track ); + + } + + clip.tracks = tracks; + + // find minimum .times value across all tracks in the trimmed clip + + let minStartTime = Infinity; + + for ( let i = 0; i < clip.tracks.length; ++ i ) { + + if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) { + + minStartTime = clip.tracks[ i ].times[ 0 ]; + + } + + } + + // shift all tracks such that clip begins at t=0 + + for ( let i = 0; i < clip.tracks.length; ++ i ) { + + clip.tracks[ i ].shift( -1 * minStartTime ); + + } + + clip.resetDuration(); + + return clip; + +} + +/** + * Converts the keyframes of the given animation clip to an additive format. + * + * @param {AnimationClip} targetClip - The clip to make additive. + * @param {number} [referenceFrame=0] - The reference frame. + * @param {AnimationClip} [referenceClip=targetClip] - The reference clip. + * @param {number} [fps=30] - The FPS. + * @return {AnimationClip} The updated clip which is now additive. + */ +function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) { + + if ( fps <= 0 ) fps = 30; + + const numTracks = referenceClip.tracks.length; + const referenceTime = referenceFrame / fps; + + // Make each track's values relative to the values at the reference frame + for ( let i = 0; i < numTracks; ++ i ) { + + const referenceTrack = referenceClip.tracks[ i ]; + const referenceTrackType = referenceTrack.ValueTypeName; + + // Skip this track if it's non-numeric + if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue; + + // Find the track in the target clip whose name and type matches the reference track + const targetTrack = targetClip.tracks.find( function ( track ) { + + return track.name === referenceTrack.name + && track.ValueTypeName === referenceTrackType; + + } ); + + if ( targetTrack === undefined ) continue; + + let referenceOffset = 0; + const referenceValueSize = referenceTrack.getValueSize(); + + if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) { + + referenceOffset = referenceValueSize / 3; + + } + + let targetOffset = 0; + const targetValueSize = targetTrack.getValueSize(); + + if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) { + + targetOffset = targetValueSize / 3; + + } + + const lastIndex = referenceTrack.times.length - 1; + let referenceValue; + + // Find the value to subtract out of the track + if ( referenceTime <= referenceTrack.times[ 0 ] ) { + + // Reference frame is earlier than the first keyframe, so just use the first keyframe + const startIndex = referenceOffset; + const endIndex = referenceValueSize - referenceOffset; + referenceValue = referenceTrack.values.slice( startIndex, endIndex ); + + } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) { + + // Reference frame is after the last keyframe, so just use the last keyframe + const startIndex = lastIndex * referenceValueSize + referenceOffset; + const endIndex = startIndex + referenceValueSize - referenceOffset; + referenceValue = referenceTrack.values.slice( startIndex, endIndex ); + + } else { + + // Interpolate to the reference value + const interpolant = referenceTrack.createInterpolant(); + const startIndex = referenceOffset; + const endIndex = referenceValueSize - referenceOffset; + interpolant.evaluate( referenceTime ); + referenceValue = interpolant.resultBuffer.slice( startIndex, endIndex ); + + } + + // Conjugate the quaternion + if ( referenceTrackType === 'quaternion' ) { + + const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate(); + referenceQuat.toArray( referenceValue ); + + } + + // Subtract the reference value from all of the track values + + const numTimes = targetTrack.times.length; + for ( let j = 0; j < numTimes; ++ j ) { + + const valueStart = j * targetValueSize + targetOffset; + + if ( referenceTrackType === 'quaternion' ) { + + // Multiply the conjugate for quaternion track types + Quaternion.multiplyQuaternionsFlat( + targetTrack.values, + valueStart, + referenceValue, + 0, + targetTrack.values, + valueStart + ); + + } else { + + const valueEnd = targetValueSize - targetOffset * 2; + + // Subtract each value for all other numeric track types + for ( let k = 0; k < valueEnd; ++ k ) { + + targetTrack.values[ valueStart + k ] -= referenceValue[ k ]; + + } + + } + + } + + } + + targetClip.blendMode = AdditiveAnimationBlendMode; + + return targetClip; + +} + +/** + * A class with various methods to assist with animations. + * + * @hideconstructor + */ +class AnimationUtils { + + /** + * Converts an array to a specific type + * + * @static + * @param {TypedArray|Array} array - The array to convert. + * @param {TypedArray.constructor} type - The constructor of a type array. + * @return {TypedArray} The converted array + */ + static convertArray( array, type ) { + + return convertArray( array, type ); + + } + + /** + * Returns `true` if the given object is a typed array. + * + * @static + * @param {any} object - The object to check. + * @return {boolean} Whether the given object is a typed array. + */ + static isTypedArray( object ) { + + return isTypedArray( object ); + + } + + /** + * Returns `true` if the given keyframe track settings hold Bezier tangent data. + * + * @static + * @param {?Object} settings - The settings of a keyframe track. + * @return {boolean} Whether both tangent arrays are defined or not. + */ + static hasTangents( settings ) { + + return hasTangents( settings ); + + } + + /** + * Returns an array by which times and values can be sorted. + * + * @static + * @param {Array} times - The keyframe time values. + * @return {Array} The array. + */ + static getKeyframeOrder( times ) { + + return getKeyframeOrder( times ); + + } + + /** + * Sorts the given array by the previously computed order via `getKeyframeOrder()`. + * + * @static + * @param {Array} values - The values to sort. + * @param {number} stride - The stride. + * @param {Array} order - The sort order. + * @return {Array} The sorted values. + */ + static sortedArray( values, stride, order ) { + + return sortedArray( values, stride, order ); + + } + + /** + * Used for parsing AOS keyframe formats. + * + * @static + * @param {Array} jsonKeys - A list of JSON keyframes. + * @param {Array} times - This array will be filled with keyframe times by this method. + * @param {Array} values - This array will be filled with keyframe values by this method. + * @param {string} valuePropertyName - The name of the property to use. + */ + static flattenJSON( jsonKeys, times, values, valuePropertyName ) { + + flattenJSON( jsonKeys, times, values, valuePropertyName ); + + } + + /** + * Creates a new clip, containing only the segment of the original clip between the given frames. + * + * @static + * @param {AnimationClip} sourceClip - The values to sort. + * @param {string} name - The name of the clip. + * @param {number} startFrame - The start frame. + * @param {number} endFrame - The end frame. + * @param {number} [fps=30] - The FPS. + * @return {AnimationClip} The new sub clip. + */ + static subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) { + + return subclip( sourceClip, name, startFrame, endFrame, fps ); + + } + + /** + * Converts the keyframes of the given animation clip to an additive format. + * + * @static + * @param {AnimationClip} targetClip - The clip to make additive. + * @param {number} [referenceFrame=0] - The reference frame. + * @param {AnimationClip} [referenceClip=targetClip] - The reference clip. + * @param {number} [fps=30] - The FPS. + * @return {AnimationClip} The updated clip which is now additive. + */ + static makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) { + + return makeClipAdditive( targetClip, referenceFrame, referenceClip, fps ); + + } + +} + +/** + * Abstract base class of interpolants over parametric samples. + * + * The parameter domain is one dimensional, typically the time or a path + * along a curve defined by the data. + * + * The sample values can have any dimensionality and derived classes may + * apply special interpretations to the data. + * + * This class provides the interval seek in a Template Method, deferring + * the actual interpolation to derived classes. + * + * Time complexity is O(1) for linear access crossing at most two points + * and O(log N) for random access, where N is the number of positions. + * + * References: {@link http://www.oodesign.com/template-method-pattern.html} + * + * @abstract + */ +class Interpolant { + + /** + * Constructs a new interpolant. + * + * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors. + * @param {TypedArray} sampleValues - The sample values. + * @param {number} sampleSize - The sample size + * @param {TypedArray} [resultBuffer] - The result buffer. + */ + constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) { + + /** + * The parameter positions. + * + * @type {TypedArray} + */ + this.parameterPositions = parameterPositions; + + /** + * A cache index. + * + * @private + * @type {number} + * @default 0 + */ + this._cachedIndex = 0; + + /** + * The result buffer. + * + * @type {TypedArray} + */ + this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor( sampleSize ); + + /** + * The sample values. + * + * @type {TypedArray} + */ + this.sampleValues = sampleValues; + + /** + * The value size. + * + * @type {TypedArray} + */ + this.valueSize = sampleSize; + + /** + * The interpolation settings. + * + * @type {?Object} + * @default null + */ + this.settings = null; + + /** + * The default settings object. + * + * @type {Object} + */ + this.DefaultSettings_ = {}; + + } + + /** + * Evaluate the interpolant at position `t`. + * + * @param {number} t - The interpolation factor. + * @return {TypedArray} The result buffer. + */ + evaluate( t ) { + + const pp = this.parameterPositions; + let i1 = this._cachedIndex, + t1 = pp[ i1 ], + t0 = pp[ i1 - 1 ]; + + validate_interval: { + + seek: { + + let right; + + linear_scan: { + + //- See http://jsperf.com/comparison-to-undefined/3 + //- slower code: + //- + //- if ( t >= t1 || t1 === undefined ) { + forward_scan: if ( ! ( t < t1 ) ) { + + for ( let giveUpAt = i1 + 2; ; ) { + + if ( t1 === undefined ) { + + if ( t < t0 ) break forward_scan; + + // after end + + i1 = pp.length; + this._cachedIndex = i1; + return this.copySampleValue_( i1 - 1 ); + + } + + if ( i1 === giveUpAt ) break; // this loop + + t0 = t1; + t1 = pp[ ++ i1 ]; + + if ( t < t1 ) { + + // we have arrived at the sought interval + break seek; + + } + + } + + // prepare binary search on the right side of the index + right = pp.length; + break linear_scan; + + } + + //- slower code: + //- if ( t < t0 || t0 === undefined ) { + if ( ! ( t >= t0 ) ) { + + // looping? + + const t1global = pp[ 1 ]; + + if ( t < t1global ) { + + i1 = 2; // + 1, using the scan for the details + t0 = t1global; + + } + + // linear reverse scan + + for ( let giveUpAt = i1 - 2; ; ) { + + if ( t0 === undefined ) { + + // before start + + this._cachedIndex = 0; + return this.copySampleValue_( 0 ); + + } + + if ( i1 === giveUpAt ) break; // this loop + + t1 = t0; + t0 = pp[ -- i1 - 1 ]; + + if ( t >= t0 ) { + + // we have arrived at the sought interval + break seek; + + } + + } + + // prepare binary search on the left side of the index + right = i1; + i1 = 0; + break linear_scan; + + } + + // the interval is valid + + break validate_interval; + + } // linear scan + + // binary search + + while ( i1 < right ) { + + const mid = ( i1 + right ) >>> 1; + + if ( t < pp[ mid ] ) { + + right = mid; + + } else { + + i1 = mid + 1; + + } + + } + + t1 = pp[ i1 ]; + t0 = pp[ i1 - 1 ]; + + // check boundary cases, again + + if ( t0 === undefined ) { + + this._cachedIndex = 0; + return this.copySampleValue_( 0 ); + + } + + if ( t1 === undefined ) { + + i1 = pp.length; + this._cachedIndex = i1; + return this.copySampleValue_( i1 - 1 ); + + } + + } // seek + + this._cachedIndex = i1; + + this.intervalChanged_( i1, t0, t1 ); + + } // validate_interval + + return this.interpolate_( i1, t0, t, t1 ); + + } + + /** + * Returns the interpolation settings. + * + * @return {Object} The interpolation settings. + */ + getSettings_() { + + return this.settings || this.DefaultSettings_; + + } + + /** + * Copies a sample value to the result buffer. + * + * @param {number} index - An index into the sample value buffer. + * @return {TypedArray} The result buffer. + */ + copySampleValue_( index ) { + + // copies a sample value to the result buffer + + const result = this.resultBuffer, + values = this.sampleValues, + stride = this.valueSize, + offset = index * stride; + + for ( let i = 0; i !== stride; ++ i ) { + + result[ i ] = values[ offset + i ]; + + } + + return result; + + } + + /** + * Copies a sample value to the result buffer. + * + * @abstract + * @param {number} i1 - An index into the sample value buffer. + * @param {number} t0 - The previous interpolation factor. + * @param {number} t - The current interpolation factor. + * @param {number} t1 - The next interpolation factor. + * @return {TypedArray} The result buffer. + */ + interpolate_( /* i1, t0, t, t1 */ ) { + + throw new Error( 'THREE.Interpolant: Call to abstract method.' ); + // implementations shall return this.resultBuffer + + } + + /** + * Optional method that is executed when the interval has changed. + * + * @param {number} i1 - An index into the sample value buffer. + * @param {number} t0 - The previous interpolation factor. + * @param {number} t - The current interpolation factor. + */ + intervalChanged_( /* i1, t0, t1 */ ) { + + // empty + + } + +} + +/** + * Fast and simple cubic spline interpolant. + * + * It was derived from a Hermitian construction setting the first derivative + * at each sample position to the linear slope between neighboring positions + * over their parameter interval. + * + * @augments Interpolant + */ +class CubicInterpolant extends Interpolant { + + /** + * Constructs a new cubic interpolant. + * + * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors. + * @param {TypedArray} sampleValues - The sample values. + * @param {number} sampleSize - The sample size + * @param {TypedArray} [resultBuffer] - The result buffer. + */ + constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) { + + super( parameterPositions, sampleValues, sampleSize, resultBuffer ); + + this._weightPrev = -0; + this._offsetPrev = -0; + this._weightNext = -0; + this._offsetNext = -0; + + this.DefaultSettings_ = { + + endingStart: ZeroCurvatureEnding, + endingEnd: ZeroCurvatureEnding + + }; + + } + + intervalChanged_( i1, t0, t1 ) { + + const pp = this.parameterPositions; + let iPrev = i1 - 2, + iNext = i1 + 1, + + tPrev = pp[ iPrev ], + tNext = pp[ iNext ]; + + if ( tPrev === undefined ) { + + switch ( this.getSettings_().endingStart ) { + + case ZeroSlopeEnding: + + // f'(t0) = 0 + iPrev = i1; + tPrev = 2 * t0 - t1; + + break; + + case WrapAroundEnding: + + // use the other end of the curve + iPrev = pp.length - 2; + tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ]; + + break; + + default: // ZeroCurvatureEnding + + // f''(t0) = 0 a.k.a. Natural Spline + iPrev = i1; + tPrev = t1; + + } + + } + + if ( tNext === undefined ) { + + switch ( this.getSettings_().endingEnd ) { + + case ZeroSlopeEnding: + + // f'(tN) = 0 + iNext = i1; + tNext = 2 * t1 - t0; + + break; + + case WrapAroundEnding: + + // use the other end of the curve + iNext = 1; + tNext = t1 + pp[ 1 ] - pp[ 0 ]; + + break; + + default: // ZeroCurvatureEnding + + // f''(tN) = 0, a.k.a. Natural Spline + iNext = i1 - 1; + tNext = t0; + + } + + } + + const halfDt = ( t1 - t0 ) * 0.5, + stride = this.valueSize; + + this._weightPrev = halfDt / ( t0 - tPrev ); + this._weightNext = halfDt / ( tNext - t1 ); + this._offsetPrev = iPrev * stride; + this._offsetNext = iNext * stride; + + } + + interpolate_( i1, t0, t, t1 ) { + + const result = this.resultBuffer, + values = this.sampleValues, + stride = this.valueSize, + + o1 = i1 * stride, o0 = o1 - stride, + oP = this._offsetPrev, oN = this._offsetNext, + wP = this._weightPrev, wN = this._weightNext, + + p = ( t - t0 ) / ( t1 - t0 ), + pp = p * p, + ppp = pp * p; + + // evaluate polynomials + + const sP = - wP * ppp + 2 * wP * pp - wP * p; + const s0 = ( 1 + wP ) * ppp + ( -1.5 - 2 * wP ) * pp + ( -0.5 + wP ) * p + 1; + const s1 = ( -1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p; + const sN = wN * ppp - wN * pp; + + // combine data linearly + + for ( let i = 0; i !== stride; ++ i ) { + + result[ i ] = + sP * values[ oP + i ] + + s0 * values[ o0 + i ] + + s1 * values[ o1 + i ] + + sN * values[ oN + i ]; + + } + + return result; + + } + +} + +/** + * A basic linear interpolant. + * + * @augments Interpolant + */ +class LinearInterpolant extends Interpolant { + + /** + * Constructs a new linear interpolant. + * + * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors. + * @param {TypedArray} sampleValues - The sample values. + * @param {number} sampleSize - The sample size + * @param {TypedArray} [resultBuffer] - The result buffer. + */ + constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) { + + super( parameterPositions, sampleValues, sampleSize, resultBuffer ); + + } + + interpolate_( i1, t0, t, t1 ) { + + const result = this.resultBuffer, + values = this.sampleValues, + stride = this.valueSize, + + offset1 = i1 * stride, + offset0 = offset1 - stride, + + weight1 = ( t - t0 ) / ( t1 - t0 ), + weight0 = 1 - weight1; + + for ( let i = 0; i !== stride; ++ i ) { + + result[ i ] = + values[ offset0 + i ] * weight0 + + values[ offset1 + i ] * weight1; + + } + + return result; + + } + +} + +/** + * Interpolant that evaluates to the sample value at the position preceding + * the parameter. + * + * @augments Interpolant + */ +class DiscreteInterpolant extends Interpolant { + + /** + * Constructs a new discrete interpolant. + * + * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors. + * @param {TypedArray} sampleValues - The sample values. + * @param {number} sampleSize - The sample size + * @param {TypedArray} [resultBuffer] - The result buffer. + */ + constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) { + + super( parameterPositions, sampleValues, sampleSize, resultBuffer ); + + } + + interpolate_( i1 /*, t0, t, t1 */ ) { + + return this.copySampleValue_( i1 - 1 ); + + } + +} + +/** + * A Bezier interpolant using cubic Bezier curves with 2D control points. + * + * This interpolant supports the COLLADA/Maya style of Bezier animation where + * each keyframe has explicit in/out tangent control points specified as + * 2D coordinates (time, value). + * + * Tangent data is read from `inTangents` and `outTangents` on the interpolant + * (populated by `KeyframeTrack.InterpolantFactoryMethodBezier`). + * + * For a track with N keyframes and stride S: + * - Each tangent array has N * S * 2 values + * - Layout: [k0_c0_time, k0_c0_value, k0_c1_time, k0_c1_value, ..., k0_cS_time, k0_cS_value, + * k1_c0_time, k1_c0_value, ...] + * + * @augments Interpolant + */ +class BezierInterpolant extends Interpolant { + + interpolate_( i1, t0, t, t1 ) { + + const result = this.resultBuffer; + const values = this.sampleValues; + const stride = this.valueSize; + + const offset1 = i1 * stride; + const offset0 = offset1 - stride; + + const inTangents = this.inTangents; + const outTangents = this.outTangents; + + // If no tangent data, fall back to linear interpolation + if ( ! inTangents || ! outTangents ) { + + const weight1 = ( t - t0 ) / ( t1 - t0 ); + const weight0 = 1 - weight1; + + for ( let i = 0; i !== stride; ++ i ) { + + result[ i ] = values[ offset0 + i ] * weight0 + values[ offset1 + i ] * weight1; + + } + + return result; + + } + + const tangentStride = stride * 2; + const i0 = i1 - 1; + + for ( let i = 0; i !== stride; ++ i ) { + + const v0 = values[ offset0 + i ]; + const v1 = values[ offset1 + i ]; + + // outTangent of previous keyframe (C0) + const outTangentOffset = i0 * tangentStride + i * 2; + const c0x = outTangents[ outTangentOffset ]; + const c0y = outTangents[ outTangentOffset + 1 ]; + + // inTangent of current keyframe (C1) + const inTangentOffset = i1 * tangentStride + i * 2; + const c1x = inTangents[ inTangentOffset ]; + const c1y = inTangents[ inTangentOffset + 1 ]; + + // Find the curve parameter s where the Bezier X(s) matches t, then evaluate Y(s) + const s = solveBezierParameter( t, t0, c0x, c1x, t1 ); + + result[ i ] = cubicBezier( s, v0, c0y, c1y, v1 ); + + } + + return result; + + } + +} + +function cubicBezier( s, p0, p1, p2, p3 ) { + + const k = 1 - s; + + return k * k * k * p0 + 3 * k * k * s * p1 + 3 * k * s * s * p2 + s * s * s * p3; + +} + +function cubicBezierSlope( s, p0, p1, p2, p3 ) { + + const k = 1 - s; + + return 3 * k * k * ( p1 - p0 ) + 6 * k * s * ( p2 - p1 ) + 3 * s * s * ( p3 - p2 ); + +} + +// Solves cubicBezier( s, x0, x1, x2, x3 ) = x for s in [0,1] using Newton-Raphson + +function solveBezierParameter( x, x0, x1, x2, x3 ) { + + let s = ( x - x0 ) / ( x3 - x0 ); + + for ( let i = 0; i < 8; i ++ ) { + + const error = cubicBezier( s, x0, x1, x2, x3 ) - x; + if ( Math.abs( error ) < 1e-10 ) break; + + const slope = cubicBezierSlope( s, x0, x1, x2, x3 ); + if ( Math.abs( slope ) < 1e-10 ) break; + + s = Math.max( 0, Math.min( 1, s - error / slope ) ); + + } + + return s; + +} + +/** + * Represents a timed sequence of keyframes, which are composed of lists of + * times and related values, and which are used to animate a specific property + * of an object. + */ +class KeyframeTrack { + + /** + * Constructs a new keyframe track. + * + * @param {string} name - The keyframe track's name. + * @param {Array} times - A list of keyframe times. + * @param {Array} values - A list of keyframe values. + * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth|InterpolateBezier)} [interpolation] - The interpolation type. + */ + constructor( name, times, values, interpolation ) { + + if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' ); + if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name ); + + /** + * The track's name can refer to morph targets or bones or + * possibly other values within an animated object. See {@link PropertyBinding#parseTrackName} + * for the forms of strings that can be parsed for property binding. + * + * @type {string} + */ + this.name = name; + + /** + * The keyframe times. + * + * @type {Float32Array} + */ + this.times = convertArray( times, this.TimeBufferType ); + + /** + * The keyframe values. + * + * @type {Float32Array} + */ + this.values = convertArray( values, this.ValueBufferType ); + + this.setInterpolation( interpolation || this.DefaultInterpolation ); + + } + + /** + * Converts the keyframe track to JSON. + * + * @static + * @param {KeyframeTrack} track - The keyframe track to serialize. + * @return {Object} The serialized keyframe track as JSON. + */ + static toJSON( track ) { + + const trackType = track.constructor; + + let json; + + // derived classes can define a static toJSON method + if ( trackType.toJSON !== this.toJSON ) { + + json = trackType.toJSON( track ); + + } else { + + // by default, we assume the data can be serialized as-is + json = { + + 'name': track.name, + 'times': convertArray( track.times, Array ), + 'values': convertArray( track.values, Array ) + + }; + + const interpolation = track.getInterpolation(); + + if ( interpolation !== track.DefaultInterpolation ) { + + json.interpolation = interpolation; + + } + + if ( hasTangents( track.settings ) ) { + + json.settings = { + inTangents: convertArray( track.settings.inTangents, Array ), + outTangents: convertArray( track.settings.outTangents, Array ) + }; + + } + + } + + json.type = track.ValueTypeName; // mandatory + + return json; + + } + + /** + * Factory method for creating a new discrete interpolant. + * + * @static + * @param {TypedArray} [result] - The result buffer. + * @return {DiscreteInterpolant} The new interpolant. + */ + InterpolantFactoryMethodDiscrete( result ) { + + return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result ); + + } + + /** + * Factory method for creating a new linear interpolant. + * + * @static + * @param {TypedArray} [result] - The result buffer. + * @return {LinearInterpolant} The new interpolant. + */ + InterpolantFactoryMethodLinear( result ) { + + return new LinearInterpolant( this.times, this.values, this.getValueSize(), result ); + + } + + /** + * Factory method for creating a new smooth interpolant. + * + * @static + * @param {TypedArray} [result] - The result buffer. + * @return {CubicInterpolant} The new interpolant. + */ + InterpolantFactoryMethodSmooth( result ) { + + return new CubicInterpolant( this.times, this.values, this.getValueSize(), result ); + + } + + /** + * Factory method for creating a new Bezier interpolant. + * + * The Bezier interpolant requires tangent data to be set via the `settings` property + * on the track before creating the interpolant. The settings should contain: + * - `inTangents`: Float32Array with [time, value] pairs per keyframe per component + * - `outTangents`: Float32Array with [time, value] pairs per keyframe per component + * + * @static + * @param {TypedArray} [result] - The result buffer. + * @return {BezierInterpolant} The new interpolant. + */ + InterpolantFactoryMethodBezier( result ) { + + const interpolant = new BezierInterpolant( this.times, this.values, this.getValueSize(), result ); + + if ( this.settings ) { + + interpolant.inTangents = this.settings.inTangents; + interpolant.outTangents = this.settings.outTangents; + + } + + return interpolant; + + } + + /** + * Defines the interpolation factor method for this keyframe track. + * + * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth|InterpolateBezier)} interpolation - The interpolation type. + * @return {KeyframeTrack} A reference to this keyframe track. + */ + setInterpolation( interpolation ) { + + let factoryMethod; + + switch ( interpolation ) { + + case InterpolateDiscrete: + + factoryMethod = this.InterpolantFactoryMethodDiscrete; + + break; + + case InterpolateLinear: + + factoryMethod = this.InterpolantFactoryMethodLinear; + + break; + + case InterpolateSmooth: + + factoryMethod = this.InterpolantFactoryMethodSmooth; + + break; + + case InterpolateBezier: + + factoryMethod = this.InterpolantFactoryMethodBezier; + + break; + + } + + if ( factoryMethod === undefined ) { + + const message = 'unsupported interpolation for ' + + this.ValueTypeName + ' keyframe track named ' + this.name; + + if ( this.createInterpolant === undefined ) { + + // fall back to default, unless the default itself is messed up + if ( interpolation !== this.DefaultInterpolation ) { + + this.setInterpolation( this.DefaultInterpolation ); + + } else { + + throw new Error( message ); // fatal, in this case + + } + + } + + warn( 'KeyframeTrack:', message ); + return this; + + } + + this.createInterpolant = factoryMethod; + + return this; + + } + + /** + * Returns the current interpolation type. + * + * @return {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth|InterpolateBezier)} The interpolation type. + */ + getInterpolation() { + + switch ( this.createInterpolant ) { + + case this.InterpolantFactoryMethodDiscrete: + + return InterpolateDiscrete; + + case this.InterpolantFactoryMethodLinear: + + return InterpolateLinear; + + case this.InterpolantFactoryMethodSmooth: + + return InterpolateSmooth; + + case this.InterpolantFactoryMethodBezier: + + return InterpolateBezier; + + } + + } + + /** + * Returns the value size. + * + * @return {number} The value size. + */ + getValueSize() { + + return this.values.length / this.times.length; + + } + + /** + * Moves all keyframes either forward or backward in time. + * + * @param {number} timeOffset - The offset to move the time values. + * @return {KeyframeTrack} A reference to this keyframe track. + */ + shift( timeOffset ) { + + if ( timeOffset !== 0.0 ) { + + const times = this.times; + + for ( let i = 0, n = times.length; i !== n; ++ i ) { + + times[ i ] += timeOffset; + + } + + } + + return this; + + } + + /** + * Scale all keyframe times by a factor (useful for frame - seconds conversions). + * + * @param {number} timeScale - The time scale. + * @return {KeyframeTrack} A reference to this keyframe track. + */ + scale( timeScale ) { + + if ( timeScale !== 1.0 ) { + + const times = this.times; + + for ( let i = 0, n = times.length; i !== n; ++ i ) { + + times[ i ] *= timeScale; + + } + + if ( hasTangents( this.settings ) ) { + + scaleTangentTimes( this.settings.inTangents, timeScale ); + scaleTangentTimes( this.settings.outTangents, timeScale ); + + } + + } + + return this; + + } + + /** + * Removes keyframes before and after animation without changing any values within the defined time range. + * + * Note: The method does not shift around keys to the start of the track time, because for interpolated + * keys this will change their values + * + * @param {number} startTime - The start time. + * @param {number} endTime - The end time. + * @return {KeyframeTrack} A reference to this keyframe track. + */ + trim( startTime, endTime ) { + + const times = this.times, + nKeys = times.length; + + let from = 0, + to = nKeys - 1; + + while ( from !== nKeys && times[ from ] < startTime ) { + + ++ from; + + } + + while ( to !== -1 && times[ to ] > endTime ) { + + -- to; + + } + + ++ to; // inclusive -> exclusive bound + + if ( from !== 0 || to !== nKeys ) { + + // empty tracks are forbidden, so keep at least one keyframe + if ( from >= to ) { + + to = Math.max( to, 1 ); + from = to - 1; + + } + + const stride = this.getValueSize(); + this.times = times.slice( from, to ); + this.values = this.values.slice( from * stride, to * stride ); + + } + + return this; + + } + + /** + * Performs minimal validation on the keyframe track. Returns `true` if the values + * are valid. + * + * @return {boolean} Whether the keyframes are valid or not. + */ + validate() { + + let valid = true; + + const valueSize = this.getValueSize(); + if ( valueSize - Math.floor( valueSize ) !== 0 ) { + + error( 'KeyframeTrack: Invalid value size in track.', this ); + valid = false; + + } + + const times = this.times, + values = this.values, + + nKeys = times.length; + + if ( nKeys === 0 ) { + + error( 'KeyframeTrack: Track is empty.', this ); + valid = false; + + } + + let prevTime = null; + + for ( let i = 0; i !== nKeys; i ++ ) { + + const currTime = times[ i ]; + + if ( typeof currTime === 'number' && isNaN( currTime ) ) { + + error( 'KeyframeTrack: Time is not a valid number.', this, i, currTime ); + valid = false; + break; + + } + + if ( prevTime !== null && prevTime > currTime ) { + + error( 'KeyframeTrack: Out of order keys.', this, i, currTime, prevTime ); + valid = false; + break; + + } + + prevTime = currTime; + + } + + if ( values !== undefined ) { + + if ( isTypedArray( values ) ) { + + for ( let i = 0, n = values.length; i !== n; ++ i ) { + + const value = values[ i ]; + + if ( isNaN( value ) ) { + + error( 'KeyframeTrack: Value is not a valid number.', this, i, value ); + valid = false; + break; + + } + + } + + } + + } + + return valid; + + } + + /** + * Optimizes this keyframe track by removing equivalent sequential keys (which are + * common in morph target sequences). + * + * @return {KeyframeTrack} A reference to this keyframe track. + */ + optimize() { + + // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0) + + // times or values may be shared with other tracks, so overwriting is unsafe + const times = this.times.slice(), + values = this.values.slice(), + stride = this.getValueSize(), + + smoothInterpolation = this.getInterpolation() === InterpolateSmooth, + + lastIndex = times.length - 1; + + let writeIndex = 1; + + for ( let i = 1; i < lastIndex; ++ i ) { + + let keep = false; + + const time = times[ i ]; + const timeNext = times[ i + 1 ]; + + // remove adjacent keyframes scheduled at the same time + + if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) { + + if ( ! smoothInterpolation ) { + + // remove unnecessary keyframes same as their neighbors + + const offset = i * stride, + offsetP = offset - stride, + offsetN = offset + stride; + + for ( let j = 0; j !== stride; ++ j ) { + + const value = values[ offset + j ]; + + if ( value !== values[ offsetP + j ] || + value !== values[ offsetN + j ] ) { + + keep = true; + break; + + } + + } + + } else { + + keep = true; + + } + + } + + // in-place compaction + + if ( keep ) { + + if ( i !== writeIndex ) { + + times[ writeIndex ] = times[ i ]; + + const readOffset = i * stride, + writeOffset = writeIndex * stride; + + for ( let j = 0; j !== stride; ++ j ) { + + values[ writeOffset + j ] = values[ readOffset + j ]; + + } + + } + + ++ writeIndex; + + } + + } + + // flush last keyframe (compaction looks ahead) + + if ( lastIndex > 0 ) { + + times[ writeIndex ] = times[ lastIndex ]; + + for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) { + + values[ writeOffset + j ] = values[ readOffset + j ]; + + } + + ++ writeIndex; + + } + + if ( writeIndex !== times.length ) { + + this.times = times.slice( 0, writeIndex ); + this.values = values.slice( 0, writeIndex * stride ); + + } else { + + this.times = times; + this.values = values; + + } + + return this; + + } + + /** + * Returns a new keyframe track with copied values from this instance. + * + * @return {KeyframeTrack} A clone of this instance. + */ + clone() { + + const times = this.times.slice(); + const values = this.values.slice(); + + const TypedKeyframeTrack = this.constructor; + const track = new TypedKeyframeTrack( this.name, times, values ); + + // Interpolant argument to constructor is not saved, so copy the factory method directly. + track.createInterpolant = this.createInterpolant; + + if ( hasTangents( this.settings ) ) { + + track.settings = { + inTangents: this.settings.inTangents.slice(), + outTangents: this.settings.outTangents.slice() + }; + + } + + return track; + + } + +} + +function scaleTangentTimes( tangents, timeScale ) { + + // tangents are [ time, value ] pairs, so only every second entry is a time + + for ( let i = 0, n = tangents.length; i !== n; i += 2 ) { + + tangents[ i ] *= timeScale; + + } + +} + +/** + * The value type name. + * + * @type {string} + * @default '' + */ +KeyframeTrack.prototype.ValueTypeName = ''; + +/** + * The time buffer type of this keyframe track. + * + * @type {TypedArray|Array} + * @default Float32Array.constructor + */ +KeyframeTrack.prototype.TimeBufferType = Float32Array; + +/** + * The value buffer type of this keyframe track. + * + * @type {TypedArray|Array} + * @default Float32Array.constructor + */ +KeyframeTrack.prototype.ValueBufferType = Float32Array; + +/** + * The default interpolation type of this keyframe track. + * + * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth|InterpolateBezier)} + * @default InterpolateLinear + */ +KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear; + +/** + * A track for boolean keyframe values. + * + * @augments KeyframeTrack + */ +class BooleanKeyframeTrack extends KeyframeTrack { + + /** + * Constructs a new boolean keyframe track. + * + * This keyframe track type has no `interpolation` parameter because the + * interpolation is always discrete. + * + * @param {string} name - The keyframe track's name. + * @param {Array} times - A list of keyframe times. + * @param {Array} values - A list of keyframe values. + */ + constructor( name, times, values ) { + + super( name, times, values ); + + } + +} + +/** + * The value type name. + * + * @type {string} + * @default 'bool' + */ +BooleanKeyframeTrack.prototype.ValueTypeName = 'bool'; + +/** + * The value buffer type of this keyframe track. + * + * @type {TypedArray|Array} + * @default Array.constructor + */ +BooleanKeyframeTrack.prototype.ValueBufferType = Array; + +/** + * The default interpolation type of this keyframe track. + * + * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} + * @default InterpolateDiscrete + */ +BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete; +BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined; +BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined; + +/** + * A track for color keyframe values. + * + * @augments KeyframeTrack + */ +class ColorKeyframeTrack extends KeyframeTrack { + + /** + * Constructs a new color keyframe track. + * + * @param {string} name - The keyframe track's name. + * @param {Array} times - A list of keyframe times. + * @param {Array} values - A list of keyframe values. + * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type. + */ + constructor( name, times, values, interpolation ) { + + super( name, times, values, interpolation ); + + } + +} + +/** + * The value type name. + * + * @type {string} + * @default 'color' + */ +ColorKeyframeTrack.prototype.ValueTypeName = 'color'; + +/** + * A track for numeric keyframe values. + * + * @augments KeyframeTrack + */ +class NumberKeyframeTrack extends KeyframeTrack { + + /** + * Constructs a new number keyframe track. + * + * @param {string} name - The keyframe track's name. + * @param {Array} times - A list of keyframe times. + * @param {Array} values - A list of keyframe values. + * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type. + */ + constructor( name, times, values, interpolation ) { + + super( name, times, values, interpolation ); + + } + +} + +/** + * The value type name. + * + * @type {string} + * @default 'number' + */ +NumberKeyframeTrack.prototype.ValueTypeName = 'number'; + +/** + * Spherical linear unit quaternion interpolant. + * + * @augments Interpolant + */ +class QuaternionLinearInterpolant extends Interpolant { + + /** + * Constructs a new SLERP interpolant. + * + * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors. + * @param {TypedArray} sampleValues - The sample values. + * @param {number} sampleSize - The sample size + * @param {TypedArray} [resultBuffer] - The result buffer. + */ + constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) { + + super( parameterPositions, sampleValues, sampleSize, resultBuffer ); + + } + + interpolate_( i1, t0, t, t1 ) { + + const result = this.resultBuffer, + values = this.sampleValues, + stride = this.valueSize, + + alpha = ( t - t0 ) / ( t1 - t0 ); + + let offset = i1 * stride; + + for ( let end = offset + stride; offset !== end; offset += 4 ) { + + Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha ); + + } + + return result; + + } + +} + +/** + * A track for Quaternion keyframe values. + * + * @augments KeyframeTrack + */ +class QuaternionKeyframeTrack extends KeyframeTrack { + + /** + * Constructs a new Quaternion keyframe track. + * + * @param {string} name - The keyframe track's name. + * @param {Array} times - A list of keyframe times. + * @param {Array} values - A list of keyframe values. + * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type. + */ + constructor( name, times, values, interpolation ) { + + super( name, times, values, interpolation ); + + } + + /** + * Overwritten so the method returns Quaternion based interpolant. + * + * @static + * @param {TypedArray} [result] - The result buffer. + * @return {QuaternionLinearInterpolant} The new interpolant. + */ + InterpolantFactoryMethodLinear( result ) { + + return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result ); + + } + +} + +/** + * The value type name. + * + * @type {string} + * @default 'quaternion' + */ +QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion'; +// ValueBufferType is inherited +// DefaultInterpolation is inherited; +QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined; + +/** + * A track for string keyframe values. + * + * @augments KeyframeTrack + */ +class StringKeyframeTrack extends KeyframeTrack { + + /** + * Constructs a new string keyframe track. + * + * This keyframe track type has no `interpolation` parameter because the + * interpolation is always discrete. + * + * @param {string} name - The keyframe track's name. + * @param {Array} times - A list of keyframe times. + * @param {Array} values - A list of keyframe values. + */ + constructor( name, times, values ) { + + super( name, times, values ); + + } + +} + +/** + * The value type name. + * + * @type {string} + * @default 'string' + */ +StringKeyframeTrack.prototype.ValueTypeName = 'string'; + +/** + * The value buffer type of this keyframe track. + * + * @type {TypedArray|Array} + * @default Array.constructor + */ +StringKeyframeTrack.prototype.ValueBufferType = Array; + +/** + * The default interpolation type of this keyframe track. + * + * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} + * @default InterpolateDiscrete + */ +StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete; +StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined; +StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined; + +/** + * A track for vector keyframe values. + * + * @augments KeyframeTrack + */ +class VectorKeyframeTrack extends KeyframeTrack { + + /** + * Constructs a new vector keyframe track. + * + * @param {string} name - The keyframe track's name. + * @param {Array} times - A list of keyframe times. + * @param {Array} values - A list of keyframe values. + * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type. + */ + constructor( name, times, values, interpolation ) { + + super( name, times, values, interpolation ); + + } + +} + +/** + * The value type name. + * + * @type {string} + * @default 'vector' + */ +VectorKeyframeTrack.prototype.ValueTypeName = 'vector'; + +/** + * A reusable set of keyframe tracks which represent an animation. + */ +class AnimationClip { + + /** + * Constructs a new animation clip. + * + * Note: Instead of instantiating an AnimationClip directly with the constructor, you can + * use the static interface of this class for creating clips. In most cases though, animation clips + * will automatically be created by loaders when importing animated 3D assets. + * + * @param {string} [name=''] - The clip's name. + * @param {number} [duration=-1] - The clip's duration in seconds. If a negative value is passed, + * the duration will be calculated from the passed keyframes. + * @param {Array} tracks - An array of keyframe tracks. + * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode=NormalAnimationBlendMode] - Defines how the animation + * is blended/combined when two or more animations are simultaneously played. + */ + constructor( name = '', duration = -1, tracks = [], blendMode = NormalAnimationBlendMode ) { + + /** + * The clip's name. + * + * @type {string} + */ + this.name = name; + + /** + * An array of keyframe tracks. + * + * @type {Array} + */ + this.tracks = tracks; + + /** + * The clip's duration in seconds. + * + * @type {number} + */ + this.duration = duration; + + /** + * Defines how the animation is blended/combined when two or more animations + * are simultaneously played. + * + * @type {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} + */ + this.blendMode = blendMode; + + /** + * The UUID of the animation clip. + * + * @type {string} + * @readonly + */ + this.uuid = generateUUID(); + + /** + * An object that can be used to store custom data about the animation clip. + * It should not hold references to functions as these will not be cloned. + * + * @type {Object} + */ + this.userData = {}; + + // this means it should figure out its duration by scanning the tracks + if ( this.duration < 0 ) { + + this.resetDuration(); + + } + + } + + /** + * Factory method for creating an animation clip from the given JSON. + * + * @static + * @param {Object} json - The serialized animation clip. + * @return {AnimationClip} The new animation clip. + */ + static parse( json ) { + + const tracks = [], + jsonTracks = json.tracks, + frameTime = 1.0 / ( json.fps || 1.0 ); + + for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) { + + tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) ); + + } + + const clip = new this( json.name, json.duration, tracks, json.blendMode ); + clip.uuid = json.uuid; + + clip.userData = JSON.parse( json.userData || '{}' ); + + return clip; + + } + + /** + * Serializes the given animation clip into JSON. + * + * @static + * @param {AnimationClip} clip - The animation clip to serialize. + * @return {Object} The JSON object. + */ + static toJSON( clip ) { + + const tracks = [], + clipTracks = clip.tracks; + + const json = { + + 'name': clip.name, + 'duration': clip.duration, + 'tracks': tracks, + 'uuid': clip.uuid, + 'blendMode': clip.blendMode, + 'userData': JSON.stringify( clip.userData ), + + }; + + for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) { + + tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) ); + + } + + return json; + + } + + /** + * Returns a new animation clip from the passed morph targets array of a + * geometry, taking a name and the number of frames per second. + * + * Note: The fps parameter is required, but the animation speed can be + * overridden via {@link AnimationAction#setDuration}. + * + * @static + * @param {string} name - The name of the animation clip. + * @param {Array} morphTargetSequence - A sequence of morph targets. + * @param {number} fps - The Frames-Per-Second value. + * @param {boolean} noLoop - Whether the clip should be no loop or not. + * @return {AnimationClip} The new animation clip. + */ + static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) { + + const numMorphTargets = morphTargetSequence.length; + const tracks = []; + + for ( let i = 0; i < numMorphTargets; i ++ ) { + + let times = []; + let values = []; + + times.push( + ( i + numMorphTargets - 1 ) % numMorphTargets, + i, + ( i + 1 ) % numMorphTargets ); + + values.push( 0, 1, 0 ); + + const order = getKeyframeOrder( times ); + times = sortedArray( times, 1, order ); + values = sortedArray( values, 1, order ); + + // if there is a key at the first frame, duplicate it as the + // last frame as well for perfect loop. + if ( ! noLoop && times[ 0 ] === 0 ) { + + times.push( numMorphTargets ); + values.push( values[ 0 ] ); + + } + + tracks.push( + new NumberKeyframeTrack( + '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']', + times, values + ).scale( 1.0 / fps ) ); + + } + + return new this( name, -1, tracks ); + + } + + /** + * Searches for an animation clip by name, taking as its first parameter + * either an array of clips, or a mesh or geometry that contains an + * array named "animations" property. + * + * @static + * @param {(Array|Object3D)} objectOrClipArray - The array or object to search through. + * @param {string} name - The name to search for. + * @return {?AnimationClip} The found animation clip. Returns `null` if no clip has been found. + */ + static findByName( objectOrClipArray, name ) { + + let clipArray = objectOrClipArray; + + if ( ! Array.isArray( objectOrClipArray ) ) { + + const o = objectOrClipArray; + clipArray = o.geometry && o.geometry.animations || o.animations; + + } + + for ( let i = 0; i < clipArray.length; i ++ ) { + + if ( clipArray[ i ].name === name ) { + + return clipArray[ i ]; + + } + + } + + return null; + + } + + /** + * Returns an array of new AnimationClips created from the morph target + * sequences of a geometry, trying to sort morph target names into + * animation-group-based patterns like "Walk_001, Walk_002, Run_001, Run_002...". + * + * See {@link MD2Loader#parse} as an example for how the method should be used. + * + * @static + * @param {Array} morphTargets - A sequence of morph targets. + * @param {number} fps - The Frames-Per-Second value. + * @param {boolean} noLoop - Whether the clip should be no loop or not. + * @return {Array} An array of new animation clips. + */ + static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) { + + const animationToMorphTargets = {}; + + // tested with https://regex101.com/ on trick sequences + // such flamingo_flyA_003, flamingo_run1_003, crdeath0059 + const pattern = /^([\w-]*?)([\d]+)$/; + + // sort morph target names into animation groups based + // patterns like Walk_001, Walk_002, Run_001, Run_002 + for ( let i = 0, il = morphTargets.length; i < il; i ++ ) { + + const morphTarget = morphTargets[ i ]; + const parts = morphTarget.name.match( pattern ); + + if ( parts && parts.length > 1 ) { + + const name = parts[ 1 ]; + + let animationMorphTargets = animationToMorphTargets[ name ]; + + if ( ! animationMorphTargets ) { + + animationToMorphTargets[ name ] = animationMorphTargets = []; + + } + + animationMorphTargets.push( morphTarget ); + + } + + } + + const clips = []; + + for ( const name in animationToMorphTargets ) { + + clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) ); + + } + + return clips; + + } + + /** + * Sets the duration of this clip to the duration of its longest keyframe track. + * + * @return {AnimationClip} A reference to this animation clip. + */ + resetDuration() { + + const tracks = this.tracks; + let duration = 0; + + for ( let i = 0, n = tracks.length; i !== n; ++ i ) { + + const track = this.tracks[ i ]; + + duration = Math.max( duration, track.times[ track.times.length - 1 ] ); + + } + + this.duration = duration; + + return this; + + } + + /** + * Trims all tracks to the clip's duration. + * + * @return {AnimationClip} A reference to this animation clip. + */ + trim() { + + for ( let i = 0; i < this.tracks.length; i ++ ) { + + this.tracks[ i ].trim( 0, this.duration ); + + } + + return this; + + } + + /** + * Performs minimal validation on each track in the clip. Returns `true` if all + * tracks are valid. + * + * @return {boolean} Whether the clip's keyframes are valid or not. + */ + validate() { + + let valid = true; + + for ( let i = 0; i < this.tracks.length; i ++ ) { + + valid = valid && this.tracks[ i ].validate(); + + } + + return valid; + + } + + /** + * Optimizes each track by removing equivalent sequential keys (which are + * common in morph target sequences). + * + * @return {AnimationClip} A reference to this animation clip. + */ + optimize() { + + for ( let i = 0; i < this.tracks.length; i ++ ) { + + this.tracks[ i ].optimize(); + + } + + return this; + + } + + /** + * Returns a new animation clip with copied values from this instance. + * + * @return {AnimationClip} A clone of this instance. + */ + clone() { + + const tracks = []; + + for ( let i = 0; i < this.tracks.length; i ++ ) { + + tracks.push( this.tracks[ i ].clone() ); + + } + + const clip = new this.constructor( this.name, this.duration, tracks, this.blendMode ); + + clip.userData = JSON.parse( JSON.stringify( this.userData ) ); + + return clip; + + } + + /** + * Serializes this animation clip into JSON. + * + * @return {Object} The JSON object. + */ + toJSON() { + + return this.constructor.toJSON( this ); + + } + +} + +function getTrackTypeForValueTypeName( typeName ) { + + switch ( typeName.toLowerCase() ) { + + case 'scalar': + case 'double': + case 'float': + case 'number': + case 'integer': + + return NumberKeyframeTrack; + + case 'vector': + case 'vector2': + case 'vector3': + case 'vector4': + + return VectorKeyframeTrack; + + case 'color': + + return ColorKeyframeTrack; + + case 'quaternion': + + return QuaternionKeyframeTrack; + + case 'bool': + case 'boolean': + + return BooleanKeyframeTrack; + + case 'string': + + return StringKeyframeTrack; + + } + + throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName ); + +} + +function parseKeyframeTrack( json ) { + + if ( json.type === undefined ) { + + throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' ); + + } + + const trackType = getTrackTypeForValueTypeName( json.type ); + + if ( json.times === undefined ) { + + const times = [], values = []; + + flattenJSON( json.keys, times, values, 'value' ); + + json.times = times; + json.values = values; + + } + + let track; + + // derived classes can define a static parse method + if ( trackType.parse !== undefined ) { + + track = trackType.parse( json ); + + } else { + + // by default, we assume a constructor compatible with the base + track = new trackType( json.name, json.times, json.values, json.interpolation ); + + } + + if ( hasTangents( json.settings ) ) { + + track.settings = { + inTangents: convertArray( json.settings.inTangents, Float32Array ), + outTangents: convertArray( json.settings.outTangents, Float32Array ) + }; + + } + + return track; + +} + +/** + * @class + * @classdesc A simple caching system, used internally by {@link FileLoader}. + * To enable caching across all loaders that use {@link FileLoader}, add `THREE.Cache.enabled = true.` once in your app. + * @hideconstructor + */ +const Cache = { + + /** + * Whether caching is enabled or not. + * + * @static + * @type {boolean} + * @default false + */ + enabled: false, + + /** + * A dictionary that holds cached files. + * + * @static + * @type {Object} + */ + files: {}, + + /** + * Adds a cache entry with a key to reference the file. If this key already + * holds a file, it is overwritten. + * + * @static + * @param {string} key - The key to reference the cached file. + * @param {Object} file - The file to be cached. + */ + add: function ( key, file ) { + + if ( this.enabled === false ) return; + + if ( isBlobURL( key ) ) return; + + // log( 'Cache', 'Adding key:', key ); + + this.files[ key ] = file; + + }, + + /** + * Gets the cached value for the given key. + * + * @static + * @param {string} key - The key to reference the cached file. + * @return {Object|undefined} The cached file. If the key does not exist `undefined` is returned. + */ + get: function ( key ) { + + if ( this.enabled === false ) return; + + if ( isBlobURL( key ) ) return; + + // log( 'Cache', 'Checking key:', key ); + + return this.files[ key ]; + + }, + + /** + * Removes the cached file associated with the given key. + * + * @static + * @param {string} key - The key to reference the cached file. + */ + remove: function ( key ) { + + delete this.files[ key ]; + + }, + + /** + * Remove all values from the cache. + * + * @static + */ + clear: function () { + + this.files = {}; + + } + +}; + +/** + * Returns true if the given cache key contains the blob: scheme. + * + * @private + * @param {string} key - The cache key. + * @return {boolean} Whether the given cache key contains the blob: scheme or not. + */ +function isBlobURL( key ) { + + try { + + const urlString = key.slice( key.indexOf( ':' ) + 1 ); // remove type identifier + + const url = new URL( urlString ); + return url.protocol === 'blob:'; + + } catch ( e ) { + + // If the string is not a valid URL, it throws an error + return false; + + } + +} + +/** + * Handles and keeps track of loaded and pending data. A default global + * instance of this class is created and used by loaders if not supplied + * manually. + * + * In general that should be sufficient, however there are times when it can + * be useful to have separate loaders - for example if you want to show + * separate loading bars for objects and textures. + * + * ```js + * const manager = new THREE.LoadingManager(); + * manager.onLoad = () => console.log( 'Loading complete!' ); + * + * const loader1 = new OBJLoader( manager ); + * const loader2 = new ColladaLoader( manager ); + * ``` + */ +class LoadingManager { + + /** + * Constructs a new loading manager. + * + * @param {Function} [onLoad] - Executes when all items have been loaded. + * @param {Function} [onProgress] - Executes when single items have been loaded. + * @param {Function} [onError] - Executes when an error occurs. + */ + constructor( onLoad, onProgress, onError ) { + + const scope = this; + + let isLoading = false; + let itemsLoaded = 0; + let itemsTotal = 0; + let urlModifier = undefined; + const handlers = []; + + // Refer to #5689 for the reason why we don't set .onStart + // in the constructor + + /** + * Executes when an item starts loading. + * + * @type {Function|undefined} + * @default undefined + */ + this.onStart = undefined; + + /** + * Executes when all items have been loaded. + * + * @type {Function|undefined} + * @default undefined + */ + this.onLoad = onLoad; + + /** + * Executes when single items have been loaded. + * + * @type {Function|undefined} + * @default undefined + */ + this.onProgress = onProgress; + + /** + * Executes when an error occurs. + * + * @type {Function|undefined} + * @default undefined + */ + this.onError = onError; + + /** + * Used for aborting ongoing requests in loaders using this manager. + * + * @private + * @type {AbortController | null} + */ + this._abortController = null; + + /** + * This should be called by any loader using the manager when the loader + * starts loading an item. + * + * @param {string} url - The URL to load. + */ + this.itemStart = function ( url ) { + + itemsTotal ++; + + if ( isLoading === false ) { + + if ( scope.onStart !== undefined ) { + + scope.onStart( url, itemsLoaded, itemsTotal ); + + } + + } + + isLoading = true; + + }; + + /** + * This should be called by any loader using the manager when the loader + * ended loading an item. + * + * @param {string} url - The URL of the loaded item. + */ + this.itemEnd = function ( url ) { + + itemsLoaded ++; + + if ( scope.onProgress !== undefined ) { + + scope.onProgress( url, itemsLoaded, itemsTotal ); + + } + + if ( itemsLoaded === itemsTotal ) { + + isLoading = false; + + if ( scope.onLoad !== undefined ) { + + scope.onLoad(); + + } + + } + + }; + + /** + * This should be called by any loader using the manager when the loader + * encounters an error when loading an item. + * + * @param {string} url - The URL of the item that produces an error. + */ + this.itemError = function ( url ) { + + if ( scope.onError !== undefined ) { + + scope.onError( url ); + + } + + }; + + /** + * Given a URL, uses the URL modifier callback (if any) and returns a + * resolved URL. If no URL modifier is set, returns the original URL. + * + * @param {string} url - The URL to load. + * @return {string} The resolved URL. + */ + this.resolveURL = function ( url ) { + + // Normalize to NFC so that Unicode URIs (e.g. from glTF) + // are percent-encoded correctly per RFC 3987. + + url = url.normalize( 'NFC' ); + + if ( urlModifier ) { + + return urlModifier( url ); + + } + + return url; + + }; + + /** + * If provided, the callback will be passed each resource URL before a + * request is sent. The callback may return the original URL, or a new URL to + * override loading behavior. This behavior can be used to load assets from + * .ZIP files, drag-and-drop APIs, and Data URIs. + * + * ```js + * const blobs = {'fish.gltf': blob1, 'diffuse.png': blob2, 'normal.png': blob3}; + * + * const manager = new THREE.LoadingManager(); + * + * // Initialize loading manager with URL callback. + * const objectURLs = []; + * manager.setURLModifier( ( url ) => { + * + * url = URL.createObjectURL( blobs[ url ] ); + * objectURLs.push( url ); + * return url; + * + * } ); + * + * // Load as usual, then revoke the blob URLs. + * const loader = new GLTFLoader( manager ); + * loader.load( 'fish.gltf', (gltf) => { + * + * scene.add( gltf.scene ); + * objectURLs.forEach( ( url ) => URL.revokeObjectURL( url ) ); + * + * } ); + * ``` + * + * @param {function(string):string} transform - URL modifier callback. Called with an URL and must return a resolved URL. + * @return {LoadingManager} A reference to this loading manager. + */ + this.setURLModifier = function ( transform ) { + + urlModifier = transform; + + return this; + + }; + + /** + * Registers a loader with the given regular expression. Can be used to + * define what loader should be used in order to load specific files. A + * typical use case is to overwrite the default loader for textures. + * + * ```js + * // add handler for TGA textures + * manager.addHandler( /\.tga$/i, new TGALoader() ); + * ``` + * + * @param {string} regex - A regular expression. + * @param {Loader} loader - A loader that should handle matched cases. + * @return {LoadingManager} A reference to this loading manager. + */ + this.addHandler = function ( regex, loader ) { + + handlers.push( regex, loader ); + + return this; + + }; + + /** + * Removes the loader for the given regular expression. + * + * @param {string} regex - A regular expression. + * @return {LoadingManager} A reference to this loading manager. + */ + this.removeHandler = function ( regex ) { + + const index = handlers.indexOf( regex ); + + if ( index !== -1 ) { + + handlers.splice( index, 2 ); + + } + + return this; + + }; + + /** + * Can be used to retrieve the registered loader for the given file path. + * + * @param {string} file - The file path. + * @return {?Loader} The registered loader. Returns `null` if no loader was found. + */ + this.getHandler = function ( file ) { + + for ( let i = 0, l = handlers.length; i < l; i += 2 ) { + + const regex = handlers[ i ]; + const loader = handlers[ i + 1 ]; + + if ( regex.global ) regex.lastIndex = 0; // see #17920 + + if ( regex.test( file ) ) { + + return loader; + + } + + } + + return null; + + }; + + /** + * Can be used to abort ongoing loading requests in loaders using this manager. + * The abort only works if the loaders implement {@link Loader#abort} and `AbortSignal.any()` + * is supported in the browser. + * + * @return {LoadingManager} A reference to this loading manager. + */ + this.abort = function () { + + + this.abortController.abort(); + this._abortController = null; + + return this; + + }; + + } + + // TODO: Revert this back to a single member variable once this issue has been fixed + // https://github.com/cloudflare/workerd/issues/3657 + + /** + * Used for aborting ongoing requests in loaders using this manager. + * + * @type {AbortController} + */ + get abortController() { + + if ( ! this._abortController ) { + + this._abortController = new AbortController(); + + } + + return this._abortController; + + } + +} + +/** + * The global default loading manager. + * + * @constant + * @type {LoadingManager} + */ +const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager(); + +/** + * Abstract base class for loaders. + * + * @abstract + */ +class Loader { + + /** + * Constructs a new loader. + * + * @param {LoadingManager} [manager] - The loading manager. + */ + constructor( manager ) { + + /** + * The loading manager. + * + * @type {LoadingManager} + * @default DefaultLoadingManager + */ + this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager; + + /** + * The crossOrigin string to implement CORS for loading the url from a + * different domain that allows CORS. + * + * @type {string} + * @default 'anonymous' + */ + this.crossOrigin = 'anonymous'; + + /** + * Whether the XMLHttpRequest uses credentials. + * + * @type {boolean} + * @default false + */ + this.withCredentials = false; + + /** + * The base path from which the asset will be loaded. + * + * @type {string} + */ + this.path = ''; + + /** + * The base path from which additional resources like textures will be loaded. + * + * @type {string} + */ + this.resourcePath = ''; + + /** + * The [request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header) + * used in HTTP request. + * + * @type {Object} + */ + this.requestHeader = {}; + + if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) { + + __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) ); + + } + + } + + /** + * This method needs to be implemented by all concrete loaders. It holds the + * logic for loading assets from the backend. + * + * @abstract + * @param {string} url - The path/URL of the file to be loaded. + * @param {Function} onLoad - Executed when the loading process has been finished. + * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress. + * @param {onErrorCallback} [onError] - Executed when errors occur. + */ + load( /* url, onLoad, onProgress, onError */ ) {} + + /** + * A async version of {@link Loader#load}. + * + * @param {string} url - The path/URL of the file to be loaded. + * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress. + * @return {Promise} A Promise that resolves when the asset has been loaded. + */ + loadAsync( url, onProgress ) { + + const scope = this; + + return new Promise( function ( resolve, reject ) { + + scope.load( url, resolve, onProgress, reject ); + + } ); + + } + + /** + * This method needs to be implemented by all concrete loaders. It holds the + * logic for parsing the asset into three.js entities. + * + * @abstract + * @param {any} data - The data to parse. + */ + parse( /* data */ ) {} + + /** + * Sets the `crossOrigin` String to implement CORS for loading the URL + * from a different domain that allows CORS. + * + * @param {string} crossOrigin - The `crossOrigin` value. + * @return {Loader} A reference to this instance. + */ + setCrossOrigin( crossOrigin ) { + + this.crossOrigin = crossOrigin; + return this; + + } + + /** + * Whether the XMLHttpRequest uses credentials such as cookies, authorization + * headers or TLS client certificates, see [XMLHttpRequest.withCredentials](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials). + * + * Note: This setting has no effect if you are loading files locally or from the same domain. + * + * @param {boolean} value - The `withCredentials` value. + * @return {Loader} A reference to this instance. + */ + setWithCredentials( value ) { + + this.withCredentials = value; + return this; + + } + + /** + * Sets the base path for the asset. + * + * @param {string} path - The base path. + * @return {Loader} A reference to this instance. + */ + setPath( path ) { + + this.path = path; + return this; + + } + + /** + * Sets the base path for dependent resources like textures. + * + * @param {string} resourcePath - The resource path. + * @return {Loader} A reference to this instance. + */ + setResourcePath( resourcePath ) { + + this.resourcePath = resourcePath; + return this; + + } + + /** + * Sets the given request header. + * + * @param {Object} requestHeader - A [request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header) + * for configuring the HTTP request. + * @return {Loader} A reference to this instance. + */ + setRequestHeader( requestHeader ) { + + this.requestHeader = requestHeader; + return this; + + } + + /** + * This method can be implemented in loaders for aborting ongoing requests. + * + * @abstract + * @return {Loader} A reference to this instance. + */ + abort() { + + return this; + + } + +} + +/** + * Callback for onProgress in loaders. + * + * @callback onProgressCallback + * @param {ProgressEvent} event - An instance of `ProgressEvent` that represents the current loading status. + */ + +/** + * Callback for onError in loaders. + * + * @callback onErrorCallback + * @param {Error} error - The error which occurred during the loading process. + */ + +/** + * The default material name that is used by loaders + * when creating materials for loaded 3D objects. + * + * Note: Not all loaders might honor this setting. + * + * @static + * @type {string} + * @default '__DEFAULT' + */ +Loader.DEFAULT_MATERIAL_NAME = '__DEFAULT'; + +const loading = {}; + +class HttpError extends Error { + + constructor( message, response ) { + + super( message ); + this.response = response; + + } + +} + +/** + * A low level class for loading resources with the Fetch API, used internally by + * most loaders. It can also be used directly to load any file type that does + * not have a loader. + * + * This loader supports caching. If you want to use it, add `THREE.Cache.enabled = true;` + * once to your application. + * + * ```js + * const loader = new THREE.FileLoader(); + * const data = await loader.loadAsync( 'example.txt' ); + * ``` + * + * @augments Loader + */ +class FileLoader extends Loader { + + /** + * Constructs a new file loader. + * + * @param {LoadingManager} [manager] - The loading manager. + */ + constructor( manager ) { + + super( manager ); + + /** + * The expected mime type. Valid values can be found + * [here](https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString#mimetype) + * + * @type {string} + */ + this.mimeType = ''; + + /** + * The expected response type. + * + * @type {('arraybuffer'|'blob'|'document'|'json'|'')} + * @default '' + */ + this.responseType = ''; + + /** + * Used for aborting requests. + * + * @private + * @type {AbortController} + */ + this._abortController = new AbortController(); + + } + + /** + * Starts loading from the given URL and pass the loaded response to the `onLoad()` callback. + * + * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI. + * @param {function(any)} onLoad - Executed when the loading process has been finished. + * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress. + * @param {onErrorCallback} [onError] - Executed when errors occur. + */ + load( url, onLoad, onProgress, onError ) { + + if ( url === undefined ) url = ''; + + if ( this.path !== undefined ) url = this.path + url; + + url = this.manager.resolveURL( url ); + + const cached = Cache.get( `file:${url}` ); + + if ( cached !== undefined ) { + + this.manager.itemStart( url ); + + setTimeout( () => { + + if ( onLoad ) onLoad( cached ); + + this.manager.itemEnd( url ); + + }, 0 ); + + return; + + } + + // Check if request is duplicate + + if ( loading[ url ] !== undefined ) { + + loading[ url ].push( { + + onLoad: onLoad, + onProgress: onProgress, + onError: onError + + } ); + + return; + + } + + // Initialise array for duplicate requests + loading[ url ] = []; + + loading[ url ].push( { + onLoad: onLoad, + onProgress: onProgress, + onError: onError, + } ); + + // create request + const req = new Request( url, { + headers: new Headers( this.requestHeader ), + credentials: this.withCredentials ? 'include' : 'same-origin', + signal: ( typeof AbortSignal.any === 'function' ) ? AbortSignal.any( [ this._abortController.signal, this.manager.abortController.signal ] ) : this._abortController.signal + } ); + + // record states ( avoid data race ) + const mimeType = this.mimeType; + const responseType = this.responseType; + + // start the fetch + fetch( req ) + .then( response => { + + if ( response.status === 200 || response.status === 0 ) { + + // Some browsers return HTTP Status 0 when using non-http protocol + // e.g. 'file://' or 'data://'. Handle as success. + + if ( response.status === 0 ) { + + warn( 'FileLoader: HTTP Status 0 received.' ); + + } + + // Workaround: Checking if response.body === undefined for Alipay browser #23548 + + if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) { + + return response; + + } + + const callbacks = loading[ url ]; + const reader = response.body.getReader(); + + // Nginx needs X-File-Size check + // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content + const contentLength = response.headers.get( 'X-File-Size' ) || response.headers.get( 'Content-Length' ); + const total = contentLength ? parseInt( contentLength ) : 0; + const lengthComputable = total !== 0; + let loaded = 0; + + // periodically read data into the new stream tracking while download progress + const stream = new ReadableStream( { + start( controller ) { + + readData(); + + function readData() { + + reader.read().then( ( { done, value } ) => { + + if ( done ) { + + controller.close(); + + } else { + + loaded += value.byteLength; + + const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } ); + for ( let i = 0, il = callbacks.length; i < il; i ++ ) { + + const callback = callbacks[ i ]; + if ( callback.onProgress ) callback.onProgress( event ); + + } + + controller.enqueue( value ); + readData(); + + } + + }, ( e ) => { + + controller.error( e ); + + } ); + + } + + } + + } ); + + return new Response( stream ); + + } else { + + throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response ); + + } + + } ) + .then( response => { + + switch ( responseType ) { + + case 'arraybuffer': + + return response.arrayBuffer(); + + case 'blob': + + return response.blob(); + + case 'document': + + return response.text() + .then( text => { + + const parser = new DOMParser(); + return parser.parseFromString( text, mimeType ); + + } ); + + case 'json': + + return response.json(); + + default: + + if ( mimeType === '' ) { + + return response.text(); + + } else { + + // sniff encoding + const re = /charset="?([^;"\s]*)"?/i; + const exec = re.exec( mimeType ); + const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined; + const decoder = new TextDecoder( label ); + return response.arrayBuffer().then( ab => decoder.decode( ab ) ); + + } + + } + + } ) + .then( data => { + + // Add to cache only on HTTP success, so that we do not cache + // error response bodies as proper responses to requests. + Cache.add( `file:${url}`, data ); + + const callbacks = loading[ url ]; + delete loading[ url ]; + + for ( let i = 0, il = callbacks.length; i < il; i ++ ) { + + const callback = callbacks[ i ]; + if ( callback.onLoad ) callback.onLoad( data ); + + } + + } ) + .catch( err => { + + // Abort errors and other errors are handled the same + + const callbacks = loading[ url ]; + + if ( callbacks === undefined ) { + + // When onLoad was called and url was deleted in `loading` + this.manager.itemError( url ); + throw err; + + } + + delete loading[ url ]; + + for ( let i = 0, il = callbacks.length; i < il; i ++ ) { + + const callback = callbacks[ i ]; + if ( callback.onError ) callback.onError( err ); + + } + + this.manager.itemError( url ); + + } ) + .finally( () => { + + this.manager.itemEnd( url ); + + } ); + + this.manager.itemStart( url ); + + } + + /** + * Sets the expected response type. + * + * @param {('arraybuffer'|'blob'|'document'|'json'|'')} value - The response type. + * @return {FileLoader} A reference to this file loader. + */ + setResponseType( value ) { + + this.responseType = value; + return this; + + } + + /** + * Sets the expected mime type of the loaded file. + * + * @param {string} value - The mime type. + * @return {FileLoader} A reference to this file loader. + */ + setMimeType( value ) { + + this.mimeType = value; + return this; + + } + + /** + * Aborts ongoing fetch requests. + * + * @return {FileLoader} A reference to this instance. + */ + abort() { + + this._abortController.abort(); + this._abortController = new AbortController(); + + return this; + + } + +} + +/** + * Class for loading animation clips in the JSON format. The files are internally + * loaded via {@link FileLoader}. + * + * ```js + * const loader = new THREE.AnimationLoader(); + * const animations = await loader.loadAsync( 'animations/animation.js' ); + * ``` + * + * @augments Loader + */ +class AnimationLoader extends Loader { + + /** + * Constructs a new animation loader. + * + * @param {LoadingManager} [manager] - The loading manager. + */ + constructor( manager ) { + + super( manager ); + + } + + /** + * Starts loading from the given URL and pass the loaded animations as an array + * holding instances of {@link AnimationClip} to the `onLoad()` callback. + * + * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI. + * @param {function(Array)} onLoad - Executed when the loading process has been finished. + * @param {onProgressCallback} onProgress - Executed while the loading is in progress. + * @param {onErrorCallback} onError - Executed when errors occur. + */ + load( url, onLoad, onProgress, onError ) { + + const scope = this; + + const loader = new FileLoader( this.manager ); + loader.setPath( this.path ); + loader.setRequestHeader( this.requestHeader ); + loader.setWithCredentials( this.withCredentials ); + loader.load( url, function ( text ) { + + try { + + onLoad( scope.parse( JSON.parse( text ) ) ); + + } catch ( e ) { + + if ( onError ) { + + onError( e ); + + } else { + + error( e ); + + } + + scope.manager.itemError( url ); + + } + + }, onProgress, onError ); + + } + + /** + * Parses the given JSON object and returns an array of animation clips. + * + * @param {Object} json - The serialized animation clips. + * @return {Array} The parsed animation clips. + */ + parse( json ) { + + const animations = []; + + for ( let i = 0; i < json.length; i ++ ) { + + const clip = AnimationClip.parse( json[ i ] ); + + animations.push( clip ); + + } + + return animations; + + } + +} + +/** + * Abstract base class for loading compressed texture formats S3TC, ASTC or ETC. + * Textures are internally loaded via {@link FileLoader}. + * + * Derived classes have to implement the `parse()` method which holds the parsing + * for the respective format. + * + * @abstract + * @augments Loader + */ +class CompressedTextureLoader extends Loader { + + /** + * Constructs a new compressed texture loader. + * + * @param {LoadingManager} [manager] - The loading manager. + */ + constructor( manager ) { + + super( manager ); + + } + + /** + * Starts loading from the given URL and passes the loaded compressed texture + * to the `onLoad()` callback. The method also returns a new texture object which can + * directly be used for material creation. If you do it this way, the texture + * may pop up in your scene once the respective loading process is finished. + * + * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI. + * @param {function(CompressedTexture)} onLoad - Executed when the loading process has been finished. + * @param {onProgressCallback} onProgress - Executed while the loading is in progress. + * @param {onErrorCallback} onError - Executed when errors occur. + * @return {CompressedTexture} The compressed texture. + */ + load( url, onLoad, onProgress, onError ) { + + const scope = this; + + const images = []; + + const texture = new CompressedTexture(); + + const loader = new FileLoader( this.manager ); + loader.setPath( this.path ); + loader.setResponseType( 'arraybuffer' ); + loader.setRequestHeader( this.requestHeader ); + loader.setWithCredentials( scope.withCredentials ); + + let loaded = 0; + + function loadTexture( i ) { + + loader.load( url[ i ], function ( buffer ) { + + const texDatas = scope.parse( buffer, true ); + + images[ i ] = { + width: texDatas.width, + height: texDatas.height, + format: texDatas.format, + mipmaps: texDatas.mipmaps + }; + + loaded += 1; + + if ( loaded === 6 ) { + + if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter; + + texture.image = images; + texture.format = texDatas.format; + texture.needsUpdate = true; + + if ( onLoad ) onLoad( texture ); + + } + + }, onProgress, onError ); + + } + + if ( Array.isArray( url ) ) { + + for ( let i = 0, il = url.length; i < il; ++ i ) { + + loadTexture( i ); + + } + + } else { + + // compressed cubemap texture stored in a single DDS file + + loader.load( url, function ( buffer ) { + + const texDatas = scope.parse( buffer, true ); + + if ( texDatas.isCubemap ) { + + const faces = texDatas.mipmaps.length / texDatas.mipmapCount; + + for ( let f = 0; f < faces; f ++ ) { + + images[ f ] = { mipmaps: [] }; + + for ( let i = 0; i < texDatas.mipmapCount; i ++ ) { + + images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] ); + images[ f ].format = texDatas.format; + images[ f ].width = texDatas.width; + images[ f ].height = texDatas.height; + + } + + } + + texture.image = images; + + } else { + + texture.image.width = texDatas.width; + texture.image.height = texDatas.height; + texture.mipmaps = texDatas.mipmaps; + + } + + if ( texDatas.mipmapCount === 1 ) { + + texture.minFilter = LinearFilter; + + } + + texture.format = texDatas.format; + texture.needsUpdate = true; + + if ( onLoad ) onLoad( texture ); + + }, onProgress, onError ); + + } + + return texture; + + } + +} + +const _loading = new WeakMap(); + +/** + * A loader for loading images. The class loads images with the HTML `Image` API. + * + * ```js + * const loader = new THREE.ImageLoader(); + * const image = await loader.loadAsync( 'image.png' ); + * ``` + * Please note that `ImageLoader` has dropped support for progress + * events in `r84`. For an `ImageLoader` that supports progress events, see + * [this thread](https://github.com/mrdoob/three.js/issues/10439#issuecomment-275785639). + * + * @augments Loader + */ +class ImageLoader extends Loader { + + /** + * Constructs a new image loader. + * + * @param {LoadingManager} [manager] - The loading manager. + */ + constructor( manager ) { + + super( manager ); + + } + + /** + * Starts loading from the given URL and passes the loaded image + * to the `onLoad()` callback. The method also returns a new `Image` object which can + * directly be used for texture creation. If you do it this way, the texture + * may pop up in your scene once the respective loading process is finished. + * + * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI. + * @param {function(Image)} onLoad - Executed when the loading process has been finished. + * @param {onProgressCallback} onProgress - Unsupported in this loader. + * @param {onErrorCallback} onError - Executed when errors occur. + * @return {Image} The image. + */ + load( url, onLoad, onProgress, onError ) { + + if ( this.path !== undefined ) url = this.path + url; + + url = this.manager.resolveURL( url ); + + const scope = this; + + const cached = Cache.get( `image:${url}` ); + + if ( cached !== undefined ) { + + if ( cached.complete === true ) { + + scope.manager.itemStart( url ); + + setTimeout( function () { + + if ( onLoad ) onLoad( cached ); + + scope.manager.itemEnd( url ); + + }, 0 ); + + } else { + + let arr = _loading.get( cached ); + + if ( arr === undefined ) { + + arr = []; + _loading.set( cached, arr ); + + } + + arr.push( { onLoad, onError } ); + + } + + return cached; + + } + + const image = createElementNS( 'img' ); + + function onImageLoad() { + + removeEventListeners(); + + if ( onLoad ) onLoad( this ); + + // + + const callbacks = _loading.get( this ) || []; + + for ( let i = 0; i < callbacks.length; i ++ ) { + + const callback = callbacks[ i ]; + if ( callback.onLoad ) callback.onLoad( this ); + + } + + _loading.delete( this ); + + scope.manager.itemEnd( url ); + + } + + function onImageError( event ) { + + removeEventListeners(); + + if ( onError ) onError( event ); + + Cache.remove( `image:${url}` ); + + // + + const callbacks = _loading.get( this ) || []; + + for ( let i = 0; i < callbacks.length; i ++ ) { + + const callback = callbacks[ i ]; + if ( callback.onError ) callback.onError( event ); + + } + + _loading.delete( this ); + + + scope.manager.itemError( url ); + scope.manager.itemEnd( url ); + + } + + function removeEventListeners() { + + image.removeEventListener( 'load', onImageLoad, false ); + image.removeEventListener( 'error', onImageError, false ); + + } + + image.addEventListener( 'load', onImageLoad, false ); + image.addEventListener( 'error', onImageError, false ); + + if ( url.slice( 0, 5 ) !== 'data:' ) { + + if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin; + + } + + Cache.add( `image:${url}`, image ); + scope.manager.itemStart( url ); + + image.src = url; + + return image; + + } + +} + +/** + * Class for loading cube textures. Images are internally loaded via {@link ImageLoader}. + * + * The loader returns an instance of {@link CubeTexture} and expects the cube map to + * be defined as six separate images representing the sides of a cube. Other cube map definitions + * like vertical and horizontal cross, column and row layouts are not supported. + * + * Note that, by convention, cube maps are specified in a coordinate system + * in which positive-x is to the right when looking up the positive-z axis -- + * in other words, using a left-handed coordinate system. Since three.js uses + * a right-handed coordinate system, environment maps used in three.js will + * have pos-x and neg-x swapped. + * + * The loaded cube texture is in sRGB color space. Meaning {@link Texture#colorSpace} + * is set to `SRGBColorSpace` by default. + * + * ```js + * const loader = new THREE.CubeTextureLoader().setPath( 'textures/cubeMaps/' ); + * const cubeTexture = await loader.loadAsync( [ + * 'px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png' + * ] ); + * scene.background = cubeTexture; + * ``` + * + * @augments Loader + */ +class CubeTextureLoader extends Loader { + + /** + * Constructs a new cube texture loader. + * + * @param {LoadingManager} [manager] - The loading manager. + */ + constructor( manager ) { + + super( manager ); + + } + + /** + * Starts loading from the given URL and pass the fully loaded cube texture + * to the `onLoad()` callback. The method also returns a new cube texture object which can + * directly be used for material creation. If you do it this way, the cube texture + * may pop up in your scene once the respective loading process is finished. + * + * @param {Array} urls - Array of 6 URLs to images, one for each side of the + * cube texture. The urls should be specified in the following order: pos-x, + * neg-x, pos-y, neg-y, pos-z, neg-z. An array of data URIs are allowed as well. + * @param {function(CubeTexture)} onLoad - Executed when the loading process has been finished. + * @param {onProgressCallback} onProgress - Unsupported in this loader. + * @param {onErrorCallback} onError - Executed when errors occur. + * @return {CubeTexture} The cube texture. + */ + load( urls, onLoad, onProgress, onError ) { + + const texture = new CubeTexture(); + texture.colorSpace = SRGBColorSpace; + + const loader = new ImageLoader( this.manager ); + loader.setCrossOrigin( this.crossOrigin ); + loader.setPath( this.path ); + + let loaded = 0; + + function loadTexture( i ) { + + loader.load( urls[ i ], function ( image ) { + + texture.images[ i ] = image; + + loaded ++; + + if ( loaded === 6 ) { + + texture.needsUpdate = true; + + if ( onLoad ) onLoad( texture ); + + } + + }, undefined, onError ); + + } + + for ( let i = 0; i < urls.length; ++ i ) { + + loadTexture( i ); + + } + + return texture; + + } + +} + +/** + * Abstract base class for loading binary texture formats RGBE, EXR or TGA. + * Textures are internally loaded via {@link FileLoader}. + * + * Derived classes have to implement the `parse()` method which holds the parsing + * for the respective format. + * + * @abstract + * @augments Loader + */ +class DataTextureLoader extends Loader { + + /** + * Constructs a new data texture loader. + * + * @param {LoadingManager} [manager] - The loading manager. + */ + constructor( manager ) { + + super( manager ); + + } + + /** + * Starts loading from the given URL and passes the loaded data texture + * to the `onLoad()` callback. The method also returns a new texture object which can + * directly be used for material creation. If you do it this way, the texture + * may pop up in your scene once the respective loading process is finished. + * + * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI. + * @param {function(DataTexture)} onLoad - Executed when the loading process has been finished. + * @param {onProgressCallback} onProgress - Executed while the loading is in progress. + * @param {onErrorCallback} onError - Executed when errors occur. + * @return {DataTexture} The data texture. + */ + load( url, onLoad, onProgress, onError ) { + + const scope = this; + + const texture = new DataTexture(); + + const loader = new FileLoader( this.manager ); + loader.setResponseType( 'arraybuffer' ); + loader.setRequestHeader( this.requestHeader ); + loader.setPath( this.path ); + loader.setWithCredentials( scope.withCredentials ); + loader.load( url, function ( buffer ) { + + let texData; + + try { + + texData = scope.parse( buffer ); + + } catch ( e ) { + + if ( onError !== undefined ) { + + onError( e ); + + } else { + + error( e ); + + } + + return; + + } + + scope._applyTexData( texture, texData ); + + if ( onLoad ) onLoad( texture, texData ); + + }, onProgress, onError ); + + + return texture; + + } + + /** + * Parses the given buffer and returns a configured data texture. Use this method + * for parsing texture data that is already in memory (e.g. drag and drop or data + * loaded from a server) without going through {@link DataTextureLoader#load}. + * + * @param {ArrayBuffer} buffer - The raw texture data. + * @return {DataTexture} The data texture. + */ + createDataTexture( buffer ) { + + const texture = new DataTexture(); + + this._applyTexData( texture, this.parse( buffer ) ); + + return texture; + + } + + /** + * Applies the given parsed texture data to the given data texture. + * + * @private + * @param {DataTexture} texture - The data texture. + * @param {DataTextureLoader~TexData} texData - The parsed texture data. + */ + _applyTexData( texture, texData ) { + + if ( texData.image !== undefined ) { + + texture.image = texData.image; + + } else if ( texData.data !== undefined ) { + + texture.image.width = texData.width; + texture.image.height = texData.height; + texture.image.data = texData.data; + + } + + texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping; + texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping; + + texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter; + texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter; + + texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1; + + if ( texData.colorSpace !== undefined ) { + + texture.colorSpace = texData.colorSpace; + + } + + if ( texData.flipY !== undefined ) { + + texture.flipY = texData.flipY; + + } + + if ( texData.format !== undefined ) { + + texture.format = texData.format; + + } + + if ( texData.type !== undefined ) { + + texture.type = texData.type; + + } + + if ( texData.mipmaps !== undefined ) { + + texture.mipmaps = texData.mipmaps; + texture.minFilter = LinearMipmapLinearFilter; // presumably... + + } + + if ( texData.mipmapCount === 1 ) { + + texture.minFilter = LinearFilter; + + } + + if ( texData.generateMipmaps !== undefined ) { + + texture.generateMipmaps = texData.generateMipmaps; + + } + + texture.needsUpdate = true; + + } + +} + +/** + * Class for loading textures. Images are internally + * loaded via {@link ImageLoader}. + * + * ```js + * const loader = new THREE.TextureLoader(); + * const texture = await loader.loadAsync( 'textures/land_ocean_ice_cloud_2048.jpg' ); + * + * const material = new THREE.MeshBasicMaterial( { map:texture } ); + * ``` + * Please note that `TextureLoader` has dropped support for progress + * events in `r84`. For a `TextureLoader` that supports progress events, see + * [this thread](https://github.com/mrdoob/three.js/issues/10439#issuecomment-293260145). + * + * @augments Loader + */ +class TextureLoader extends Loader { + + /** + * Constructs a new texture loader. + * + * @param {LoadingManager} [manager] - The loading manager. + */ + constructor( manager ) { + + super( manager ); + + } + + /** + * Starts loading from the given URL and pass the fully loaded texture + * to the `onLoad()` callback. The method also returns a new texture object which can + * directly be used for material creation. If you do it this way, the texture + * may pop up in your scene once the respective loading process is finished. + * + * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI. + * @param {function(Texture)} onLoad - Executed when the loading process has been finished. + * @param {onProgressCallback} onProgress - Unsupported in this loader. + * @param {onErrorCallback} onError - Executed when errors occur. + * @return {Texture} The texture. + */ + load( url, onLoad, onProgress, onError ) { + + const texture = new Texture(); + + const loader = new ImageLoader( this.manager ); + loader.setCrossOrigin( this.crossOrigin ); + loader.setPath( this.path ); + + loader.load( url, function ( image ) { + + texture.image = image; + texture.needsUpdate = true; + + if ( onLoad !== undefined ) { + + onLoad( texture ); + + } + + }, onProgress, onError ); + + return texture; + + } + +} + +/** + * Abstract base class for lights - all other light types inherit the + * properties and methods described here. + * + * @abstract + * @augments Object3D + */ +class Light extends Object3D { + + /** + * Constructs a new light. + * + * @param {(number|Color|string)} [color=0xffffff] - The light's color. + * @param {number} [intensity=1] - The light's strength/intensity. + */ + constructor( color, intensity = 1 ) { + + super(); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isLight = true; + + this.type = 'Light'; + + /** + * The light's color. + * + * @type {Color} + */ + this.color = new Color( color ); + + /** + * The light's intensity. + * + * @type {number} + * @default 1 + */ + this.intensity = intensity; + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + this.color.copy( source.color ); + this.intensity = source.intensity; + + return this; + + } + + toJSON( meta ) { + + const data = super.toJSON( meta ); + + data.object.color = this.color.getHex(); + data.object.intensity = this.intensity; + + return data; + + } + +} + +/** + * A light source positioned directly above the scene, with color fading from + * the sky color to the ground color. + * + * This light cannot be used to cast shadows. + * + * ```js + * const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 ); + * scene.add( light ); + * ``` + * + * @augments Light + */ +class HemisphereLight extends Light { + + /** + * Constructs a new hemisphere light. + * + * @param {(number|Color|string)} [skyColor=0xffffff] - The light's sky color. + * @param {(number|Color|string)} [groundColor=0xffffff] - The light's ground color. + * @param {number} [intensity=1] - The light's strength/intensity. + */ + constructor( skyColor, groundColor, intensity ) { + + super( skyColor, intensity ); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isHemisphereLight = true; + + this.type = 'HemisphereLight'; + + this.position.copy( Object3D.DEFAULT_UP ); + this.updateMatrix(); + + /** + * The light's ground color. + * + * @type {Color} + */ + this.groundColor = new Color( groundColor ); + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + this.groundColor.copy( source.groundColor ); + + return this; + + } + + toJSON( meta ) { + + const data = super.toJSON( meta ); + + data.object.groundColor = this.groundColor.getHex(); + + return data; + + } + +} + +const _projScreenMatrix = /*@__PURE__*/ new Matrix4(); +const _lightPositionWorld = /*@__PURE__*/ new Vector3(); +const _lookTarget = /*@__PURE__*/ new Vector3(); + +/** + * Abstract base class for light shadow classes. These classes + * represent the shadow configuration for different light types. + * + * @abstract + */ +class LightShadow { + + /** + * Constructs a new light shadow. + * + * @param {Camera} camera - The light's view of the world. + */ + constructor( camera ) { + + /** + * The light's view of the world. + * + * @type {Camera} + */ + this.camera = camera; + + /** + * The intensity of the shadow. The default is `1`. + * Valid values are in the range `[0, 1]`. + * + * @type {number} + * @default 1 + */ + this.intensity = 1; + + /** + * Shadow map bias, how much to add or subtract from the normalized depth + * when deciding whether a surface is in shadow. + * + * The default is `0`. Very tiny adjustments here (in the order of `0.0001`) + * may help reduce artifacts in shadows. + * + * @type {number} + * @default 0 + */ + this.bias = 0; + + /** + * A node version of `bias`. Only supported with `WebGPURenderer`. + * + * If a bias node is defined, `bias` has no effect. + * + * @type {?Node} + * @default null + */ + this.biasNode = null; + + /** + * Defines how much the position used to query the shadow map is offset along + * the object normal. The default is `0`. Increasing this value can be used to + * reduce shadow acne especially in large scenes where light shines onto + * geometry at a shallow angle. The cost is that shadows may appear distorted. + * + * @type {number} + * @default 0 + */ + this.normalBias = 0; + + /** + * Setting this to values greater than 1 will blur the edges of the shadow. + * High values will cause unwanted banding effects in the shadows - a greater + * map size will allow for a higher value to be used here before these effects + * become visible. + * + * The property has no effect when the shadow map type is `BasicShadowMap`. + * + * @type {number} + * @default 1 + */ + this.radius = 1; + + /** + * The amount of samples to use when blurring a VSM shadow map. + * + * @type {number} + * @default 8 + */ + this.blurSamples = 8; + + /** + * Defines the width and height of the shadow map. Higher values give better quality + * shadows at the cost of computation time. Values must be powers of two. + * + * @type {Vector2} + * @default (512,512) + */ + this.mapSize = new Vector2( 512, 512 ); + + /** + * The type of shadow texture. The default is `UnsignedByteType`. + * + * @type {number} + * @default UnsignedByteType + */ + this.mapType = UnsignedByteType; + + /** + * The depth map generated using the internal camera; a location beyond a + * pixel's depth is in shadow. Computed internally during rendering. + * + * @type {?RenderTarget} + * @default null + */ + this.map = null; + + /** + * The distribution map generated using the internal camera; an occlusion is + * calculated based on the distribution of depths. Computed internally during + * rendering. + * + * @type {?RenderTarget} + * @default null + */ + this.mapPass = null; + + /** + * Model to shadow camera space, to compute location and depth in shadow map. + * This is computed internally during rendering. + * + * @type {Matrix4} + */ + this.matrix = new Matrix4(); + + /** + * Enables automatic updates of the light's shadow. If you do not require dynamic + * lighting / shadows, you may set this to `false`. + * + * @type {boolean} + * @default true + */ + this.autoUpdate = true; + + /** + * When set to `true`, shadow maps will be updated in the next `render` call. + * If you have set {@link LightShadow#autoUpdate} to `false`, you will need to + * set this property to `true` and then make a render call to update the light's shadow. + * + * @type {boolean} + * @default false + */ + this.needsUpdate = false; + + this._frustum = new Frustum(); + this._frameExtents = new Vector2( 1, 1 ); + + this._viewportCount = 1; + + this._viewports = [ + + new Vector4( 0, 0, 1, 1 ) + + ]; + + } + + /** + * Used internally by the renderer to get the number of viewports that need + * to be rendered for this shadow. + * + * @return {number} The viewport count. + */ + getViewportCount() { + + return this._viewportCount; + + } + + /** + * Used internally by the renderer to get the camera that renders the given viewport. + * + * @param {number} [viewportIndex=0] - The viewport index. + * @return {Camera} The shadow camera. + */ + getCamera( /* viewportIndex */ ) { + + return this.camera; + + } + + /** + * Gets the shadow cameras frustum. Used internally by the renderer to cull objects. + * + * @return {Frustum} The shadow camera frustum. + */ + getFrustum() { + + return this._frustum; + + } + + /** + * Update the matrices for the camera and shadow, used internally by the renderer. + * + * @param {Light} light - The light for which the shadow is being rendered. + */ + updateMatrices( light ) { + + const shadowCamera = this.camera; + _lightPositionWorld.setFromMatrixPosition( light.matrixWorld ); + shadowCamera.position.copy( _lightPositionWorld ); + + _lookTarget.setFromMatrixPosition( light.target.matrixWorld ); + shadowCamera.lookAt( _lookTarget ); + shadowCamera.updateMatrixWorld(); + this._updateMatrix( shadowCamera, this.matrix, this._frustum ); + + } + + /** + * Updates a shadow projection matrix and its corresponding frustum. + * + * @private + * @param {Camera} shadowCamera - The shadow camera. + * @param {Matrix4} shadowMatrix - The target shadow matrix. + * @param {Frustum} frustum - The target frustum. + * @param {Vector4} [viewport] - The viewport within the shadow atlas. + */ + _updateMatrix( shadowCamera, shadowMatrix, frustum, viewport ) { + + _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse ); + frustum.setFromProjectionMatrix( _projScreenMatrix, shadowCamera.coordinateSystem, shadowCamera.reversedDepth ); + + const frameExtents = this._frameExtents; + const scaleX = viewport ? viewport.z / frameExtents.x : 1; + const scaleY = viewport ? viewport.w / frameExtents.y : 1; + const offsetX = viewport ? viewport.x / frameExtents.x : 0; + const offsetY = viewport ? viewport.y / frameExtents.y : 0; + + if ( shadowCamera.coordinateSystem === WebGPUCoordinateSystem || shadowCamera.reversedDepth ) { + + shadowMatrix.set( + 0.5 * scaleX, 0.0, 0.0, 0.5 * scaleX + offsetX, + 0.0, 0.5 * scaleY, 0.0, 0.5 * scaleY + offsetY, + 0.0, 0.0, 1.0, 0.0, // Identity Z (preserving the correct [0, 1] range from the projection matrix) + 0.0, 0.0, 0.0, 1.0 + ); + + } else { + + shadowMatrix.set( + 0.5 * scaleX, 0.0, 0.0, 0.5 * scaleX + offsetX, + 0.0, 0.5 * scaleY, 0.0, 0.5 * scaleY + offsetY, + 0.0, 0.0, 0.5, 0.5, + 0.0, 0.0, 0.0, 1.0 + ); + + } + + shadowMatrix.multiply( _projScreenMatrix ); + + } + + /** + * Returns a viewport definition for the given viewport index. + * + * @param {number} viewportIndex - The viewport index. + * @return {Vector4} The viewport. + */ + getViewport( viewportIndex ) { + + return this._viewports[ viewportIndex ]; + + } + + /** + * Returns the frame extends. + * + * @return {Vector2} The frame extends. + */ + getFrameExtents() { + + return this._frameExtents; + + } + + /** + * Frees the GPU-related resources allocated by this instance. Call this + * method whenever this instance is no longer used in your app. + */ + dispose() { + + if ( this.map ) { + + this.map.dispose(); + + } + + if ( this.mapPass ) { + + this.mapPass.dispose(); + + } + + } + + /** + * Copies the values of the given light shadow instance to this instance. + * + * @param {LightShadow} source - The light shadow to copy. + * @return {LightShadow} A reference to this light shadow instance. + */ + copy( source ) { + + this.camera = source.camera.clone(); + + this.intensity = source.intensity; + + this.bias = source.bias; + this.radius = source.radius; + + this.autoUpdate = source.autoUpdate; + this.needsUpdate = source.needsUpdate; + this.normalBias = source.normalBias; + this.blurSamples = source.blurSamples; + + this.mapSize.copy( source.mapSize ); + + this.biasNode = source.biasNode; + + return this; + + } + + /** + * Returns a new light shadow instance with copied values from this instance. + * + * @return {LightShadow} A clone of this instance. + */ + clone() { + + return new this.constructor().copy( this ); + + } + + /** + * Serializes the light shadow into JSON. + * + * @return {Object} A JSON object representing the serialized light shadow. + * @see {@link ObjectLoader#parse} + */ + toJSON() { + + const object = {}; + + object.intensity = this.intensity; + object.bias = this.bias; + object.normalBias = this.normalBias; + object.radius = this.radius; + object.blurSamples = this.blurSamples; + object.mapSize = this.mapSize.toArray(); + + object.camera = this.camera.toJSON( false ).object; + delete object.camera.matrix; + + return object; + + } + +} + +const _position$2 = /*@__PURE__*/ new Vector3(); +const _quaternion$2 = /*@__PURE__*/ new Quaternion(); +const _scale$2 = /*@__PURE__*/ new Vector3(); + +/** + * Abstract base class for cameras. This class should always be inherited + * when you build a new camera. + * + * @abstract + * @augments Object3D + */ +class Camera extends Object3D { + + /** + * Constructs a new camera. + */ + constructor() { + + super(); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isCamera = true; + + this.type = 'Camera'; + + /** + * The inverse of the camera's world matrix. + * + * @type {Matrix4} + */ + this.matrixWorldInverse = new Matrix4(); + + /** + * The camera's projection matrix. + * + * @type {Matrix4} + */ + this.projectionMatrix = new Matrix4(); + + /** + * The inverse of the camera's projection matrix. + * + * @type {Matrix4} + */ + this.projectionMatrixInverse = new Matrix4(); + + /** + * The coordinate system in which the camera is used. + * + * @type {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} + */ + this.coordinateSystem = WebGLCoordinateSystem; + + this._reversedDepth = false; + + } + + /** + * The flag that indicates whether the camera uses a reversed depth buffer. + * + * @type {boolean} + * @default false + */ + get reversedDepth() { + + return this._reversedDepth; + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + this.matrixWorldInverse.copy( source.matrixWorldInverse ); + + this.projectionMatrix.copy( source.projectionMatrix ); + this.projectionMatrixInverse.copy( source.projectionMatrixInverse ); + + this.coordinateSystem = source.coordinateSystem; + + return this; + + } + + /** + * Returns a vector representing the ("look") direction of the 3D object in world space. + * + * This method is overwritten since cameras have a different forward vector compared to other + * 3D objects. A camera looks down its local, negative z-axis by default. + * + * @param {Vector3} target - The target vector the result is stored to. + * @return {Vector3} The 3D object's direction in world space. + */ + getWorldDirection( target ) { + + return super.getWorldDirection( target ).negate(); + + } + + updateMatrixWorld( force ) { + + super.updateMatrixWorld( force ); + + // exclude scale from view matrix to be glTF conform + + this.matrixWorld.decompose( _position$2, _quaternion$2, _scale$2 ); + + if ( _scale$2.x === 1 && _scale$2.y === 1 && _scale$2.z === 1 ) { + + this.matrixWorldInverse.copy( this.matrixWorld ).invert(); + + } else { + + this.matrixWorldInverse.compose( _position$2, _quaternion$2, _scale$2.set( 1, 1, 1 ) ).invert(); + + } + + } + + updateWorldMatrix( updateParents, updateChildren, force = false ) { + + super.updateWorldMatrix( updateParents, updateChildren, force ); + + // exclude scale from view matrix to be glTF conform + + this.matrixWorld.decompose( _position$2, _quaternion$2, _scale$2 ); + + if ( _scale$2.x === 1 && _scale$2.y === 1 && _scale$2.z === 1 ) { + + this.matrixWorldInverse.copy( this.matrixWorld ).invert(); + + } else { + + this.matrixWorldInverse.compose( _position$2, _quaternion$2, _scale$2.set( 1, 1, 1 ) ).invert(); + + } + + } + + clone() { + + return new this.constructor().copy( this ); + + } + +} + +const _v3$1 = /*@__PURE__*/ new Vector3(); +const _minTarget = /*@__PURE__*/ new Vector2(); +const _maxTarget = /*@__PURE__*/ new Vector2(); + +/** + * Camera that uses [perspective projection](https://en.wikipedia.org/wiki/Perspective_(graphical)). + * + * This projection mode is designed to mimic the way the human eye sees. It + * is the most common projection mode used for rendering a 3D scene. + * + * ```js + * const camera = new THREE.PerspectiveCamera( 45, width / height, 1, 1000 ); + * scene.add( camera ); + * ``` + * + * @augments Camera + */ +class PerspectiveCamera extends Camera { + + /** + * Constructs a new perspective camera. + * + * @param {number} [fov=50] - The vertical field of view. + * @param {number} [aspect=1] - The aspect ratio. + * @param {number} [near=0.1] - The camera's near plane. + * @param {number} [far=2000] - The camera's far plane. + */ + constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) { + + super(); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isPerspectiveCamera = true; + + this.type = 'PerspectiveCamera'; + + /** + * The vertical field of view, from bottom to top of view, + * in degrees. + * + * @type {number} + * @default 50 + */ + this.fov = fov; + + /** + * The zoom factor of the camera. + * + * @type {number} + * @default 1 + */ + this.zoom = 1; + + /** + * The camera's near plane. The valid range is greater than `0` + * and less than the current value of {@link PerspectiveCamera#far}. + * + * Note that, unlike for the {@link OrthographicCamera}, `0` is not a + * valid value for a perspective camera's near plane. + * + * @type {number} + * @default 0.1 + */ + this.near = near; + + /** + * The camera's far plane. Must be greater than the + * current value of {@link PerspectiveCamera#near}. + * + * @type {number} + * @default 2000 + */ + this.far = far; + + /** + * Object distance used for stereoscopy and depth-of-field effects. This + * parameter does not influence the projection matrix unless a + * {@link StereoCamera} is being used. + * + * @type {number} + * @default 10 + */ + this.focus = 10; + + /** + * The aspect ratio, usually the canvas width / canvas height. + * + * @type {number} + * @default 1 + */ + this.aspect = aspect; + + /** + * Represents the frustum window specification. This property should not be edited + * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}. + * + * @type {?Object} + * @default null + */ + this.view = null; + + /** + * Film size used for the larger axis. Default is `35` (millimeters). This + * parameter does not influence the projection matrix unless {@link PerspectiveCamera#filmOffset} + * is set to a nonzero value. + * + * @type {number} + * @default 35 + */ + this.filmGauge = 35; + + /** + * Horizontal off-center offset in the same unit as {@link PerspectiveCamera#filmGauge}. + * + * @type {number} + * @default 0 + */ + this.filmOffset = 0; + + this.updateProjectionMatrix(); + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + this.fov = source.fov; + this.zoom = source.zoom; + + this.near = source.near; + this.far = source.far; + this.focus = source.focus; + + this.aspect = source.aspect; + this.view = source.view === null ? null : Object.assign( {}, source.view ); + + this.filmGauge = source.filmGauge; + this.filmOffset = source.filmOffset; + + return this; + + } + + /** + * Sets the FOV by focal length in respect to the current {@link PerspectiveCamera#filmGauge}. + * + * The default film gauge is 35, so that the focal length can be specified for + * a 35mm (full frame) camera. + * + * @param {number} focalLength - Values for focal length and film gauge must have the same unit. + */ + setFocalLength( focalLength ) { + + /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */ + const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength; + + this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope ); + this.updateProjectionMatrix(); + + } + + /** + * Returns the focal length from the current {@link PerspectiveCamera#fov} and + * {@link PerspectiveCamera#filmGauge}. + * + * @return {number} The computed focal length. + */ + getFocalLength() { + + const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov ); + + return 0.5 * this.getFilmHeight() / vExtentSlope; + + } + + /** + * Returns the current vertical field of view angle in degrees considering {@link PerspectiveCamera#zoom}. + * + * @return {number} The effective FOV. + */ + getEffectiveFOV() { + + return RAD2DEG * 2 * Math.atan( + Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom ); + + } + + /** + * Returns the width of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or + * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}. + * + * @return {number} The film width. + */ + getFilmWidth() { + + // film not completely covered in portrait format (aspect < 1) + return this.filmGauge * Math.min( this.aspect, 1 ); + + } + + /** + * Returns the height of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or + * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}. + * + * @return {number} The film width. + */ + getFilmHeight() { + + // film not completely covered in landscape format (aspect > 1) + return this.filmGauge / Math.max( this.aspect, 1 ); + + } + + /** + * Computes the 2D bounds of the camera's viewable rectangle at a given distance along the viewing direction. + * Sets `minTarget` and `maxTarget` to the coordinates of the lower-left and upper-right corners of the view rectangle. + * + * @param {number} distance - The viewing distance. + * @param {Vector2} minTarget - The lower-left corner of the view rectangle is written into this vector. + * @param {Vector2} maxTarget - The upper-right corner of the view rectangle is written into this vector. + */ + getViewBounds( distance, minTarget, maxTarget ) { + + _v3$1.set( -1, -1, 0.5 ).applyMatrix4( this.projectionMatrixInverse ); + + minTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z ); + + _v3$1.set( 1, 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse ); + + maxTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z ); + + } + + /** + * Computes the width and height of the camera's viewable rectangle at a given distance along the viewing direction. + * + * @param {number} distance - The viewing distance. + * @param {Vector2} target - The target vector that is used to store result where x is width and y is height. + * @returns {Vector2} The view size. + */ + getViewSize( distance, target ) { + + this.getViewBounds( distance, _minTarget, _maxTarget ); + + return target.subVectors( _maxTarget, _minTarget ); + + } + + /** + * Sets an offset in a larger frustum. This is useful for multi-window or + * multi-monitor/multi-machine setups. + * + * For example, if you have 3x2 monitors and each monitor is 1920x1080 and + * the monitors are in grid like this + *``` + * +---+---+---+ + * | A | B | C | + * +---+---+---+ + * | D | E | F | + * +---+---+---+ + *``` + * then for each monitor you would call it like this: + *```js + * const w = 1920; + * const h = 1080; + * const fullWidth = w * 3; + * const fullHeight = h * 2; + * + * // --A-- + * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h ); + * // --B-- + * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h ); + * // --C-- + * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h ); + * // --D-- + * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h ); + * // --E-- + * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h ); + * // --F-- + * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h ); + * ``` + * + * Note there is no reason monitors have to be the same size or in a grid. + * + * @param {number} fullWidth - The full width of multiview setup. + * @param {number} fullHeight - The full height of multiview setup. + * @param {number} x - The horizontal offset of the subcamera. + * @param {number} y - The vertical offset of the subcamera. + * @param {number} width - The width of subcamera. + * @param {number} height - The height of subcamera. + */ + setViewOffset( fullWidth, fullHeight, x, y, width, height ) { + + this.aspect = fullWidth / fullHeight; + + if ( this.view === null ) { + + this.view = { + enabled: true, + fullWidth: 1, + fullHeight: 1, + offsetX: 0, + offsetY: 0, + width: 1, + height: 1 + }; + + } + + this.view.enabled = true; + this.view.fullWidth = fullWidth; + this.view.fullHeight = fullHeight; + this.view.offsetX = x; + this.view.offsetY = y; + this.view.width = width; + this.view.height = height; + + this.updateProjectionMatrix(); + + } + + /** + * Removes the view offset from the projection matrix. + */ + clearViewOffset() { + + if ( this.view !== null ) { + + this.view.enabled = false; + + } + + this.updateProjectionMatrix(); + + } + + /** + * Updates the camera's projection matrix. Must be called after any change of + * camera properties. + */ + updateProjectionMatrix() { + + const near = this.near; + let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom; + let height = 2 * top; + let width = this.aspect * height; + let left = -0.5 * width; + const view = this.view; + + if ( this.view !== null && this.view.enabled ) { + + const fullWidth = view.fullWidth, + fullHeight = view.fullHeight; + + left += view.offsetX * width / fullWidth; + top -= view.offsetY * height / fullHeight; + width *= view.width / fullWidth; + height *= view.height / fullHeight; + + } + + const skew = this.filmOffset; + if ( skew !== 0 ) left += near * skew / this.getFilmWidth(); + + this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far, this.coordinateSystem, this.reversedDepth ); + + this.projectionMatrixInverse.copy( this.projectionMatrix ).invert(); + + } + + toJSON( meta ) { + + const data = super.toJSON( meta ); + + data.object.fov = this.fov; + data.object.zoom = this.zoom; + + data.object.near = this.near; + data.object.far = this.far; + data.object.focus = this.focus; + + data.object.aspect = this.aspect; + + if ( this.view !== null ) data.object.view = Object.assign( {}, this.view ); + + data.object.filmGauge = this.filmGauge; + data.object.filmOffset = this.filmOffset; + + return data; + + } + +} + +/** + * Represents the shadow configuration of directional lights. + * + * @augments LightShadow + */ +class SpotLightShadow extends LightShadow { + + /** + * Constructs a new spot light shadow. + */ + constructor() { + + super( new PerspectiveCamera( 50, 1, 0.5, 500 ) ); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isSpotLightShadow = true; + + /** + * Used to focus the shadow camera. The camera's field of view is set as a + * percentage of the spotlight's field-of-view. Range is `[0, 1]`. + * + * @type {number} + * @default 1 + */ + this.focus = 1; + + /** + * Texture aspect ratio. + * + * @type {number} + * @default 1 + */ + this.aspect = 1; + + } + + updateMatrices( light ) { + + const camera = this.camera; + + const fov = RAD2DEG * 2 * light.angle * this.focus; + const aspect = ( this.mapSize.width / this.mapSize.height ) * this.aspect; + const far = light.distance || camera.far; + + if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) { + + camera.fov = fov; + camera.aspect = aspect; + camera.far = far; + camera.updateProjectionMatrix(); + + } + + super.updateMatrices( light ); + + } + + copy( source ) { + + super.copy( source ); + + this.focus = source.focus; + this.aspect = source.aspect; + + return this; + + } + + /** + * Serializes the light shadow into JSON. + * + * @return {Object} A JSON object representing the serialized light shadow. + * @see {@link ObjectLoader#parse} + */ + toJSON() { + + const object = super.toJSON(); + + object.focus = this.focus; + object.aspect = this.aspect; + + return object; + + } + +} + +/** + * This light gets emitted from a single point in one direction, along a cone + * that increases in size the further from the light it gets. + * + * This light can cast shadows - see the {@link SpotLightShadow} for details. + * + * ```js + * // white spotlight shining from the side, modulated by a texture + * const spotLight = new THREE.SpotLight( 0xffffff ); + * spotLight.position.set( 100, 1000, 100 ); + * spotLight.map = new THREE.TextureLoader().load( url ); + * + * spotLight.castShadow = true; + * spotLight.shadow.mapSize.width = 1024; + * spotLight.shadow.mapSize.height = 1024; + * spotLight.shadow.camera.near = 500; + * spotLight.shadow.camera.far = 4000; + * spotLight.shadow.camera.fov = 30;s + * ``` + * + * @augments Light + */ +class SpotLight extends Light { + + /** + * Constructs a new spot light. + * + * @param {(number|Color|string)} [color=0xffffff] - The light's color. + * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd). + * @param {number} [distance=0] - Maximum range of the light. `0` means no limit. + * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`. + * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`. + * @param {number} [decay=2] - The amount the light dims along the distance of the light. + */ + constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) { + + super( color, intensity ); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isSpotLight = true; + + this.type = 'SpotLight'; + + this.position.copy( Object3D.DEFAULT_UP ); + this.updateMatrix(); + + /** + * The spot light points from its position to the + * target's position. + * + * For the target's position to be changed to anything other + * than the default, it must be added to the scene. + * + * It is also possible to set the target to be another 3D object + * in the scene. The light will now track the target object. + * + * @type {Object3D} + */ + this.target = new Object3D(); + + /** + * Maximum range of the light. `0` means no limit. + * + * @type {number} + * @default 0 + */ + this.distance = distance; + + /** + * Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`. + * + * @type {number} + * @default Math.PI/3 + */ + this.angle = angle; + + /** + * Percent of the spotlight cone that is attenuated due to penumbra. + * Value range is `[0,1]`. + * + * @type {number} + * @default 0 + */ + this.penumbra = penumbra; + + /** + * The amount the light dims along the distance of the light. In context of + * physically-correct rendering the default value should not be changed. + * + * @type {number} + * @default 2 + */ + this.decay = decay; + + /** + * A texture used to modulate the color of the light. The spot light + * color is mixed with the RGB value of this texture, with a ratio + * corresponding to its alpha value. The cookie-like masking effect is + * reproduced using pixel values (0, 0, 0, 1-cookie_value). + * + * *Warning*: This property is disabled if {@link Object3D#castShadow} is set to `false`. + * + * @type {?Texture} + * @default null + */ + this.map = null; + + /** + * This property holds the light's shadow configuration. + * + * @type {SpotLightShadow} + */ + this.shadow = new SpotLightShadow(); + + } + + /** + * The light's power. Power is the luminous power of the light measured in lumens (lm). + * Changing the power will also change the light's intensity. + * + * @type {number} + */ + get power() { + + // compute the light's luminous power (in lumens) from its intensity (in candela) + // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd) + return this.intensity * Math.PI; + + } + + set power( power ) { + + // set the light's intensity (in candela) from the desired luminous power (in lumens) + this.intensity = power / Math.PI; + + } + + dispose() { + + super.dispose(); + + this.shadow.dispose(); + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + this.distance = source.distance; + this.angle = source.angle; + this.penumbra = source.penumbra; + this.decay = source.decay; + + this.target = source.target.clone(); + this.map = source.map; + this.shadow = source.shadow.clone(); + + return this; + + } + + toJSON( meta ) { + + const data = super.toJSON( meta ); + + data.object.distance = this.distance; + data.object.angle = this.angle; + data.object.decay = this.decay; + data.object.penumbra = this.penumbra; + + data.object.target = this.target.uuid; + + if ( this.map && this.map.isTexture ) data.object.map = this.map.toJSON( meta ).uuid; + + data.object.shadow = this.shadow.toJSON(); + + return data; + + } + +} + +/** + * Represents the shadow configuration of point lights. + * + * @augments LightShadow + */ +class PointLightShadow extends LightShadow { + + /** + * Constructs a new point light shadow. + */ + constructor() { + + super( new PerspectiveCamera( 90, 1, 0.5, 500 ) ); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isPointLightShadow = true; + + } + +} + +/** + * A light that gets emitted from a single point in all directions. A common + * use case for this is to replicate the light emitted from a bare + * lightbulb. + * + * This light can cast shadows - see the {@link PointLightShadow} for details. + * + * ```js + * const light = new THREE.PointLight( 0xff0000, 1, 100 ); + * light.position.set( 50, 50, 50 ); + * scene.add( light ); + * ``` + * + * @augments Light + */ +class PointLight extends Light { + + /** + * Constructs a new point light. + * + * @param {(number|Color|string)} [color=0xffffff] - The light's color. + * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd). + * @param {number} [distance=0] - Maximum range of the light. `0` means no limit. + * @param {number} [decay=2] - The amount the light dims along the distance of the light. + */ + constructor( color, intensity, distance = 0, decay = 2 ) { + + super( color, intensity ); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isPointLight = true; + + this.type = 'PointLight'; + + /** + * When distance is zero, light will attenuate according to inverse-square + * law to infinite distance. When distance is non-zero, light will attenuate + * according to inverse-square law until near the distance cutoff, where it + * will then attenuate quickly and smoothly to 0. Inherently, cutoffs are not + * physically correct. + * + * @type {number} + * @default 0 + */ + this.distance = distance; + + /** + * The amount the light dims along the distance of the light. In context of + * physically-correct rendering the default value should not be changed. + * + * @type {number} + * @default 2 + */ + this.decay = decay; + + /** + * This property holds the light's shadow configuration. + * + * @type {PointLightShadow} + */ + this.shadow = new PointLightShadow(); + + } + + /** + * The light's power. Power is the luminous power of the light measured in lumens (lm). + * Changing the power will also change the light's intensity. + * + * @type {number} + */ + get power() { + + // compute the light's luminous power (in lumens) from its intensity (in candela) + // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd) + return this.intensity * 4 * Math.PI; + + } + + set power( power ) { + + // set the light's intensity (in candela) from the desired luminous power (in lumens) + this.intensity = power / ( 4 * Math.PI ); + + } + + dispose() { + + super.dispose(); + + this.shadow.dispose(); + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + this.distance = source.distance; + this.decay = source.decay; + + this.shadow = source.shadow.clone(); + + return this; + + } + + toJSON( meta ) { + + const data = super.toJSON( meta ); + + data.object.distance = this.distance; + data.object.decay = this.decay; + + data.object.shadow = this.shadow.toJSON(); + + return data; + + } + +} + +/** + * Camera that uses [orthographic projection](https://en.wikipedia.org/wiki/Orthographic_projection). + * + * In this projection mode, an object's size in the rendered image stays + * constant regardless of its distance from the camera. This can be useful + * for rendering 2D scenes and UI elements, amongst other things. + * + * ```js + * const camera = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, 1, 1000 ); + * scene.add( camera ); + * ``` + * + * @augments Camera + */ +class OrthographicCamera extends Camera { + + /** + * Constructs a new orthographic camera. + * + * @param {number} [left=-1] - The left plane of the camera's frustum. + * @param {number} [right=1] - The right plane of the camera's frustum. + * @param {number} [top=1] - The top plane of the camera's frustum. + * @param {number} [bottom=-1] - The bottom plane of the camera's frustum. + * @param {number} [near=0.1] - The camera's near plane. + * @param {number} [far=2000] - The camera's far plane. + */ + constructor( left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2000 ) { + + super(); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isOrthographicCamera = true; + + this.type = 'OrthographicCamera'; + + /** + * The zoom factor of the camera. + * + * @type {number} + * @default 1 + */ + this.zoom = 1; + + /** + * Represents the frustum window specification. This property should not be edited + * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}. + * + * @type {?Object} + * @default null + */ + this.view = null; + + /** + * The left plane of the camera's frustum. + * + * @type {number} + * @default -1 + */ + this.left = left; + + /** + * The right plane of the camera's frustum. + * + * @type {number} + * @default 1 + */ + this.right = right; + + /** + * The top plane of the camera's frustum. + * + * @type {number} + * @default 1 + */ + this.top = top; + + /** + * The bottom plane of the camera's frustum. + * + * @type {number} + * @default -1 + */ + this.bottom = bottom; + + /** + * The camera's near plane. The valid range is greater than `0` + * and less than the current value of {@link OrthographicCamera#far}. + * + * Note that, unlike for the {@link PerspectiveCamera}, `0` is a + * valid value for an orthographic camera's near plane. + * + * @type {number} + * @default 0.1 + */ + this.near = near; + + /** + * The camera's far plane. Must be greater than the + * current value of {@link OrthographicCamera#near}. + * + * @type {number} + * @default 2000 + */ + this.far = far; + + this.updateProjectionMatrix(); + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + this.left = source.left; + this.right = source.right; + this.top = source.top; + this.bottom = source.bottom; + this.near = source.near; + this.far = source.far; + + this.zoom = source.zoom; + this.view = source.view === null ? null : Object.assign( {}, source.view ); + + return this; + + } + + /** + * Sets an offset in a larger frustum. This is useful for multi-window or + * multi-monitor/multi-machine setups. + * + * @param {number} fullWidth - The full width of multiview setup. + * @param {number} fullHeight - The full height of multiview setup. + * @param {number} x - The horizontal offset of the subcamera. + * @param {number} y - The vertical offset of the subcamera. + * @param {number} width - The width of subcamera. + * @param {number} height - The height of subcamera. + * @see {@link PerspectiveCamera#setViewOffset} + */ + setViewOffset( fullWidth, fullHeight, x, y, width, height ) { + + if ( this.view === null ) { + + this.view = { + enabled: true, + fullWidth: 1, + fullHeight: 1, + offsetX: 0, + offsetY: 0, + width: 1, + height: 1 + }; + + } + + this.view.enabled = true; + this.view.fullWidth = fullWidth; + this.view.fullHeight = fullHeight; + this.view.offsetX = x; + this.view.offsetY = y; + this.view.width = width; + this.view.height = height; + + this.updateProjectionMatrix(); + + } + + /** + * Removes the view offset from the projection matrix. + */ + clearViewOffset() { + + if ( this.view !== null ) { + + this.view.enabled = false; + + } + + this.updateProjectionMatrix(); + + } + + /** + * Updates the camera's projection matrix. Must be called after any change of + * camera properties. + */ + updateProjectionMatrix() { + + const dx = ( this.right - this.left ) / ( 2 * this.zoom ); + const dy = ( this.top - this.bottom ) / ( 2 * this.zoom ); + const cx = ( this.right + this.left ) / 2; + const cy = ( this.top + this.bottom ) / 2; + + let left = cx - dx; + let right = cx + dx; + let top = cy + dy; + let bottom = cy - dy; + + if ( this.view !== null && this.view.enabled ) { + + const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom; + const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom; + + left += scaleW * this.view.offsetX; + right = left + scaleW * this.view.width; + top -= scaleH * this.view.offsetY; + bottom = top - scaleH * this.view.height; + + } + + this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far, this.coordinateSystem, this.reversedDepth ); + + this.projectionMatrixInverse.copy( this.projectionMatrix ).invert(); + + } + + toJSON( meta ) { + + const data = super.toJSON( meta ); + + data.object.zoom = this.zoom; + data.object.left = this.left; + data.object.right = this.right; + data.object.top = this.top; + data.object.bottom = this.bottom; + data.object.near = this.near; + data.object.far = this.far; + + if ( this.view !== null ) data.object.view = Object.assign( {}, this.view ); + + return data; + + } + +} + +/** + * Represents the shadow configuration of directional lights. + * + * @augments LightShadow + */ +class DirectionalLightShadow extends LightShadow { + + /** + * Constructs a new directional light shadow. + */ + constructor() { + + super( new OrthographicCamera( -5, 5, 5, -5, 0.5, 500 ) ); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isDirectionalLightShadow = true; + + } + +} + +/** + * A light that gets emitted in a specific direction. This light will behave + * as though it is infinitely far away and the rays produced from it are all + * parallel. The common use case for this is to simulate daylight; the sun is + * far enough away that its position can be considered to be infinite, and + * all light rays coming from it are parallel. + * + * A common point of confusion for directional lights is that setting the + * rotation has no effect. This is because three.js's DirectionalLight is the + * equivalent to what is often called a 'Target Direct Light' in other + * applications. + * + * This means that its direction is calculated as pointing from the light's + * {@link Object3D#position} to the {@link DirectionalLight#target} position + * (as opposed to a 'Free Direct Light' that just has a rotation + * component). + * + * This light can cast shadows - see the {@link DirectionalLightShadow} for details. + * + * ```js + * // White directional light at half intensity shining from the top. + * const directionalLight = new THREE.DirectionalLight( 0xffffff, 0.5 ); + * scene.add( directionalLight ); + * ``` + * + * @augments Light + */ +class DirectionalLight extends Light { + + /** + * Constructs a new directional light. + * + * @param {(number|Color|string)} [color=0xffffff] - The light's color. + * @param {number} [intensity=1] - The light's strength/intensity. + */ + constructor( color, intensity ) { + + super( color, intensity ); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isDirectionalLight = true; + + this.type = 'DirectionalLight'; + + this.position.copy( Object3D.DEFAULT_UP ); + this.updateMatrix(); + + /** + * The directional light points from its position to the + * target's position. + * + * For the target's position to be changed to anything other + * than the default, it must be added to the scene. + * + * It is also possible to set the target to be another 3D object + * in the scene. The light will now track the target object. + * + * @type {Object3D} + */ + this.target = new Object3D(); + + /** + * This property holds the light's shadow configuration. + * + * @type {DirectionalLightShadow} + */ + this.shadow = new DirectionalLightShadow(); + + } + + dispose() { + + super.dispose(); + + this.shadow.dispose(); + + } + + copy( source ) { + + super.copy( source ); + + this.target = source.target.clone(); + this.shadow = source.shadow.clone(); + + return this; + + } + + toJSON( meta ) { + + const data = super.toJSON( meta ); + + data.object.shadow = this.shadow.toJSON(); + data.object.target = this.target.uuid; + + return data; + + } + +} + +/** + * This light globally illuminates all objects in the scene equally. + * + * It cannot be used to cast shadows as it does not have a direction. + * + * ```js + * const light = new THREE.AmbientLight( 0x404040 ); // soft white light + * scene.add( light ); + * ``` + * + * @augments Light + */ +class AmbientLight extends Light { + + /** + * Constructs a new ambient light. + * + * @param {(number|Color|string)} [color=0xffffff] - The light's color. + * @param {number} [intensity=1] - The light's strength/intensity. + */ + constructor( color, intensity ) { + + super( color, intensity ); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isAmbientLight = true; + + this.type = 'AmbientLight'; + + } + +} + +/** + * This class emits light uniformly across the face a rectangular plane. + * This light type can be used to simulate light sources such as bright + * windows or strip lighting. + * + * Important Notes: + * + * - There is no shadow support. + * - Only PBR materials are supported. + * - You have to include `RectAreaLightUniformsLib` (`WebGLRenderer`) or `RectAreaLightTexturesLib` (`WebGPURenderer`) + * into your app and init the uniforms/textures. + * + * ```js + * RectAreaLightUniformsLib.init(); // only relevant for WebGLRenderer + * THREE.RectAreaLightNode.setLTC( RectAreaLightTexturesLib.init() ); // only relevant for WebGPURenderer + * + * const intensity = 1; const width = 10; const height = 10; + * const rectLight = new THREE.RectAreaLight( 0xffffff, intensity, width, height ); + * rectLight.position.set( 5, 5, 0 ); + * rectLight.lookAt( 0, 0, 0 ); + * scene.add( rectLight ) + * ``` + * + * @augments Light + */ +class RectAreaLight extends Light { + + /** + * Constructs a new area light. + * + * @param {(number|Color|string)} [color=0xffffff] - The light's color. + * @param {number} [intensity=1] - The light's strength/intensity. + * @param {number} [width=10] - The width of the light. + * @param {number} [height=10] - The height of the light. + */ + constructor( color, intensity, width = 10, height = 10 ) { + + super( color, intensity ); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isRectAreaLight = true; + + this.type = 'RectAreaLight'; + + /** + * The width of the light. + * + * @type {number} + * @default 10 + */ + this.width = width; + + /** + * The height of the light. + * + * @type {number} + * @default 10 + */ + this.height = height; + + } + + /** + * The light's power. Power is the luminous power of the light measured in lumens (lm). + * Changing the power will also change the light's intensity. + * + * @type {number} + */ + get power() { + + // compute the light's luminous power (in lumens) from its intensity (in nits) + return this.intensity * this.width * this.height * Math.PI; + + } + + set power( power ) { + + // set the light's intensity (in nits) from the desired luminous power (in lumens) + this.intensity = power / ( this.width * this.height * Math.PI ); + + } + + copy( source ) { + + super.copy( source ); + + this.width = source.width; + this.height = source.height; + + return this; + + } + + toJSON( meta ) { + + const data = super.toJSON( meta ); + + data.object.width = this.width; + data.object.height = this.height; + + return data; + + } + +} + +/** + * Represents a third-order spherical harmonics (SH). Light probes use this class + * to encode lighting information. + * + * - Primary reference: {@link https://graphics.stanford.edu/papers/envmap/envmap.pdf} + * - Secondary reference: {@link https://www.ppsloan.org/publications/StupidSH36.pdf} + */ +class SphericalHarmonics3 { + + /** + * Constructs a new spherical harmonics. + */ + constructor() { + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isSphericalHarmonics3 = true; + + /** + * An array holding the (9) SH coefficients. + * + * @type {Array} + */ + this.coefficients = []; + + for ( let i = 0; i < 9; i ++ ) { + + this.coefficients.push( new Vector3() ); + + } + + } + + /** + * Sets the given SH coefficients to this instance by copying + * the values. + * + * @param {Array} coefficients - The SH coefficients. + * @return {SphericalHarmonics3} A reference to this spherical harmonics. + */ + set( coefficients ) { + + for ( let i = 0; i < 9; i ++ ) { + + this.coefficients[ i ].copy( coefficients[ i ] ); + + } + + return this; + + } + + /** + * Sets all SH coefficients to `0`. + * + * @return {SphericalHarmonics3} A reference to this spherical harmonics. + */ + zero() { + + for ( let i = 0; i < 9; i ++ ) { + + this.coefficients[ i ].set( 0, 0, 0 ); + + } + + return this; + + } + + /** + * Returns the radiance in the direction of the given normal. + * + * @param {Vector3} normal - The normal vector (assumed to be unit length) + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {Vector3} The radiance. + */ + getAt( normal, target ) { + + // normal is assumed to be unit length + + const x = normal.x, y = normal.y, z = normal.z; + + const coeff = this.coefficients; + + // band 0 + target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 ); + + // band 1 + target.addScaledVector( coeff[ 1 ], 0.488603 * y ); + target.addScaledVector( coeff[ 2 ], 0.488603 * z ); + target.addScaledVector( coeff[ 3 ], 0.488603 * x ); + + // band 2 + target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) ); + target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) ); + target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) ); + target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) ); + target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) ); + + return target; + + } + + /** + * Returns the irradiance (radiance convolved with cosine lobe) in the + * direction of the given normal. + * + * @param {Vector3} normal - The normal vector (assumed to be unit length) + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {Vector3} The irradiance. + */ + getIrradianceAt( normal, target ) { + + // normal is assumed to be unit length + + const x = normal.x, y = normal.y, z = normal.z; + + const coeff = this.coefficients; + + // band 0 + target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095 + + // band 1 + target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603 + target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z ); + target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x ); + + // band 2 + target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548 + target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z ); + target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3 + target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z ); + target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274 + + return target; + + } + + /** + * Adds the given SH to this instance. + * + * @param {SphericalHarmonics3} sh - The SH to add. + * @return {SphericalHarmonics3} A reference to this spherical harmonics. + */ + add( sh ) { + + for ( let i = 0; i < 9; i ++ ) { + + this.coefficients[ i ].add( sh.coefficients[ i ] ); + + } + + return this; + + } + + /** + * A convenience method for performing {@link SphericalHarmonics3#add} and + * {@link SphericalHarmonics3#scale} at once. + * + * @param {SphericalHarmonics3} sh - The SH to add. + * @param {number} s - The scale factor. + * @return {SphericalHarmonics3} A reference to this spherical harmonics. + */ + addScaledSH( sh, s ) { + + for ( let i = 0; i < 9; i ++ ) { + + this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s ); + + } + + return this; + + } + + /** + * Scales this SH by the given scale factor. + * + * @param {number} s - The scale factor. + * @return {SphericalHarmonics3} A reference to this spherical harmonics. + */ + scale( s ) { + + for ( let i = 0; i < 9; i ++ ) { + + this.coefficients[ i ].multiplyScalar( s ); + + } + + return this; + + } + + /** + * Linear interpolates between the given SH and this instance by the given + * alpha factor. + * + * @param {SphericalHarmonics3} sh - The SH to interpolate with. + * @param {number} alpha - The alpha factor. + * @return {SphericalHarmonics3} A reference to this spherical harmonics. + */ + lerp( sh, alpha ) { + + for ( let i = 0; i < 9; i ++ ) { + + this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha ); + + } + + return this; + + } + + /** + * Returns `true` if this spherical harmonics is equal with the given one. + * + * @param {SphericalHarmonics3} sh - The spherical harmonics to test for equality. + * @return {boolean} Whether this spherical harmonics is equal with the given one. + */ + equals( sh ) { + + for ( let i = 0; i < 9; i ++ ) { + + if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) { + + return false; + + } + + } + + return true; + + } + + /** + * Copies the values of the given spherical harmonics to this instance. + * + * @param {SphericalHarmonics3} sh - The spherical harmonics to copy. + * @return {SphericalHarmonics3} A reference to this spherical harmonics. + */ + copy( sh ) { + + return this.set( sh.coefficients ); + + } + + /** + * Returns a new spherical harmonics with copied values from this instance. + * + * @return {SphericalHarmonics3} A clone of this instance. + */ + clone() { + + return new this.constructor().copy( this ); + + } + + /** + * Sets the SH coefficients of this instance from the given array. + * + * @param {Array} array - An array holding the SH coefficients. + * @param {number} [offset=0] - The array offset where to start copying. + * @return {SphericalHarmonics3} A clone of this instance. + */ + fromArray( array, offset = 0 ) { + + const coefficients = this.coefficients; + + for ( let i = 0; i < 9; i ++ ) { + + coefficients[ i ].fromArray( array, offset + ( i * 3 ) ); + + } + + return this; + + } + + /** + * Returns an array with the SH coefficients, or copies them into the provided + * array. The coefficients are represented as numbers. + * + * @param {Array} [array=[]] - The target array. + * @param {number} [offset=0] - The array offset where to start copying. + * @return {Array} An array with flat SH coefficients. + */ + toArray( array = [], offset = 0 ) { + + const coefficients = this.coefficients; + + for ( let i = 0; i < 9; i ++ ) { + + coefficients[ i ].toArray( array, offset + ( i * 3 ) ); + + } + + return array; + + } + + /** + * Computes the SH basis for the given normal vector. + * + * @param {Vector3} normal - The normal. + * @param {Array} shBasis - The target array holding the SH basis. + */ + static getBasisAt( normal, shBasis ) { + + // normal is assumed to be unit length + + const x = normal.x, y = normal.y, z = normal.z; + + // band 0 + shBasis[ 0 ] = 0.282095; + + // band 1 + shBasis[ 1 ] = 0.488603 * y; + shBasis[ 2 ] = 0.488603 * z; + shBasis[ 3 ] = 0.488603 * x; + + // band 2 + shBasis[ 4 ] = 1.092548 * x * y; + shBasis[ 5 ] = 1.092548 * y * z; + shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 ); + shBasis[ 7 ] = 1.092548 * x * z; + shBasis[ 8 ] = 0.546274 * ( x * x - y * y ); + + } + +} + +/** + * Light probes are an alternative way of adding light to a 3D scene. Unlike + * classical light sources (e.g. directional, point or spot lights), light + * probes do not emit light. Instead they store information about light + * passing through 3D space. During rendering, the light that hits a 3D + * object is approximated by using the data from the light probe. + * + * Light probes are usually created from (radiance) environment maps. The + * class {@link LightProbeGenerator} can be used to create light probes from + * cube textures or render targets. However, light estimation data could also + * be provided in other forms e.g. by WebXR. This enables the rendering of + * augmented reality content that reacts to real world lighting. + * + * The current probe implementation in three.js supports so-called diffuse + * light probes. This type of light probe is functionally equivalent to an + * irradiance environment map. + * + * @augments Light + */ +class LightProbe extends Light { + + /** + * Constructs a new light probe. + * + * @param {SphericalHarmonics3} sh - The spherical harmonics which represents encoded lighting information. + * @param {number} [intensity=1] - The light's strength/intensity. + */ + constructor( sh = new SphericalHarmonics3(), intensity = 1 ) { + + super( undefined, intensity ); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isLightProbe = true; + + /** + * A light probe uses spherical harmonics to encode lighting information. + * + * @type {SphericalHarmonics3} + */ + this.sh = sh; + + } + + copy( source ) { + + super.copy( source ); + + this.sh.copy( source.sh ); + + return this; + + } + + toJSON( meta ) { + + const data = super.toJSON( meta ); + + data.object.sh = this.sh.toArray(); + + return data; + + } + +} + +const _customMaterials = {}; + +/** + * Class for loading materials. The files are internally + * loaded via {@link FileLoader}. + * + * ```js + * const loader = new THREE.MaterialLoader(); + * const material = await loader.loadAsync( 'material.json' ); + * ``` + * This loader does not support node materials. Use {@link NodeMaterialLoader} instead. + * + * @augments Loader + */ +class MaterialLoader extends Loader { + + /** + * Constructs a new material loader. + * + * @param {LoadingManager} [manager] - The loading manager. + */ + constructor( manager ) { + + super( manager ); + + /** + * A dictionary holding textures used by the material. + * + * @type {Object} + */ + this.textures = {}; + + } + + /** + * Starts loading from the given URL and pass the loaded material to the `onLoad()` callback. + * + * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI. + * @param {function(Material)} onLoad - Executed when the loading process has been finished. + * @param {onProgressCallback} onProgress - Executed while the loading is in progress. + * @param {onErrorCallback} onError - Executed when errors occur. + */ + load( url, onLoad, onProgress, onError ) { + + const scope = this; + + const loader = new FileLoader( scope.manager ); + loader.setPath( scope.path ); + loader.setRequestHeader( scope.requestHeader ); + loader.setWithCredentials( scope.withCredentials ); + loader.load( url, function ( text ) { + + try { + + onLoad( scope.parse( JSON.parse( text ) ) ); + + } catch ( e ) { + + if ( onError ) { + + onError( e ); + + } else { + + error( e ); + + } + + scope.manager.itemError( url ); + + } + + }, onProgress, onError ); + + } + + /** + * Parses the given JSON object and returns a material. + * + * @param {Object} json - The serialized material. + * @return {Material} The parsed material. + */ + parse( json ) { + + const material = this.createMaterialFromType( json.type ); + + material.fromJSON( json, this.textures ); + + return material; + + } + + /** + * Textures are not embedded in the material JSON so they have + * to be injected before the loading process starts. + * + * @param {Object} value - A dictionary holding textures for material properties. + * @return {MaterialLoader} A reference to this material loader. + */ + setTextures( value ) { + + this.textures = value; + return this; + + } + + /** + * Creates a material for the given type. + * + * @param {string} type - The material type. + * @return {Material} The new material. + */ + createMaterialFromType( type ) { + + return MaterialLoader.createMaterialFromType( type ); + + } + + /** + * Creates a material for the given type. + * + * @static + * @param {string} type - The material type. + * @return {Material} The new material. + */ + static createMaterialFromType( type ) { + + const materialLib = { + ShadowMaterial, + SpriteMaterial, + RawShaderMaterial, + ShaderMaterial, + PointsMaterial, + MeshPhysicalMaterial, + MeshStandardMaterial, + MeshPhongMaterial, + MeshToonMaterial, + MeshNormalMaterial, + MeshLambertMaterial, + MeshDepthMaterial, + MeshDistanceMaterial, + MeshBasicMaterial, + MeshMatcapMaterial, + LineDashedMaterial, + LineBasicMaterial, + Material, + ... _customMaterials + }; + + const MaterialType = materialLib[ type ]; + + let materialInstance; + + if ( MaterialType === undefined ) { + + warnOnce( `MaterialLoader: Unknown material type "${ type }". Use .registerMaterial() before starting the deserialization process.` ); + materialInstance = new Material(); + + } else { + + materialInstance = new MaterialType(); + + } + + return materialInstance; + + } + + /** + * Registers the given material at the internal + * material library. + * + * @static + * @param {string} type - The material type. + * @param {Material.constructor} materialClass - The material class. + */ + static registerMaterial( type, materialClass ) { + + _customMaterials[ type ] = materialClass; + + } + +} + +/** + * A class with loader utility functions. + */ +class LoaderUtils { + + /** + * Extracts the base URL from the given URL. + * + * @param {string} url -The URL to extract the base URL from. + * @return {string} The extracted base URL. + */ + static extractUrlBase( url ) { + + const index = url.lastIndexOf( '/' ); + + if ( index === -1 ) return './'; + + return url.slice( 0, index + 1 ); + + } + + /** + * Resolves relative URLs against the given path. Absolute paths, data urls, + * and blob URLs will be returned as is. Invalid URLs will return an empty + * string. + * + * @param {string} url -The URL to resolve. + * @param {string} path - The base path for relative URLs to be resolved against. + * @return {string} The resolved URL. + */ + static resolveURL( url, path ) { + + // Invalid URL + if ( typeof url !== 'string' || url === '' ) return ''; + + // Host Relative URL + if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) { + + path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' ); + + } + + // Absolute URL http://,https://,// + if ( /^(https?:)?\/\//i.test( url ) ) return url; + + // Data URI + if ( /^data:.*,.*$/i.test( url ) ) return url; + + // Blob URL + if ( /^blob:.*$/i.test( url ) ) return url; + + // Relative URL + return path + url; + + } + +} + +/** + * An instanced version of a geometry. + */ +class InstancedBufferGeometry extends BufferGeometry { + + /** + * Constructs a new instanced buffer geometry. + */ + constructor() { + + super(); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isInstancedBufferGeometry = true; + + this.type = 'InstancedBufferGeometry'; + + /** + * The instance count. + * + * @type {number} + * @default Infinity + */ + this.instanceCount = Infinity; + + } + + copy( source ) { + + super.copy( source ); + + this.instanceCount = source.instanceCount; + + return this; + + } + + toJSON() { + + const data = super.toJSON(); + + data.instanceCount = this.instanceCount; + + data.isInstancedBufferGeometry = true; + + return data; + + } + +} + +/** + * Class for loading geometries. The files are internally + * loaded via {@link FileLoader}. + * + * ```js + * const loader = new THREE.BufferGeometryLoader(); + * const geometry = await loader.loadAsync( 'models/json/pressure.json' ); + * + * const material = new THREE.MeshBasicMaterial( { color: 0xF5F5F5 } ); + * const object = new THREE.Mesh( geometry, material ); + * scene.add( object ); + * ``` + * + * @augments Loader + */ +class BufferGeometryLoader extends Loader { + + /** + * Constructs a new geometry loader. + * + * @param {LoadingManager} [manager] - The loading manager. + */ + constructor( manager ) { + + super( manager ); + + } + + /** + * Starts loading from the given URL and pass the loaded geometry to the `onLoad()` callback. + * + * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI. + * @param {function(BufferGeometry)} onLoad - Executed when the loading process has been finished. + * @param {onProgressCallback} onProgress - Executed while the loading is in progress. + * @param {onErrorCallback} onError - Executed when errors occur. + */ + load( url, onLoad, onProgress, onError ) { + + const scope = this; + + const loader = new FileLoader( scope.manager ); + loader.setPath( scope.path ); + loader.setRequestHeader( scope.requestHeader ); + loader.setWithCredentials( scope.withCredentials ); + loader.load( url, function ( text ) { + + try { + + onLoad( scope.parse( JSON.parse( text ) ) ); + + } catch ( e ) { + + if ( onError ) { + + onError( e ); + + } else { + + error( e ); + + } + + scope.manager.itemError( url ); + + } + + }, onProgress, onError ); + + } + + /** + * Parses the given JSON object and returns a geometry. + * + * @param {Object} json - The serialized geometry. + * @return {BufferGeometry} The parsed geometry. + */ + parse( json ) { + + const interleavedBufferMap = {}; + const arrayBufferMap = {}; + + function getInterleavedBuffer( json, uuid ) { + + if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ]; + + const interleavedBuffers = json.interleavedBuffers; + const interleavedBuffer = interleavedBuffers[ uuid ]; + + const buffer = getArrayBuffer( json, interleavedBuffer.buffer ); + + const array = getTypedArray( interleavedBuffer.type, buffer ); + const ib = new InterleavedBuffer( array, interleavedBuffer.stride ); + ib.uuid = interleavedBuffer.uuid; + + if ( interleavedBuffer.usage !== undefined ) ib.setUsage( interleavedBuffer.usage ); + + interleavedBufferMap[ uuid ] = ib; + + return ib; + + } + + function getArrayBuffer( json, uuid ) { + + if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ]; + + const arrayBuffers = json.arrayBuffers; + const arrayBuffer = arrayBuffers[ uuid ]; + + const ab = new Uint32Array( arrayBuffer ).buffer; + + arrayBufferMap[ uuid ] = ab; + + return ab; + + } + + const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry(); + + const index = json.data.index; + + if ( index !== undefined ) { + + const typedArray = getTypedArray( index.type, index.array ); + geometry.setIndex( new BufferAttribute( typedArray, 1 ) ); + + } + + const attributes = json.data.attributes; + + for ( const key in attributes ) { + + const attribute = attributes[ key ]; + let bufferAttribute; + + if ( attribute.isInterleavedBufferAttribute ) { + + const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data ); + bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized ); + + } else { + + const typedArray = getTypedArray( attribute.type, attribute.array ); + const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute; + bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized ); + + } + + if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name; + if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage ); + if ( attribute.gpuType !== undefined ) bufferAttribute.gpuType = attribute.gpuType; + + geometry.setAttribute( key, bufferAttribute ); + + } + + const morphAttributes = json.data.morphAttributes; + + if ( morphAttributes ) { + + for ( const key in morphAttributes ) { + + const attributeArray = morphAttributes[ key ]; + + const array = []; + + for ( let i = 0, il = attributeArray.length; i < il; i ++ ) { + + const attribute = attributeArray[ i ]; + let bufferAttribute; + + if ( attribute.isInterleavedBufferAttribute ) { + + const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data ); + bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized ); + + } else { + + const typedArray = getTypedArray( attribute.type, attribute.array ); + bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized ); + + } + + if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name; + if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage ); + if ( attribute.gpuType !== undefined ) bufferAttribute.gpuType = attribute.gpuType; + array.push( bufferAttribute ); + + } + + geometry.morphAttributes[ key ] = array; + + } + + } + + const morphTargetsRelative = json.data.morphTargetsRelative; + + if ( morphTargetsRelative ) { + + geometry.morphTargetsRelative = true; + + } + + const groups = json.data.groups || json.data.drawcalls || json.data.offsets; + + if ( groups !== undefined ) { + + for ( let i = 0, n = groups.length; i !== n; ++ i ) { + + const group = groups[ i ]; + + geometry.addGroup( group.start, group.count, group.materialIndex ); + + } + + } + + const boundingSphere = json.data.boundingSphere; + + if ( boundingSphere !== undefined ) { + + geometry.boundingSphere = new Sphere().fromJSON( boundingSphere ); + + } + + if ( json.name ) geometry.name = json.name; + if ( json.userData ) geometry.userData = json.userData; + + return geometry; + + } + +} + +const _customGeometries = {}; + +/** + * A loader for loading a JSON resource in the [JSON Object/Scene format](https://github.com/mrdoob/three.js/wiki/JSON-Object-Scene-format-4). + * The files are internally loaded via {@link FileLoader}. + * + * ```js + * const loader = new THREE.ObjectLoader(); + * const obj = await loader.loadAsync( 'models/json/example.json' ); + * scene.add( obj ); + * + * // Alternatively, to parse a previously loaded JSON structure + * const object = await loader.parseAsync( a_json_object ); + * scene.add( object ); + * ``` + * + * @augments Loader + */ +class ObjectLoader extends Loader { + + /** + * Constructs a new object loader. + * + * @param {LoadingManager} [manager] - The loading manager. + */ + constructor( manager ) { + + super( manager ); + + } + + /** + * Starts loading from the given URL and pass the loaded 3D object to the `onLoad()` callback. + * + * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI. + * @param {function(Object3D)} onLoad - Executed when the loading process has been finished. + * @param {onProgressCallback} onProgress - Executed while the loading is in progress. + * @param {onErrorCallback} onError - Executed when errors occur. + */ + load( url, onLoad, onProgress, onError ) { + + const scope = this; + + const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path; + this.resourcePath = this.resourcePath || path; + + const loader = new FileLoader( this.manager ); + loader.setPath( this.path ); + loader.setRequestHeader( this.requestHeader ); + loader.setWithCredentials( this.withCredentials ); + loader.load( url, function ( text ) { + + let json = null; + + try { + + json = JSON.parse( text ); + + } catch ( e ) { + + if ( onError !== undefined ) onError( e ); + + error( 'ObjectLoader: Can\'t parse ' + url + '.', e.message ); + + return; + + } + + const metadata = json.metadata; + + if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) { + + if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) ); + + error( 'ObjectLoader: Can\'t load ' + url ); + return; + + } + + scope.parse( json, onLoad ); + + }, onProgress, onError ); + + } + + /** + * Async version of {@link ObjectLoader#load}. + * + * @async + * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI. + * @param {onProgressCallback} onProgress - Executed while the loading is in progress. + * @return {Promise} A Promise that resolves with the loaded 3D object. + */ + async loadAsync( url, onProgress ) { + + const scope = this; + + const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path; + this.resourcePath = this.resourcePath || path; + + const loader = new FileLoader( this.manager ); + loader.setPath( this.path ); + loader.setRequestHeader( this.requestHeader ); + loader.setWithCredentials( this.withCredentials ); + + const text = await loader.loadAsync( url, onProgress ); + + let json; + + try { + + json = JSON.parse( text ); + + } catch ( e ) { + + throw new Error( 'THREE.ObjectLoader: Can\'t parse ' + url + '. ' + e.message ); + + } + + const metadata = json.metadata; + + if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) { + + throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url ); + + } + + return await scope.parseAsync( json ); + + } + + /** + * Parses the given JSON. This is used internally by {@link ObjectLoader#load} + * but can also be used directly to parse a previously loaded JSON structure. + * + * @param {Object} json - The serialized 3D object. + * @param {onLoad} onLoad - Executed when all resources (e.g. textures) have been fully loaded. + * @return {Object3D} The parsed 3D object. + */ + parse( json, onLoad ) { + + const animations = this.parseAnimations( json.animations ); + const shapes = this.parseShapes( json.shapes ); + const geometries = this.parseGeometries( json.geometries, shapes ); + + const images = this.parseImages( json.images, function () { + + if ( onLoad !== undefined ) onLoad( object ); + + } ); + + const textures = this.parseTextures( json.textures, images ); + const materials = this.parseMaterials( json.materials, textures ); + + const object = this.parseObject( json.object, geometries, materials, textures, animations ); + const skeletons = this.parseSkeletons( json.skeletons, object ); + + this.bindSkeletons( object, skeletons ); + this.bindLightTargets( object ); + + // + + if ( onLoad !== undefined ) { + + let hasImages = false; + + for ( const uuid in images ) { + + if ( images[ uuid ].data instanceof HTMLImageElement ) { + + hasImages = true; + break; + + } + + } + + if ( hasImages === false ) onLoad( object ); + + } + + return object; + + } + + /** + * Async version of {@link ObjectLoader#parse}. + * + * @param {Object} json - The serialized 3D object. + * @return {Promise} A Promise that resolves with the parsed 3D object. + */ + async parseAsync( json ) { + + const animations = this.parseAnimations( json.animations ); + const shapes = this.parseShapes( json.shapes ); + const geometries = this.parseGeometries( json.geometries, shapes ); + + const images = await this.parseImagesAsync( json.images ); + + const textures = this.parseTextures( json.textures, images ); + const materials = this.parseMaterials( json.materials, textures ); + + const object = this.parseObject( json.object, geometries, materials, textures, animations ); + const skeletons = this.parseSkeletons( json.skeletons, object ); + + this.bindSkeletons( object, skeletons ); + this.bindLightTargets( object ); + + return object; + + } + + /** + * Registers the given geometry at the internal + * geometry library. + * + * @static + * @param {string} type - The geometry type. + * @param {BufferGeometry.constructor} geometryClass - The geometry class. + */ + static registerGeometry( type, geometryClass ) { + + _customGeometries[ type ] = geometryClass; + + } + + // internals + + parseShapes( json ) { + + const shapes = {}; + + if ( json !== undefined ) { + + for ( let i = 0, l = json.length; i < l; i ++ ) { + + const shape = new Shape().fromJSON( json[ i ] ); + + shapes[ shape.uuid ] = shape; + + } + + } + + return shapes; + + } + + parseSkeletons( json, object ) { + + const skeletons = {}; + const bones = {}; + + // generate bone lookup table + + object.traverse( function ( child ) { + + if ( child.isBone ) bones[ child.uuid ] = child; + + } ); + + // create skeletons + + if ( json !== undefined ) { + + for ( let i = 0, l = json.length; i < l; i ++ ) { + + const skeleton = new Skeleton().fromJSON( json[ i ], bones ); + + skeletons[ skeleton.uuid ] = skeleton; + + } + + } + + return skeletons; + + } + + parseGeometries( json, shapes ) { + + const geometries = {}; + + if ( json !== undefined ) { + + const bufferGeometryLoader = new BufferGeometryLoader(); + + for ( let i = 0, l = json.length; i < l; i ++ ) { + + let geometry; + const data = json[ i ]; + + switch ( data.type ) { + + case 'BufferGeometry': + case 'InstancedBufferGeometry': + + geometry = bufferGeometryLoader.parse( data ); + break; + + default: + + if ( data.type in Geometries ) { + + geometry = Geometries[ data.type ].fromJSON( data, shapes ); + + } else if ( data.type in _customGeometries ) { + + geometry = _customGeometries[ data.type ].fromJSON( data, shapes ); + + } else { + + warn( `ObjectLoader: Unknown geometry type "${ data.type }". Use .registerGeometry() before starting the deserialization process.` ); + + } + + } + + geometry.uuid = data.uuid; + + if ( data.name !== undefined ) geometry.name = data.name; + if ( data.userData !== undefined ) geometry.userData = data.userData; + + geometries[ data.uuid ] = geometry; + + } + + } + + return geometries; + + } + + parseMaterials( json, textures ) { + + const cache = {}; // MultiMaterial + const materials = {}; + + if ( json !== undefined ) { + + const loader = new MaterialLoader(); + loader.setTextures( textures ); + + for ( let i = 0, l = json.length; i < l; i ++ ) { + + const data = json[ i ]; + + if ( cache[ data.uuid ] === undefined ) { + + cache[ data.uuid ] = loader.parse( data ); + + } + + materials[ data.uuid ] = cache[ data.uuid ]; + + } + + } + + return materials; + + } + + parseAnimations( json ) { + + const animations = {}; + + if ( json !== undefined ) { + + for ( let i = 0; i < json.length; i ++ ) { + + const data = json[ i ]; + + const clip = AnimationClip.parse( data ); + + animations[ clip.uuid ] = clip; + + } + + } + + return animations; + + } + + parseImages( json, onLoad ) { + + const scope = this; + const images = {}; + + let loader; + + function loadImage( url ) { + + url = scope.manager.resolveURL( url ); + + scope.manager.itemStart( url ); + + return loader.load( url, function () { + + scope.manager.itemEnd( url ); + + }, undefined, function () { + + scope.manager.itemError( url ); + scope.manager.itemEnd( url ); + + } ); + + } + + function deserializeImage( image ) { + + if ( typeof image === 'string' ) { + + const url = image; + + const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url; + + return loadImage( path ); + + } else { + + if ( image.data ) { + + return { + data: getTypedArray( image.type, image.data ), + width: image.width, + height: image.height + }; + + } else { + + return null; + + } + + } + + } + + if ( json !== undefined && json.length > 0 ) { + + const manager = new LoadingManager( onLoad ); + + loader = new ImageLoader( manager ); + loader.setCrossOrigin( this.crossOrigin ); + + for ( let i = 0, il = json.length; i < il; i ++ ) { + + const image = json[ i ]; + const url = image.url; + + if ( Array.isArray( url ) ) { + + // load array of images e.g CubeTexture + + const imageArray = []; + + for ( let j = 0, jl = url.length; j < jl; j ++ ) { + + const currentUrl = url[ j ]; + + const deserializedImage = deserializeImage( currentUrl ); + + if ( deserializedImage !== null ) { + + if ( deserializedImage instanceof HTMLImageElement ) { + + imageArray.push( deserializedImage ); + + } else { + + // special case: handle array of data textures for cube textures + + imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) ); + + } + + } + + } + + images[ image.uuid ] = new TextureSource( imageArray ); + + } else { + + // load single image + + const deserializedImage = deserializeImage( image.url ); + images[ image.uuid ] = new TextureSource( deserializedImage ); + + + } + + } + + } + + return images; + + } + + async parseImagesAsync( json ) { + + const scope = this; + const images = {}; + + let loader; + + async function deserializeImage( image ) { + + if ( typeof image === 'string' ) { + + const url = image; + + const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url; + + return await loader.loadAsync( path ); + + } else { + + if ( image.data ) { + + return { + data: getTypedArray( image.type, image.data ), + width: image.width, + height: image.height + }; + + } else { + + return null; + + } + + } + + } + + if ( json !== undefined && json.length > 0 ) { + + loader = new ImageLoader( this.manager ); + loader.setCrossOrigin( this.crossOrigin ); + + for ( let i = 0, il = json.length; i < il; i ++ ) { + + const image = json[ i ]; + const url = image.url; + + if ( Array.isArray( url ) ) { + + // load array of images e.g CubeTexture + + const imageArray = []; + + for ( let j = 0, jl = url.length; j < jl; j ++ ) { + + const currentUrl = url[ j ]; + + const deserializedImage = await deserializeImage( currentUrl ); + + if ( deserializedImage !== null ) { + + if ( deserializedImage instanceof HTMLImageElement ) { + + imageArray.push( deserializedImage ); + + } else { + + // special case: handle array of data textures for cube textures + + imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) ); + + } + + } + + } + + images[ image.uuid ] = new TextureSource( imageArray ); + + } else { + + // load single image + + const deserializedImage = await deserializeImage( image.url ); + images[ image.uuid ] = new TextureSource( deserializedImage ); + + } + + } + + } + + return images; + + } + + parseTextures( json, images ) { + + function parseConstant( value, type ) { + + if ( typeof value === 'number' ) return value; + + warn( 'ObjectLoader.parseTexture: Constant should be in numeric form.', value ); + + return type[ value ]; + + } + + const textures = {}; + + if ( json !== undefined ) { + + for ( let i = 0, l = json.length; i < l; i ++ ) { + + const data = json[ i ]; + + if ( data.image === undefined ) { + + warn( 'ObjectLoader: No "image" specified for', data.uuid ); + + } + + if ( images[ data.image ] === undefined ) { + + warn( 'ObjectLoader: Undefined image', data.image ); + + } + + const source = images[ data.image ]; + const image = source.data; + + let texture; + + if ( Array.isArray( image ) ) { + + texture = new CubeTexture(); + + if ( image.length === 6 ) texture.needsUpdate = true; + + } else { + + if ( image && image.data ) { + + texture = new DataTexture(); + + } else { + + texture = new Texture(); + + } + + if ( image ) texture.needsUpdate = true; // textures can have undefined image data + + } + + texture.source = source; + + texture.uuid = data.uuid; + + if ( data.name !== undefined ) texture.name = data.name; + + if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING ); + if ( data.channel !== undefined ) texture.channel = data.channel; + + if ( data.offset !== undefined ) texture.offset.fromArray( data.offset ); + if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat ); + if ( data.center !== undefined ) texture.center.fromArray( data.center ); + if ( data.rotation !== undefined ) texture.rotation = data.rotation; + + if ( data.wrap !== undefined ) { + + texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING ); + texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING ); + + } + + if ( data.format !== undefined ) texture.format = data.format; + if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat; + if ( data.type !== undefined ) texture.type = data.type; + if ( data.colorSpace !== undefined ) texture.colorSpace = data.colorSpace; + + if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER ); + if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER ); + if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy; + + if ( data.flipY !== undefined ) texture.flipY = data.flipY; + + if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps; + if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha; + if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment; + if ( data.compareFunction !== undefined ) texture.compareFunction = data.compareFunction; + if ( data.normalized !== undefined ) texture.normalized = data.normalized; + + if ( data.userData !== undefined ) texture.userData = data.userData; + + textures[ data.uuid ] = texture; + + } + + } + + return textures; + + } + + parseObject( data, geometries, materials, textures, animations ) { + + let object; + + function getGeometry( name ) { + + if ( geometries[ name ] === undefined ) { + + warn( 'ObjectLoader: Undefined geometry', name ); + + } + + return geometries[ name ]; + + } + + function getMaterial( name ) { + + if ( name === undefined ) return undefined; + + if ( Array.isArray( name ) ) { + + const array = []; + + for ( let i = 0, l = name.length; i < l; i ++ ) { + + const uuid = name[ i ]; + + if ( materials[ uuid ] === undefined ) { + + warn( 'ObjectLoader: Undefined material', uuid ); + + } + + array.push( materials[ uuid ] ); + + } + + return array; + + } + + if ( materials[ name ] === undefined ) { + + warn( 'ObjectLoader: Undefined material', name ); + + } + + return materials[ name ]; + + } + + function getTexture( uuid ) { + + if ( textures[ uuid ] === undefined ) { + + warn( 'ObjectLoader: Undefined texture', uuid ); + + } + + return textures[ uuid ]; + + } + + let geometry, material; + + switch ( data.type ) { + + case 'Scene': + + object = new Scene(); + + if ( data.background !== undefined ) { + + if ( Number.isInteger( data.background ) ) { + + object.background = new Color( data.background ); + + } else { + + object.background = getTexture( data.background ); + + } + + } + + if ( data.environment !== undefined ) { + + object.environment = getTexture( data.environment ); + + } + + if ( data.fog !== undefined ) { + + if ( data.fog.type === 'Fog' ) { + + object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far ); + + } else if ( data.fog.type === 'FogExp2' ) { + + object.fog = new FogExp2( data.fog.color, data.fog.density ); + + } + + if ( data.fog.name !== '' ) { + + object.fog.name = data.fog.name; + + } + + } + + if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness; + if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity; + if ( data.backgroundRotation !== undefined ) object.backgroundRotation.fromArray( data.backgroundRotation ); + + if ( data.environmentIntensity !== undefined ) object.environmentIntensity = data.environmentIntensity; + if ( data.environmentRotation !== undefined ) object.environmentRotation.fromArray( data.environmentRotation ); + + break; + + case 'PerspectiveCamera': + + object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far ); + + if ( data.focus !== undefined ) object.focus = data.focus; + if ( data.zoom !== undefined ) object.zoom = data.zoom; + if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge; + if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset; + if ( data.view !== undefined ) object.view = Object.assign( {}, data.view ); + + break; + + case 'OrthographicCamera': + + object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far ); + + if ( data.zoom !== undefined ) object.zoom = data.zoom; + if ( data.view !== undefined ) object.view = Object.assign( {}, data.view ); + + break; + + case 'AmbientLight': + + object = new AmbientLight( data.color, data.intensity ); + + break; + + case 'DirectionalLight': + + object = new DirectionalLight( data.color, data.intensity ); + object.target = data.target || ''; + + break; + + case 'PointLight': + + object = new PointLight( data.color, data.intensity, data.distance, data.decay ); + + break; + + case 'RectAreaLight': + + object = new RectAreaLight( data.color, data.intensity, data.width, data.height ); + + break; + + case 'SpotLight': + + object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay ); + object.target = data.target || ''; + + break; + + case 'HemisphereLight': + + object = new HemisphereLight( data.color, data.groundColor, data.intensity ); + + break; + + case 'LightProbe': + + const sh = new SphericalHarmonics3().fromArray( data.sh ); + object = new LightProbe( sh, data.intensity ); + + break; + + case 'SkinnedMesh': + + geometry = getGeometry( data.geometry ); + material = getMaterial( data.material ); + + object = new SkinnedMesh( geometry, material ); + + if ( data.bindMode !== undefined ) object.bindMode = data.bindMode; + if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix ); + if ( data.skeleton !== undefined ) object.skeleton = data.skeleton; + + break; + + case 'Mesh': + + geometry = getGeometry( data.geometry ); + material = getMaterial( data.material ); + + object = new Mesh( geometry, material ); + + break; + + case 'InstancedMesh': + + geometry = getGeometry( data.geometry ); + material = getMaterial( data.material ); + const count = data.count; + const instanceMatrix = data.instanceMatrix; + const instanceColor = data.instanceColor; + + object = new InstancedMesh( geometry, material, count ); + object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 ); + if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize ); + + break; + + case 'BatchedMesh': + + geometry = getGeometry( data.geometry ); + material = getMaterial( data.material ); + + object = new BatchedMesh( data.maxInstanceCount, data.maxVertexCount, data.maxIndexCount, material ); + object.geometry = geometry; + object.perObjectFrustumCulled = data.perObjectFrustumCulled; + object.sortObjects = data.sortObjects; + + object._drawRanges = data.drawRanges; + object._reservedRanges = data.reservedRanges; + + object._geometryInfo = data.geometryInfo.map( info => { + + let box = null; + let sphere = null; + if ( info.boundingBox !== undefined ) { + + box = new Box3().fromJSON( info.boundingBox ); + + } + + if ( info.boundingSphere !== undefined ) { + + sphere = new Sphere().fromJSON( info.boundingSphere ); + + } + + return { + ...info, + boundingBox: box, + boundingSphere: sphere + }; + + } ); + object._instanceInfo = data.instanceInfo; + + object._availableInstanceIds = data._availableInstanceIds; + object._availableGeometryIds = data._availableGeometryIds; + + object._nextIndexStart = data.nextIndexStart; + object._nextVertexStart = data.nextVertexStart; + object._geometryCount = data.geometryCount; + + object._maxInstanceCount = data.maxInstanceCount; + object._maxVertexCount = data.maxVertexCount; + object._maxIndexCount = data.maxIndexCount; + + object._geometryInitialized = data.geometryInitialized; + + object._matricesTexture = getTexture( data.matricesTexture.uuid ); + + object._indirectTexture = getTexture( data.indirectTexture.uuid ); + + if ( data.colorsTexture !== undefined ) { + + object._colorsTexture = getTexture( data.colorsTexture.uuid ); + + } + + if ( data.boundingSphere !== undefined ) { + + object.boundingSphere = new Sphere().fromJSON( data.boundingSphere ); + + } + + if ( data.boundingBox !== undefined ) { + + object.boundingBox = new Box3().fromJSON( data.boundingBox ); + + } + + break; + + case 'LOD': + + object = new LOD(); + + break; + + case 'Line': + + object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) ); + + break; + + case 'LineLoop': + + object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) ); + + break; + + case 'LineSegments': + + object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) ); + + break; + + case 'PointCloud': + case 'Points': + + object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) ); + + break; + + case 'Sprite': + + object = new Sprite( getMaterial( data.material ) ); + + break; + + case 'Group': + + object = new Group(); + + break; + + case 'Bone': + + object = new Bone(); + + break; + + default: + + object = new Object3D(); + + } + + object.uuid = data.uuid; + + if ( data.name !== undefined ) object.name = data.name; + + if ( data.matrix !== undefined ) { + + object.matrix.fromArray( data.matrix ); + + if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate; + if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale ); + + } else { + + if ( data.position !== undefined ) object.position.fromArray( data.position ); + if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation ); + if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion ); + if ( data.scale !== undefined ) object.scale.fromArray( data.scale ); + + } + + if ( data.up !== undefined ) object.up.fromArray( data.up ); + + if ( data.pivot !== undefined ) object.pivot = new Vector3().fromArray( data.pivot ); + + if ( data.morphTargetDictionary !== undefined ) object.morphTargetDictionary = Object.assign( {}, data.morphTargetDictionary ); + if ( data.morphTargetInfluences !== undefined ) object.morphTargetInfluences = data.morphTargetInfluences.slice(); + + if ( data.castShadow !== undefined ) object.castShadow = data.castShadow; + if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow; + + if ( data.shadow ) { + + if ( data.shadow.intensity !== undefined ) object.shadow.intensity = data.shadow.intensity; + if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias; + if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias; + if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius; + if ( data.shadow.blurSamples !== undefined ) object.shadow.blurSamples = data.shadow.blurSamples; + if ( data.shadow.focus !== undefined ) object.shadow.focus = data.shadow.focus; + if ( data.shadow.aspect !== undefined ) object.shadow.aspect = data.shadow.aspect; + if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize ); + if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera ); + + } + + if ( data.visible !== undefined ) object.visible = data.visible; + if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled; + if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder; + if ( data.static !== undefined ) object.static = data.static; + if ( data.userData !== undefined ) object.userData = data.userData; + if ( data.layers !== undefined ) object.layers.mask = data.layers; + + if ( data.children !== undefined ) { + + const children = data.children; + + for ( let i = 0; i < children.length; i ++ ) { + + object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) ); + + } + + } + + if ( data.animations !== undefined ) { + + const objectAnimations = data.animations; + + for ( let i = 0; i < objectAnimations.length; i ++ ) { + + const uuid = objectAnimations[ i ]; + + object.animations.push( animations[ uuid ] ); + + } + + } + + if ( data.type === 'LOD' ) { + + if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate; + + const levels = data.levels; + + for ( let l = 0; l < levels.length; l ++ ) { + + const level = levels[ l ]; + const child = object.getObjectByProperty( 'uuid', level.object ); + + if ( child !== undefined ) { + + object.addLevel( child, level.distance, level.hysteresis ); + + } + + } + + } + + return object; + + } + + bindSkeletons( object, skeletons ) { + + if ( Object.keys( skeletons ).length === 0 ) return; + + object.traverse( function ( child ) { + + if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) { + + const skeleton = skeletons[ child.skeleton ]; + + if ( skeleton === undefined ) { + + warn( 'ObjectLoader: No skeleton found with UUID:', child.skeleton ); + + } else { + + child.bind( skeleton, child.bindMatrix ); + + } + + } + + } ); + + } + + bindLightTargets( object ) { + + object.traverse( function ( child ) { + + if ( child.isDirectionalLight || child.isSpotLight ) { + + const uuid = child.target; + + const target = object.getObjectByProperty( 'uuid', uuid ); + + if ( target !== undefined ) { + + child.target = target; + + } else { + + child.target = new Object3D(); + + } + + } + + } ); + + } + +} + +const TEXTURE_MAPPING = { + UVMapping: UVMapping, + CubeReflectionMapping: CubeReflectionMapping, + CubeRefractionMapping: CubeRefractionMapping, + EquirectangularReflectionMapping: EquirectangularReflectionMapping, + EquirectangularRefractionMapping: EquirectangularRefractionMapping, + CubeUVReflectionMapping: CubeUVReflectionMapping +}; + +const TEXTURE_WRAPPING = { + RepeatWrapping: RepeatWrapping, + ClampToEdgeWrapping: ClampToEdgeWrapping, + MirroredRepeatWrapping: MirroredRepeatWrapping +}; + +const TEXTURE_FILTER = { + NearestFilter: NearestFilter, + NearestMipmapNearestFilter: NearestMipmapNearestFilter, + NearestMipmapLinearFilter: NearestMipmapLinearFilter, + LinearFilter: LinearFilter, + LinearMipmapNearestFilter: LinearMipmapNearestFilter, + LinearMipmapLinearFilter: LinearMipmapLinearFilter +}; + +const _errorMap = new WeakMap(); + +/** + * A loader for loading images as an [ImageBitmap](https://developer.mozilla.org/en-US/docs/Web/API/ImageBitmap). + * An `ImageBitmap` provides an asynchronous and resource efficient pathway to prepare + * textures for rendering. + * + * Note that {@link Texture#flipY} and {@link Texture#premultiplyAlpha} are ignored with image bitmaps. + * These options need to be configured via {@link ImageBitmapLoader#setOptions} prior to loading, + * unlike regular images which can be configured on the Texture to set these options on GPU upload instead. + * + * To match the default behaviour of {@link Texture}, the following options are needed: + * + * ```js + * { imageOrientation: 'flipY', premultiplyAlpha: 'none' } + * ``` + * + * Also note that unlike {@link FileLoader}, this loader will only avoid multiple concurrent requests to the same URL if {@link Cache} is enabled. + * + * ```js + * const loader = new THREE.ImageBitmapLoader(); + * loader.setOptions( { imageOrientation: 'flipY' } ); // set options if needed + * const imageBitmap = await loader.loadAsync( 'image.png' ); + * + * const texture = new THREE.Texture( imageBitmap ); + * texture.needsUpdate = true; + * ``` + * + * @augments Loader + */ +class ImageBitmapLoader extends Loader { + + /** + * Constructs a new image bitmap loader. + * + * @param {LoadingManager} [manager] - The loading manager. + */ + constructor( manager ) { + + super( manager ); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isImageBitmapLoader = true; + + if ( typeof createImageBitmap === 'undefined' ) { + + warn( 'ImageBitmapLoader: createImageBitmap() not supported.' ); + + } + + if ( typeof fetch === 'undefined' ) { + + warn( 'ImageBitmapLoader: fetch() not supported.' ); + + } + + /** + * Represents the loader options. + * + * @type {Object} + * @default {premultiplyAlpha:'none'} + */ + this.options = { premultiplyAlpha: 'none' }; + + /** + * Used for aborting requests. + * + * @private + * @type {AbortController} + */ + this._abortController = new AbortController(); + + } + + /** + * Sets the given loader options. The structure of the object must match the `options` parameter of + * [createImageBitmap](https://developer.mozilla.org/en-US/docs/Web/API/Window/createImageBitmap). + * + * Note: When caching is enabled, the cache key is based on the URL only. Loading the same URL with + * different options will return the cached result of the first request. + * + * @param {Object} options - The loader options to set. + * @return {ImageBitmapLoader} A reference to this image bitmap loader. + */ + setOptions( options ) { + + this.options = options; + + return this; + + } + + /** + * Starts loading from the given URL and pass the loaded image bitmap to the `onLoad()` callback. + * + * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI. + * @param {function(ImageBitmap)} onLoad - Executed when the loading process has been finished. + * @param {onProgressCallback} onProgress - Unsupported in this loader. + * @param {onErrorCallback} onError - Executed when errors occur. + */ + load( url, onLoad, onProgress, onError ) { + + if ( url === undefined ) url = ''; + + if ( this.path !== undefined ) url = this.path + url; + + url = this.manager.resolveURL( url ); + + const scope = this; + + const cached = Cache.get( `image-bitmap:${url}` ); + + if ( cached !== undefined ) { + + scope.manager.itemStart( url ); + + // If cached is a promise, wait for it to resolve + if ( cached.then ) { + + cached.then( imageBitmap => { + + // check if there is an error for the cached promise + + if ( _errorMap.has( cached ) === true ) { + + if ( onError ) onError( _errorMap.get( cached ) ); + + scope.manager.itemError( url ); + scope.manager.itemEnd( url ); + + } else { + + if ( onLoad ) onLoad( imageBitmap ); + + scope.manager.itemEnd( url ); + + } + + } ); + + return; + + } + + // If cached is not a promise (i.e., it's already an imageBitmap) + setTimeout( function () { + + if ( onLoad ) onLoad( cached ); + + scope.manager.itemEnd( url ); + + }, 0 ); + + return; + + } + + const fetchOptions = {}; + fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include'; + fetchOptions.headers = this.requestHeader; + fetchOptions.signal = ( typeof AbortSignal.any === 'function' ) ? AbortSignal.any( [ this._abortController.signal, this.manager.abortController.signal ] ) : this._abortController.signal; + + const promise = fetch( url, fetchOptions ).then( function ( res ) { + + return res.blob(); + + } ).then( function ( blob ) { + + return createImageBitmap( blob, Object.assign( {}, scope.options, { colorSpaceConversion: 'none' } ) ); + + } ).then( function ( imageBitmap ) { + + Cache.add( `image-bitmap:${url}`, imageBitmap ); + + if ( onLoad ) onLoad( imageBitmap ); + + scope.manager.itemEnd( url ); + + return imageBitmap; // see #34150 + + } ).catch( function ( e ) { + + if ( onError ) onError( e ); + + _errorMap.set( promise, e ); + + Cache.remove( `image-bitmap:${url}` ); + + scope.manager.itemError( url ); + scope.manager.itemEnd( url ); + + } ); + + Cache.add( `image-bitmap:${url}`, promise ); + scope.manager.itemStart( url ); + + } + + /** + * Aborts ongoing fetch requests. + * + * @return {ImageBitmapLoader} A reference to this instance. + */ + abort() { + + this._abortController.abort(); + this._abortController = new AbortController(); + + return this; + + } + +} + +let _context; + +/** + * Manages the global audio context in the engine. + * + * @hideconstructor + */ +class AudioContext { + + /** + * Returns the global native audio context. + * + * @return {Window.AudioContext} The native audio context. + */ + static getContext() { + + if ( _context === undefined ) { + + _context = new ( window.AudioContext || window.webkitAudioContext )(); + + } + + return _context; + + } + + /** + * Allows to set the global native audio context from outside. + * + * @param {Window.AudioContext} value - The native context to set. + */ + static setContext( value ) { + + _context = value; + + } + +} + +/** + * Class for loading audio buffers. Audios are internally + * loaded via {@link FileLoader}. + * + * ```js + * const audioListener = new THREE.AudioListener(); + * const ambientSound = new THREE.Audio( audioListener ); + * + * const loader = new THREE.AudioLoader(); + * const audioBuffer = await loader.loadAsync( 'audio/ambient_ocean.ogg' ); + * + * ambientSound.setBuffer( audioBuffer ); + * ambientSound.play(); + * ``` + * + * @augments Loader + */ +class AudioLoader extends Loader { + + /** + * Constructs a new audio loader. + * + * @param {LoadingManager} [manager] - The loading manager. + */ + constructor( manager ) { + + super( manager ); + + } + + /** + * Starts loading from the given URL and passes the loaded audio buffer + * to the `onLoad()` callback. + * + * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI. + * @param {function(AudioBuffer)} onLoad - Executed when the loading process has been finished. + * @param {onProgressCallback} onProgress - Executed while the loading is in progress. + * @param {onErrorCallback} onError - Executed when errors occur. + */ + load( url, onLoad, onProgress, onError ) { + + const scope = this; + + const loader = new FileLoader( this.manager ); + loader.setResponseType( 'arraybuffer' ); + loader.setPath( this.path ); + loader.setRequestHeader( this.requestHeader ); + loader.setWithCredentials( this.withCredentials ); + loader.load( url, function ( buffer ) { + + try { + + // Create a copy of the buffer. The `decodeAudioData` method + // detaches the buffer when complete, preventing reuse. + const bufferCopy = buffer.slice( 0 ); + + const context = AudioContext.getContext(); + + const decodeUrl = url + '#decode'; + scope.manager.itemStart( decodeUrl ); // prevent loading manager from completing too early, see #33378 + + context.decodeAudioData( bufferCopy, function ( audioBuffer ) { + + onLoad( audioBuffer ); + scope.manager.itemEnd( decodeUrl ); + + } ).catch( function ( e ) { + + handleError( e ); + scope.manager.itemEnd( decodeUrl ); + + } ); + + } catch ( e ) { + + handleError( e ); + + } + + }, onProgress, onError ); + + function handleError( e ) { + + if ( onError ) { + + onError( e ); + + } else { + + error( e ); + + } + + scope.manager.itemError( url ); + + } + + } + +} + +const _eyeRight = /*@__PURE__*/ new Matrix4(); +const _eyeLeft = /*@__PURE__*/ new Matrix4(); +const _projectionMatrix = /*@__PURE__*/ new Matrix4(); + +/** + * A special type of camera that uses two perspective cameras with + * stereoscopic projection. Can be used for rendering stereo effects + * like [3D Anaglyph](https://en.wikipedia.org/wiki/Anaglyph_3D) or + * [Parallax Barrier](https://en.wikipedia.org/wiki/parallax_barrier). + */ +class StereoCamera { + + /** + * Constructs a new stereo camera. + */ + constructor() { + + /** + * The type property is used for detecting the object type + * in context of serialization/deserialization. + * + * @type {string} + * @readonly + */ + this.type = 'StereoCamera'; + + /** + * The aspect. + * + * @type {number} + * @default 1 + */ + this.aspect = 1; + + /** + * The eye separation which represents the distance + * between the left and right camera. + * + * @type {number} + * @default 0.064 + */ + this.eyeSep = 0.064; + + /** + * The camera representing the left eye. This is added to layer `1` so objects to be + * rendered by the left camera must also be added to this layer. + * + * @type {PerspectiveCamera} + */ + this.cameraL = new PerspectiveCamera(); + this.cameraL.layers.enable( 1 ); + this.cameraL.matrixAutoUpdate = false; + + /** + * The camera representing the right eye. This is added to layer `2` so objects to be + * rendered by the right camera must also be added to this layer. + * + * @type {PerspectiveCamera} + */ + this.cameraR = new PerspectiveCamera(); + this.cameraR.layers.enable( 2 ); + this.cameraR.matrixAutoUpdate = false; + + this._cache = { + focus: null, + fov: null, + aspect: null, + near: null, + far: null, + zoom: null, + eyeSep: null + }; + + } + + /** + * Updates the stereo camera based on the given perspective camera. + * + * @param {PerspectiveCamera} camera - The perspective camera. + */ + update( camera ) { + + const cache = this._cache; + + const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov || + cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near || + cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep; + + if ( needsUpdate ) { + + cache.focus = camera.focus; + cache.fov = camera.fov; + cache.aspect = camera.aspect * this.aspect; + cache.near = camera.near; + cache.far = camera.far; + cache.zoom = camera.zoom; + cache.eyeSep = this.eyeSep; + + // Off-axis stereoscopic effect based on + // http://paulbourke.net/stereographics/stereorender/ + + _projectionMatrix.copy( camera.projectionMatrix ); + const eyeSepHalf = cache.eyeSep / 2; + const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus; + const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom; + let xmin, xmax; + + // translate xOffset + + _eyeLeft.elements[ 12 ] = - eyeSepHalf; + _eyeRight.elements[ 12 ] = eyeSepHalf; + + // for left eye + + xmin = - ymax * cache.aspect + eyeSepOnProjection; + xmax = ymax * cache.aspect + eyeSepOnProjection; + + _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin ); + _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin ); + + this.cameraL.projectionMatrix.copy( _projectionMatrix ); + + // for right eye + + xmin = - ymax * cache.aspect - eyeSepOnProjection; + xmax = ymax * cache.aspect - eyeSepOnProjection; + + _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin ); + _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin ); + + this.cameraR.projectionMatrix.copy( _projectionMatrix ); + + } + + this.cameraL.matrix.copy( camera.matrixWorld ).multiply( _eyeLeft ); + this.cameraL.matrixWorldNeedsUpdate = true; + + this.cameraR.matrix.copy( camera.matrixWorld ).multiply( _eyeRight ); + this.cameraR.matrixWorldNeedsUpdate = true; + + } + +} + +const fov = -90; // negative fov is not an error +const aspect = 1; + +/** + * A special type of camera that is positioned in 3D space to render its surroundings into a + * cube render target. The render target can then be used as an environment map for rendering + * realtime reflections in your scene. + * + * ```js + * // Create cube render target + * const cubeRenderTarget = new THREE.WebGLCubeRenderTarget( 256, { generateMipmaps: true, minFilter: THREE.LinearMipmapLinearFilter } ); + * + * // Create cube camera + * const cubeCamera = new THREE.CubeCamera( 1, 100000, cubeRenderTarget ); + * scene.add( cubeCamera ); + * + * // Create car + * const chromeMaterial = new THREE.MeshLambertMaterial( { color: 0xffffff, envMap: cubeRenderTarget.texture } ); + * const car = new THREE.Mesh( carGeometry, chromeMaterial ); + * scene.add( car ); + * + * // Update the render target cube + * car.visible = false; + * cubeCamera.position.copy( car.position ); + * cubeCamera.update( renderer, scene ); + * + * // Render the scene + * car.visible = true; + * renderer.render( scene, camera ); + * ``` + * + * @augments Object3D + */ +class CubeCamera extends Object3D { + + /** + * Constructs a new cube camera. + * + * @param {number} near - The camera's near plane. + * @param {number} far - The camera's far plane. + * @param {WebGLCubeRenderTarget} renderTarget - The cube render target. + */ + constructor( near, far, renderTarget ) { + + super(); + + this.type = 'CubeCamera'; + + /** + * A reference to the cube render target. + * + * @type {WebGLCubeRenderTarget} + */ + this.renderTarget = renderTarget; + + /** + * The current active coordinate system. + * + * @type {?(WebGLCoordinateSystem|WebGPUCoordinateSystem)} + * @default null + */ + this.coordinateSystem = null; + + /** + * The current active mipmap level + * + * @type {number} + * @default 0 + */ + this.activeMipmapLevel = 0; + + const cameraPX = new PerspectiveCamera( fov, aspect, near, far ); + cameraPX.layers = this.layers; + this.add( cameraPX ); + + const cameraNX = new PerspectiveCamera( fov, aspect, near, far ); + cameraNX.layers = this.layers; + this.add( cameraNX ); + + const cameraPY = new PerspectiveCamera( fov, aspect, near, far ); + cameraPY.layers = this.layers; + this.add( cameraPY ); + + const cameraNY = new PerspectiveCamera( fov, aspect, near, far ); + cameraNY.layers = this.layers; + this.add( cameraNY ); + + const cameraPZ = new PerspectiveCamera( fov, aspect, near, far ); + cameraPZ.layers = this.layers; + this.add( cameraPZ ); + + const cameraNZ = new PerspectiveCamera( fov, aspect, near, far ); + cameraNZ.layers = this.layers; + this.add( cameraNZ ); + + } + + /** + * Must be called when the coordinate system of the cube camera is changed. + */ + updateCoordinateSystem() { + + const coordinateSystem = this.coordinateSystem; + + const cameras = this.children.concat(); + + const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = cameras; + + for ( const camera of cameras ) this.remove( camera ); + + if ( coordinateSystem === WebGLCoordinateSystem ) { + + cameraPX.up.set( 0, 1, 0 ); + cameraPX.lookAt( 1, 0, 0 ); + + cameraNX.up.set( 0, 1, 0 ); + cameraNX.lookAt( -1, 0, 0 ); + + cameraPY.up.set( 0, 0, -1 ); + cameraPY.lookAt( 0, 1, 0 ); + + cameraNY.up.set( 0, 0, 1 ); + cameraNY.lookAt( 0, -1, 0 ); + + cameraPZ.up.set( 0, 1, 0 ); + cameraPZ.lookAt( 0, 0, 1 ); + + cameraNZ.up.set( 0, 1, 0 ); + cameraNZ.lookAt( 0, 0, -1 ); + + } else if ( coordinateSystem === WebGPUCoordinateSystem ) { + + cameraPX.up.set( 0, -1, 0 ); + cameraPX.lookAt( -1, 0, 0 ); + + cameraNX.up.set( 0, -1, 0 ); + cameraNX.lookAt( 1, 0, 0 ); + + cameraPY.up.set( 0, 0, 1 ); + cameraPY.lookAt( 0, 1, 0 ); + + cameraNY.up.set( 0, 0, -1 ); + cameraNY.lookAt( 0, -1, 0 ); + + cameraPZ.up.set( 0, -1, 0 ); + cameraPZ.lookAt( 0, 0, 1 ); + + cameraNZ.up.set( 0, -1, 0 ); + cameraNZ.lookAt( 0, 0, -1 ); + + } else { + + throw new Error( 'THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: ' + coordinateSystem ); + + } + + for ( const camera of cameras ) { + + this.add( camera ); + + camera.updateMatrixWorld(); + + } + + } + + /** + * Calling this method will render the given scene with the given renderer + * into the cube render target of the camera. + * + * @param {(Renderer|WebGLRenderer)} renderer - The renderer. + * @param {Scene} scene - The scene to render. + */ + update( renderer, scene ) { + + if ( this.parent === null ) this.updateMatrixWorld(); + + const { renderTarget, activeMipmapLevel } = this; + + if ( this.coordinateSystem !== renderer.coordinateSystem ) { + + this.coordinateSystem = renderer.coordinateSystem; + + this.updateCoordinateSystem(); + + } + + const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children; + + const currentRenderTarget = renderer.getRenderTarget(); + const currentActiveCubeFace = renderer.getActiveCubeFace(); + const currentActiveMipmapLevel = renderer.getActiveMipmapLevel(); + + const currentXrEnabled = renderer.xr.enabled; + + renderer.xr.enabled = false; + + const generateMipmaps = renderTarget.texture.generateMipmaps; + + renderTarget.texture.generateMipmaps = false; + + // https://github.com/mrdoob/three.js/issues/31413#issuecomment-3095966812 + + let reversedDepthBuffer = false; + + if ( renderer.isWebGLRenderer === true ) { + + reversedDepthBuffer = renderer.state.buffers.depth.getReversed(); + + } else { + + reversedDepthBuffer = renderer.reversedDepthBuffer; + + } + + renderer.setRenderTarget( renderTarget, 0, activeMipmapLevel ); + if ( reversedDepthBuffer && renderer.autoClear === false ) renderer.clearDepth(); + renderer.render( scene, cameraPX ); + + renderer.setRenderTarget( renderTarget, 1, activeMipmapLevel ); + if ( reversedDepthBuffer && renderer.autoClear === false ) renderer.clearDepth(); + renderer.render( scene, cameraNX ); + + renderer.setRenderTarget( renderTarget, 2, activeMipmapLevel ); + if ( reversedDepthBuffer && renderer.autoClear === false ) renderer.clearDepth(); + renderer.render( scene, cameraPY ); + + renderer.setRenderTarget( renderTarget, 3, activeMipmapLevel ); + if ( reversedDepthBuffer && renderer.autoClear === false ) renderer.clearDepth(); + renderer.render( scene, cameraNY ); + + renderer.setRenderTarget( renderTarget, 4, activeMipmapLevel ); + if ( reversedDepthBuffer && renderer.autoClear === false ) renderer.clearDepth(); + renderer.render( scene, cameraPZ ); + + // mipmaps are generated during the last call of render() + // at this point, all sides of the cube render target are defined + + renderTarget.texture.generateMipmaps = generateMipmaps; + + renderer.setRenderTarget( renderTarget, 5, activeMipmapLevel ); + if ( reversedDepthBuffer && renderer.autoClear === false ) renderer.clearDepth(); + renderer.render( scene, cameraNZ ); + + renderer.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel ); + + renderer.xr.enabled = currentXrEnabled; + + renderTarget.texture.needsPMREMUpdate = true; + + } + +} + +/** + * This type of camera can be used in order to efficiently render a scene with a + * predefined set of cameras. This is an important performance aspect for + * rendering VR scenes. + * + * An instance of `ArrayCamera` always has an array of sub cameras. It's mandatory + * to define for each sub camera the `viewport` property which determines the + * part of the viewport that is rendered with this camera. + * + * @augments PerspectiveCamera + */ +class ArrayCamera extends PerspectiveCamera { + + /** + * Constructs a new array camera. + * + * @param {Array} [array=[]] - An array of perspective sub cameras. + */ + constructor( array = [] ) { + + super(); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isArrayCamera = true; + + /** + * Whether this camera is used with multiview rendering or not. + * + * @type {boolean} + * @readonly + * @default false + */ + this.isMultiViewCamera = false; + + /** + * An array of perspective sub cameras. + * + * @type {Array} + */ + this.cameras = array; + + } + +} + +/** + * This class is an alternative to {@link Clock} with a different API design and behavior. + * The goal is to avoid the conceptual flaws that became apparent in `Clock` over time. + * + * - `Timer` has an `update()` method that updates its internal state. That makes it possible to + * call `getDelta()` and `getElapsed()` multiple times per simulation step without getting different values. + * - The class can make use of the Page Visibility API to avoid large time delta values when the app + * is inactive (e.g. tab switched or browser hidden). + * + * ```js + * const timer = new Timer(); + * timer.connect( document ); // use Page Visibility API + * ``` + */ +class Timer { + + /** + * Constructs a new timer. + */ + constructor() { + + this._previousTime = 0; + this._currentTime = 0; + this._startTime = performance.now(); + + this._delta = 0; + this._elapsed = 0; + + this._timescale = 1; + + this._document = null; + this._pageVisibilityHandler = null; + + } + + /** + * Connect the timer to the given document.Calling this method is not mandatory to + * use the timer but enables the usage of the Page Visibility API to avoid large time + * delta values. + * + * @param {Document} document - The document. + */ + connect( document ) { + + this._document = document; + + // use Page Visibility API to avoid large time delta values + + if ( document.hidden !== undefined ) { + + this._pageVisibilityHandler = handleVisibilityChange.bind( this ); + + document.addEventListener( 'visibilitychange', this._pageVisibilityHandler, false ); + + } + + } + + /** + * Disconnects the timer from the DOM and also disables the usage of the Page Visibility API. + */ + disconnect() { + + if ( this._pageVisibilityHandler !== null ) { + + this._document.removeEventListener( 'visibilitychange', this._pageVisibilityHandler ); + this._pageVisibilityHandler = null; + + } + + this._document = null; + + } + + /** + * Returns the time delta in seconds. + * + * @return {number} The time delta in second. + */ + getDelta() { + + return this._delta / 1000; + + } + + /** + * Returns the elapsed time in seconds. + * + * @return {number} The elapsed time in second. + */ + getElapsed() { + + return this._elapsed / 1000; + + } + + /** + * Returns the timescale. + * + * @return {number} The timescale. + */ + getTimescale() { + + return this._timescale; + + } + + /** + * Sets the given timescale which scale the time delta computation + * in `update()`. + * + * @param {number} timescale - The timescale to set. + * @return {Timer} A reference to this timer. + */ + setTimescale( timescale ) { + + this._timescale = timescale; + + return this; + + } + + /** + * Resets the time computation for the current simulation step. + * + * @return {Timer} A reference to this timer. + */ + reset() { + + this._currentTime = performance.now() - this._startTime; + + return this; + + } + + /** + * Can be used to free all internal resources. Usually called when + * the timer instance isn't required anymore. + */ + dispose() { + + this.disconnect(); + + } + + /** + * Updates the internal state of the timer. This method should be called + * once per simulation step and before you perform queries against the timer + * (e.g. via `getDelta()`). + * + * @param {number} timestamp - The current time in milliseconds. Can be obtained + * from the `requestAnimationFrame` callback argument. If not provided, the current + * time will be determined with `performance.now`. + * @return {Timer} A reference to this timer. + */ + update( timestamp ) { + + if ( this._pageVisibilityHandler !== null && this._document.hidden === true ) { + + this._delta = 0; + + } else { + + this._previousTime = this._currentTime; + this._currentTime = ( timestamp !== undefined ? timestamp : performance.now() ) - this._startTime; + + this._delta = ( this._currentTime - this._previousTime ) * this._timescale; + this._elapsed += this._delta; // _elapsed is the accumulation of all previous deltas + + } + + return this; + + } + +} + +function handleVisibilityChange() { + + if ( this._document.hidden === false ) this.reset(); + +} + +const _position$1 = /*@__PURE__*/ new Vector3(); +const _quaternion$1 = /*@__PURE__*/ new Quaternion(); +const _scale$1 = /*@__PURE__*/ new Vector3(); + +const _forward = /*@__PURE__*/ new Vector3(); +const _up = /*@__PURE__*/ new Vector3(); + +/** + * The class represents a virtual listener of the all positional and non-positional audio effects + * in the scene. A three.js application usually creates a single listener. It is a mandatory + * constructor parameter for audios entities like {@link Audio} and {@link PositionalAudio}. + * + * In most cases, the listener object is a child of the camera. So the 3D transformation of the + * camera represents the 3D transformation of the listener. + * + * @augments Object3D + */ +class AudioListener extends Object3D { + + /** + * Constructs a new audio listener. + */ + constructor() { + + super(); + + this.type = 'AudioListener'; + + /** + * The native audio context. + * + * @type {AudioContext} + * @readonly + */ + this.context = AudioContext.getContext(); + + /** + * The gain node used for volume control. + * + * @type {GainNode} + * @readonly + */ + this.gain = this.context.createGain(); + this.gain.connect( this.context.destination ); + + /** + * An optional filter. + * + * Defined via {@link AudioListener#setFilter}. + * + * @type {?AudioNode} + * @default null + * @readonly + */ + this.filter = null; + + /** + * Time delta values required for `linearRampToValueAtTime()` usage. + * + * @type {number} + * @default 0 + * @readonly + */ + this.timeDelta = 0; + + // private + + this._timer = new Timer(); + + } + + /** + * Returns the listener's input node. + * + * This method is used by other audio nodes to connect to this listener. + * + * @return {GainNode} The input node. + */ + getInput() { + + return this.gain; + + } + + /** + * Removes the current filter from this listener. + * + * @return {AudioListener} A reference to this listener. + */ + removeFilter() { + + if ( this.filter !== null ) { + + this.gain.disconnect( this.filter ); + this.filter.disconnect( this.context.destination ); + this.gain.connect( this.context.destination ); + this.filter = null; + + } + + return this; + + } + + /** + * Returns the current set filter. + * + * @return {?AudioNode} The filter. + */ + getFilter() { + + return this.filter; + + } + + /** + * Sets the given filter to this listener. + * + * @param {AudioNode} value - The filter to set. + * @return {AudioListener} A reference to this listener. + */ + setFilter( value ) { + + if ( this.filter !== null ) { + + this.gain.disconnect( this.filter ); + this.filter.disconnect( this.context.destination ); + + } else { + + this.gain.disconnect( this.context.destination ); + + } + + this.filter = value; + this.gain.connect( this.filter ); + this.filter.connect( this.context.destination ); + + return this; + + } + + /** + * Returns the applications master volume. + * + * @return {number} The master volume. + */ + getMasterVolume() { + + return this.gain.gain.value; + + } + + /** + * Sets the applications master volume. This volume setting affects + * all audio nodes in the scene. + * + * @param {number} value - The master volume to set. + * @return {AudioListener} A reference to this listener. + */ + setMasterVolume( value ) { + + this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 ); + + return this; + + } + + updateMatrixWorld( force ) { + + super.updateMatrixWorld( force ); + + this._timer.update(); + + const listener = this.context.listener; + + this.timeDelta = this._timer.getDelta(); + + this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 ); + + // the initial forward and up directions must be orthogonal + _forward.set( 0, 0, -1 ).applyQuaternion( _quaternion$1 ); + _up.set( 0, 1, 0 ).applyQuaternion( _quaternion$1 ); + + if ( listener.positionX ) { + + // code path for Chrome (see #14393) + + const endTime = this.context.currentTime + this.timeDelta; + + listener.positionX.linearRampToValueAtTime( _position$1.x, endTime ); + listener.positionY.linearRampToValueAtTime( _position$1.y, endTime ); + listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime ); + listener.forwardX.linearRampToValueAtTime( _forward.x, endTime ); + listener.forwardY.linearRampToValueAtTime( _forward.y, endTime ); + listener.forwardZ.linearRampToValueAtTime( _forward.z, endTime ); + listener.upX.linearRampToValueAtTime( _up.x, endTime ); + listener.upY.linearRampToValueAtTime( _up.y, endTime ); + listener.upZ.linearRampToValueAtTime( _up.z, endTime ); + + } else { + + listener.setPosition( _position$1.x, _position$1.y, _position$1.z ); + listener.setOrientation( _forward.x, _forward.y, _forward.z, _up.x, _up.y, _up.z ); + + } + + } + +} + +/** + * Represents a non-positional ( global ) audio object. + * + * This and related audio modules make use of the [Web Audio API](https://www.w3.org/TR/webaudio-1.1/). + * + * ```js + * // create an AudioListener and add it to the camera + * const listener = new THREE.AudioListener(); + * camera.add( listener ); + * + * // create a global audio source + * const sound = new THREE.Audio( listener ); + * + * // load a sound and set it as the Audio object's buffer + * const audioLoader = new THREE.AudioLoader(); + * audioLoader.load( 'sounds/ambient.ogg', function( buffer ) { + * sound.setBuffer( buffer ); + * sound.setLoop( true ); + * sound.setVolume( 0.5 ); + * sound.play(); + * }); + * ``` + * + * @augments Object3D + */ +class Audio extends Object3D { + + /** + * Constructs a new audio. + * + * @param {AudioListener} listener - The global audio listener. + */ + constructor( listener ) { + + super(); + + this.type = 'Audio'; + + /** + * The global audio listener. + * + * @type {AudioListener} + * @readonly + */ + this.listener = listener; + + /** + * The audio context. + * + * @type {AudioContext} + * @readonly + */ + this.context = listener.context; + + /** + * The gain node used for volume control. + * + * @type {GainNode} + * @readonly + */ + this.gain = this.context.createGain(); + this.gain.connect( listener.getInput() ); + + /** + * Whether to start playback automatically or not. + * + * @type {boolean} + * @default false + */ + this.autoplay = false; + + /** + * A reference to an audio buffer. + * + * Defined via {@link Audio#setBuffer}. + * + * @type {?AudioBuffer} + * @default null + * @readonly + */ + this.buffer = null; + + /** + * Modify pitch, measured in cents. +/- 100 is a semitone. + * +/- 1200 is an octave. + * + * Defined via {@link Audio#setDetune}. + * + * @type {number} + * @default 0 + * @readonly + */ + this.detune = 0; + + /** + * Whether the audio should loop or not. + * + * Defined via {@link Audio#setLoop}. + * + * @type {boolean} + * @default false + * @readonly + */ + this.loop = false; + + /** + * Defines where in the audio buffer the replay should + * start, in seconds. + * + * @type {number} + * @default 0 + */ + this.loopStart = 0; + + /** + * Defines where in the audio buffer the replay should + * stop, in seconds. + * + * @type {number} + * @default 0 + */ + this.loopEnd = 0; + + /** + * An offset to the time within the audio buffer the playback + * should begin, in seconds. + * + * @type {number} + * @default 0 + */ + this.offset = 0; + + /** + * Overrides the default duration of the audio. + * + * @type {undefined|number} + * @default undefined + */ + this.duration = undefined; + + /** + * The playback speed. + * + * Defined via {@link Audio#setPlaybackRate}. + * + * @type {number} + * @readonly + * @default 1 + */ + this.playbackRate = 1; + + /** + * Indicates whether the audio is playing or not. + * + * This flag will be automatically set when using {@link Audio#play}, + * {@link Audio#pause}, {@link Audio#stop}. + * + * @type {boolean} + * @readonly + * @default false + */ + this.isPlaying = false; + + /** + * Indicates whether the audio playback can be controlled + * with method like {@link Audio#play} or {@link Audio#pause}. + * + * This flag will be automatically set when audio sources are + * defined. + * + * @type {boolean} + * @readonly + * @default true + */ + this.hasPlaybackControl = true; + + /** + * Holds a reference to the current audio source. + * + * The property is automatically by one of the `set*()` methods. + * + * @type {?AudioNode} + * @readonly + * @default null + */ + this.source = null; + + /** + * Defines the source type. + * + * The property is automatically set by one of the `set*()` methods. + * + * @type {('empty'|'audioNode'|'mediaNode'|'mediaStreamNode'|'buffer')} + * @readonly + * @default 'empty' + */ + this.sourceType = 'empty'; + + this._startedAt = 0; + this._progress = 0; + this._connected = false; + + /** + * Can be used to apply a variety of low-order filters to create + * more complex sound effects e.g. via `BiquadFilterNode`. + * + * The property is automatically set by {@link Audio#setFilters}. + * + * @type {Array} + * @readonly + */ + this.filters = []; + + } + + /** + * Returns the output audio node. + * + * @return {GainNode} The output node. + */ + getOutput() { + + return this.gain; + + } + + /** + * Sets the given audio node as the source of this instance. + * + * {@link Audio#sourceType} is set to `audioNode` and {@link Audio#hasPlaybackControl} to `false`. + * + * @param {AudioNode} audioNode - The audio node like an instance of `OscillatorNode`. + * @return {Audio} A reference to this instance. + */ + setNodeSource( audioNode ) { + + this.hasPlaybackControl = false; + this.sourceType = 'audioNode'; + this.source = audioNode; + this.connect(); + + return this; + + } + + /** + * Sets the given media element as the source of this instance. + * + * {@link Audio#sourceType} is set to `mediaNode` and {@link Audio#hasPlaybackControl} to `false`. + * + * @param {HTMLMediaElement} mediaElement - The media element. + * @return {Audio} A reference to this instance. + */ + setMediaElementSource( mediaElement ) { + + this.hasPlaybackControl = false; + this.sourceType = 'mediaNode'; + this.source = this.context.createMediaElementSource( mediaElement ); + this.connect(); + + return this; + + } + + /** + * Sets the given media stream as the source of this instance. + * + * {@link Audio#sourceType} is set to `mediaStreamNode` and {@link Audio#hasPlaybackControl} to `false`. + * + * @param {MediaStream} mediaStream - The media stream. + * @return {Audio} A reference to this instance. + */ + setMediaStreamSource( mediaStream ) { + + this.hasPlaybackControl = false; + this.sourceType = 'mediaStreamNode'; + this.source = this.context.createMediaStreamSource( mediaStream ); + this.connect(); + + return this; + + } + + /** + * Sets the given audio buffer as the source of this instance. + * + * {@link Audio#sourceType} is set to `buffer` and {@link Audio#hasPlaybackControl} to `true`. + * + * @param {AudioBuffer} audioBuffer - The audio buffer. + * @return {Audio} A reference to this instance. + */ + setBuffer( audioBuffer ) { + + this.buffer = audioBuffer; + this.sourceType = 'buffer'; + + if ( this.autoplay ) this.play(); + + return this; + + } + + /** + * Starts the playback of the audio. + * + * Can only be used with compatible audio sources that allow playback control. + * + * @param {number} [delay=0] - The delay, in seconds, at which the audio should start playing. + * @return {Audio|undefined} A reference to this instance. + */ + play( delay = 0 ) { + + if ( this.isPlaying === true ) { + + warn( 'Audio: Audio is already playing.' ); + return; + + } + + if ( this.hasPlaybackControl === false ) { + + warn( 'Audio: this Audio has no playback control.' ); + return; + + } + + this._startedAt = this.context.currentTime + delay; + + const source = this.context.createBufferSource(); + source.buffer = this.buffer; + source.loop = this.loop; + source.loopStart = this.loopStart; + source.loopEnd = this.loopEnd; + source.onended = this.onEnded.bind( this ); + source.start( this._startedAt, this._progress + this.offset, this.duration ); + + this.isPlaying = true; + + this.source = source; + + this.setDetune( this.detune ); + this.setPlaybackRate( this.playbackRate ); + + return this.connect(); + + } + + /** + * Pauses the playback of the audio. + * + * Can only be used with compatible audio sources that allow playback control. + * + * @return {Audio|undefined} A reference to this instance. + */ + pause() { + + if ( this.hasPlaybackControl === false ) { + + warn( 'Audio: this Audio has no playback control.' ); + return; + + } + + if ( this.isPlaying === true ) { + + // update current progress + + this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate; + + if ( this.loop === true ) { + + // ensure _progress does not exceed duration with looped audios + + this._progress = this._progress % ( this.duration || this.buffer.duration ); + + } + + this.source.stop(); + this.source.onended = null; + + this.isPlaying = false; + + } + + return this; + + } + + /** + * Stops the playback of the audio. + * + * Can only be used with compatible audio sources that allow playback control. + * + * @param {number} [delay=0] - The delay, in seconds, at which the audio should stop playing. + * @return {Audio|undefined} A reference to this instance. + */ + stop( delay = 0 ) { + + if ( this.hasPlaybackControl === false ) { + + warn( 'Audio: this Audio has no playback control.' ); + return; + + } + + this._progress = 0; + + if ( this.source !== null ) { + + this.source.stop( this.context.currentTime + delay ); + this.source.onended = null; + + } + + this.isPlaying = false; + + return this; + + } + + /** + * Connects to the audio source. This is used internally on + * initialisation and when setting / removing filters. + * + * @return {Audio} A reference to this instance. + */ + connect() { + + if ( this.filters.length > 0 ) { + + this.source.connect( this.filters[ 0 ] ); + + for ( let i = 1, l = this.filters.length; i < l; i ++ ) { + + this.filters[ i - 1 ].connect( this.filters[ i ] ); + + } + + this.filters[ this.filters.length - 1 ].connect( this.getOutput() ); + + } else { + + this.source.connect( this.getOutput() ); + + } + + this._connected = true; + + return this; + + } + + /** + * Disconnects to the audio source. This is used internally on + * initialisation and when setting / removing filters. + * + * @return {Audio|undefined} A reference to this instance. + */ + disconnect() { + + if ( this._connected === false ) { + + return; + + } + + if ( this.filters.length > 0 ) { + + this.source.disconnect( this.filters[ 0 ] ); + + for ( let i = 1, l = this.filters.length; i < l; i ++ ) { + + this.filters[ i - 1 ].disconnect( this.filters[ i ] ); + + } + + this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() ); + + } else { + + this.source.disconnect( this.getOutput() ); + + } + + this._connected = false; + + return this; + + } + + /** + * Returns the current set filters. + * + * @return {Array} The list of filters. + */ + getFilters() { + + return this.filters; + + } + + /** + * Sets an array of filters and connects them with the audio source. + * + * @param {Array} [value] - A list of filters. + * @return {Audio} A reference to this instance. + */ + setFilters( value ) { + + if ( ! value ) value = []; + + if ( this._connected === true ) { + + this.disconnect(); + this.filters = value.slice(); + this.connect(); + + } else { + + this.filters = value.slice(); + + } + + return this; + + } + + /** + * Defines the detuning of oscillation in cents. + * + * @param {number} value - The detuning of oscillation in cents. + * @return {Audio} A reference to this instance. + */ + setDetune( value ) { + + this.detune = value; + + if ( this.isPlaying === true && this.source.detune !== undefined ) { + + this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 ); + + } + + return this; + + } + + /** + * Returns the detuning of oscillation in cents. + * + * @return {number} The detuning of oscillation in cents. + */ + getDetune() { + + return this.detune; + + } + + /** + * Returns the first filter in the list of filters. + * + * @return {AudioNode|undefined} The first filter in the list of filters. + */ + getFilter() { + + return this.getFilters()[ 0 ]; + + } + + /** + * Applies a single filter node to the audio. + * + * @param {AudioNode} [filter] - The filter to set. + * @return {Audio} A reference to this instance. + */ + setFilter( filter ) { + + return this.setFilters( filter ? [ filter ] : [] ); + + } + + /** + * Sets the playback rate. + * + * Can only be used with compatible audio sources that allow playback control. + * + * @param {number} [value] - The playback rate to set. + * @return {Audio|undefined} A reference to this instance. + */ + setPlaybackRate( value ) { + + if ( this.hasPlaybackControl === false ) { + + warn( 'Audio: this Audio has no playback control.' ); + return; + + } + + this.playbackRate = value; + + if ( this.isPlaying === true ) { + + this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 ); + + } + + return this; + + } + + /** + * Returns the current playback rate. + + * @return {number} The playback rate. + */ + getPlaybackRate() { + + return this.playbackRate; + + } + + /** + * Automatically called when playback finished. + */ + onEnded() { + + this.isPlaying = false; + this._progress = 0; + + } + + /** + * Returns the loop flag. + * + * Can only be used with compatible audio sources that allow playback control. + * + * @return {boolean} Whether the audio should loop or not. + */ + getLoop() { + + if ( this.hasPlaybackControl === false ) { + + warn( 'Audio: this Audio has no playback control.' ); + return false; + + } + + return this.loop; + + } + + /** + * Sets the loop flag. + * + * Can only be used with compatible audio sources that allow playback control. + * + * @param {boolean} value - Whether the audio should loop or not. + * @return {Audio|undefined} A reference to this instance. + */ + setLoop( value ) { + + if ( this.hasPlaybackControl === false ) { + + warn( 'Audio: this Audio has no playback control.' ); + return; + + } + + this.loop = value; + + if ( this.isPlaying === true ) { + + this.source.loop = this.loop; + + } + + return this; + + } + + /** + * Sets the loop start value which defines where in the audio buffer the replay should + * start, in seconds. + * + * @param {number} value - The loop start value. + * @return {Audio} A reference to this instance. + */ + setLoopStart( value ) { + + this.loopStart = value; + + return this; + + } + + /** + * Sets the loop end value which defines where in the audio buffer the replay should + * stop, in seconds. + * + * @param {number} value - The loop end value. + * @return {Audio} A reference to this instance. + */ + setLoopEnd( value ) { + + this.loopEnd = value; + + return this; + + } + + /** + * Returns the volume. + * + * @return {number} The volume. + */ + getVolume() { + + return this.gain.gain.value; + + } + + /** + * Sets the volume. + * + * @param {number} value - The volume to set. + * @return {Audio} A reference to this instance. + */ + setVolume( value ) { + + this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 ); + + return this; + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + if ( source.sourceType !== 'buffer' ) { + + warn( 'Audio: Audio source type cannot be copied.' ); + + return this; + + } + + this.autoplay = source.autoplay; + + this.buffer = source.buffer; + this.detune = source.detune; + this.loop = source.loop; + this.loopStart = source.loopStart; + this.loopEnd = source.loopEnd; + this.offset = source.offset; + this.duration = source.duration; + this.playbackRate = source.playbackRate; + this.hasPlaybackControl = source.hasPlaybackControl; + this.sourceType = source.sourceType; + + this.filters = source.filters.slice(); + + return this; + + } + + clone( recursive ) { + + return new this.constructor( this.listener ).copy( this, recursive ); + + } + +} + +const _position = /*@__PURE__*/ new Vector3(); +const _quaternion = /*@__PURE__*/ new Quaternion(); +const _scale = /*@__PURE__*/ new Vector3(); +const _orientation = /*@__PURE__*/ new Vector3(); + +/** + * Represents a positional audio object. + * + * ```js + * // create an AudioListener and add it to the camera + * const listener = new THREE.AudioListener(); + * camera.add( listener ); + * + * // create the PositionalAudio object (passing in the listener) + * const sound = new THREE.PositionalAudio( listener ); + * + * // load a sound and set it as the PositionalAudio object's buffer + * const audioLoader = new THREE.AudioLoader(); + * audioLoader.load( 'sounds/song.ogg', function( buffer ) { + * sound.setBuffer( buffer ); + * sound.setRefDistance( 20 ); + * sound.play(); + * }); + * + * // create an object for the sound to play from + * const sphere = new THREE.SphereGeometry( 20, 32, 16 ); + * const material = new THREE.MeshPhongMaterial( { color: 0xff2200 } ); + * const mesh = new THREE.Mesh( sphere, material ); + * scene.add( mesh ); + * + * // finally add the sound to the mesh + * mesh.add( sound ); + * + * @augments Audio + */ +class PositionalAudio extends Audio { + + /** + * Constructs a positional audio. + * + * @param {AudioListener} listener - The global audio listener. + */ + constructor( listener ) { + + super( listener ); + + /** + * The panner node represents the location, direction, and behavior of an audio + * source in 3D space. + * + * @type {PannerNode} + * @readonly + */ + this.panner = this.context.createPanner(); + this.panner.panningModel = 'HRTF'; + this.panner.connect( this.gain ); + + } + + connect() { + + super.connect(); + + this.panner.connect( this.gain ); + + return this; + + } + + disconnect() { + + super.disconnect(); + + this.panner.disconnect( this.gain ); + + return this; + + } + + getOutput() { + + return this.panner; + + } + + /** + * Returns the current reference distance. + * + * @return {number} The reference distance. + */ + getRefDistance() { + + return this.panner.refDistance; + + } + + /** + * Defines the reference distance for reducing volume as the audio source moves + * further from the listener – i.e. the distance at which the volume reduction + * starts taking effect. + * + * @param {number} value - The reference distance to set. + * @return {PositionalAudio} A reference to this instance. + */ + setRefDistance( value ) { + + this.panner.refDistance = value; + + return this; + + } + + /** + * Returns the current rolloff factor. + * + * @return {number} The rolloff factor. + */ + getRolloffFactor() { + + return this.panner.rolloffFactor; + + } + + /** + * Defines how quickly the volume is reduced as the source moves away from the listener. + * + * @param {number} value - The rolloff factor. + * @return {PositionalAudio} A reference to this instance. + */ + setRolloffFactor( value ) { + + this.panner.rolloffFactor = value; + + return this; + + } + + /** + * Returns the current distance model. + * + * @return {('linear'|'inverse'|'exponential')} The distance model. + */ + getDistanceModel() { + + return this.panner.distanceModel; + + } + + /** + * Defines which algorithm to use to reduce the volume of the audio source + * as it moves away from the listener. + * + * Read [the spec](https://www.w3.org/TR/webaudio-1.1/#enumdef-distancemodeltype) + * for more details. + * + * @param {('linear'|'inverse'|'exponential')} value - The distance model to set. + * @return {PositionalAudio} A reference to this instance. + */ + setDistanceModel( value ) { + + this.panner.distanceModel = value; + + return this; + + } + + /** + * Returns the current max distance. + * + * @return {number} The max distance. + */ + getMaxDistance() { + + return this.panner.maxDistance; + + } + + /** + * Defines the maximum distance between the audio source and the listener, + * after which the volume is not reduced any further. + * + * This value is used only by the `linear` distance model. + * + * @param {number} value - The max distance. + * @return {PositionalAudio} A reference to this instance. + */ + setMaxDistance( value ) { + + this.panner.maxDistance = value; + + return this; + + } + + /** + * Sets the directional cone in which the audio can be listened. + * + * @param {number} coneInnerAngle - An angle, in degrees, of a cone inside of which there will be no volume reduction. + * @param {number} coneOuterAngle - An angle, in degrees, of a cone outside of which the volume will be reduced by a constant value, defined by the `coneOuterGain` parameter. + * @param {number} coneOuterGain - The amount of volume reduction outside the cone defined by the `coneOuterAngle`. When set to `0`, no sound can be heard. + * @return {PositionalAudio} A reference to this instance. + */ + setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) { + + this.panner.coneInnerAngle = coneInnerAngle; + this.panner.coneOuterAngle = coneOuterAngle; + this.panner.coneOuterGain = coneOuterGain; + + return this; + + } + + updateMatrixWorld( force ) { + + super.updateMatrixWorld( force ); + + if ( this.hasPlaybackControl === true && this.isPlaying === false ) return; + + this.matrixWorld.decompose( _position, _quaternion, _scale ); + + _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion ); + + const panner = this.panner; + + if ( panner.positionX ) { + + // code path for Chrome and Firefox (see #14393) + + const endTime = this.context.currentTime + this.listener.timeDelta; + + panner.positionX.linearRampToValueAtTime( _position.x, endTime ); + panner.positionY.linearRampToValueAtTime( _position.y, endTime ); + panner.positionZ.linearRampToValueAtTime( _position.z, endTime ); + panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime ); + panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime ); + panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime ); + + } else { + + panner.setPosition( _position.x, _position.y, _position.z ); + panner.setOrientation( _orientation.x, _orientation.y, _orientation.z ); + + } + + } + +} + +/** + * This class can be used to analyse audio data. + * + * ```js + * // create an AudioListener and add it to the camera + * const listener = new THREE.AudioListener(); + * camera.add( listener ); + * + * // create an Audio source + * const sound = new THREE.Audio( listener ); + * + * // load a sound and set it as the Audio object's buffer + * const audioLoader = new THREE.AudioLoader(); + * audioLoader.load( 'sounds/ambient.ogg', function( buffer ) { + * sound.setBuffer( buffer ); + * sound.setLoop(true); + * sound.setVolume(0.5); + * sound.play(); + * }); + * + * // create an AudioAnalyser, passing in the sound and desired fftSize + * const analyser = new THREE.AudioAnalyser( sound, 32 ); + * + * // get the average frequency of the sound + * const data = analyser.getAverageFrequency(); + * ``` + */ +class AudioAnalyser { + + /** + * Constructs a new audio analyzer. + * + * @param {Audio} audio - The audio to analyze. + * @param {number} [fftSize=2048] - The window size in samples that is used when performing a Fast Fourier Transform (FFT) to get frequency domain data. + */ + constructor( audio, fftSize = 2048 ) { + + /** + * The global audio listener. + * + * @type {AnalyserNode} + */ + this.analyser = audio.context.createAnalyser(); + this.analyser.fftSize = fftSize; + + /** + * Holds the analyzed data. + * + * @type {Uint8Array} + */ + this.data = new Uint8Array( this.analyser.frequencyBinCount ); + + audio.getOutput().connect( this.analyser ); + + } + + /** + * Returns an array with frequency data of the audio. + * + * Each item in the array represents the decibel value for a specific frequency. + * The frequencies are spread linearly from 0 to 1/2 of the sample rate. + * For example, for 48000 sample rate, the last item of the array will represent + * the decibel value for 24000 Hz. + * + * @return {Uint8Array} The frequency data. + */ + getFrequencyData() { + + this.analyser.getByteFrequencyData( this.data ); + + return this.data; + + } + + /** + * Returns the average of the frequencies returned by {@link AudioAnalyser#getFrequencyData}. + * + * @return {number} The average frequency. + */ + getAverageFrequency() { + + let value = 0; + const data = this.getFrequencyData(); + + for ( let i = 0; i < data.length; i ++ ) { + + value += data[ i ]; + + } + + return value / data.length; + + } + +} + +/** + * Buffered scene graph property that allows weighted accumulation; used internally. + */ +class PropertyMixer { + + /** + * Constructs a new property mixer. + * + * @param {PropertyBinding} binding - The property binding. + * @param {string} typeName - The keyframe track type name. + * @param {number} valueSize - The keyframe track value size. + */ + constructor( binding, typeName, valueSize ) { + + /** + * The property binding. + * + * @type {PropertyBinding} + */ + this.binding = binding; + + /** + * The keyframe track value size. + * + * @type {number} + */ + this.valueSize = valueSize; + + let mixFunction, + mixFunctionAdditive, + setIdentity; + + // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ] + // + // interpolators can use .buffer as their .result + // the data then goes to 'incoming' + // + // 'accu0' and 'accu1' are used frame-interleaved for + // the cumulative result and are compared to detect + // changes + // + // 'orig' stores the original state of the property + // + // 'add' is used for additive cumulative results + // + // 'work' is optional and is only present for quaternion types. It is used + // to store intermediate quaternion multiplication results + + switch ( typeName ) { + + case 'quaternion': + mixFunction = this._slerp; + mixFunctionAdditive = this._slerpAdditive; + setIdentity = this._setAdditiveIdentityQuaternion; + + this.buffer = new Float64Array( valueSize * 6 ); + this._workIndex = 5; + break; + + case 'string': + case 'bool': + mixFunction = this._select; + + // Use the regular mix function and for additive on these types, + // additive is not relevant for non-numeric types + mixFunctionAdditive = this._select; + + setIdentity = this._setAdditiveIdentityOther; + + this.buffer = new Array( valueSize * 5 ); + break; + + default: + mixFunction = this._lerp; + mixFunctionAdditive = this._lerpAdditive; + setIdentity = this._setAdditiveIdentityNumeric; + + this.buffer = new Float64Array( valueSize * 5 ); + + } + + this._mixBufferRegion = mixFunction; + this._mixBufferRegionAdditive = mixFunctionAdditive; + this._setIdentity = setIdentity; + this._origIndex = 3; + this._addIndex = 4; + + /** + * Accumulated weight of the property binding. + * + * @type {number} + * @default 0 + */ + this.cumulativeWeight = 0; + + /** + * Accumulated additive weight of the property binding. + * + * @type {number} + * @default 0 + */ + this.cumulativeWeightAdditive = 0; + + /** + * Number of active keyframe tracks currently using this property binding. + * + * @type {number} + * @default 0 + */ + this.useCount = 0; + + /** + * Number of keyframe tracks referencing this property binding. + * + * @type {number} + * @default 0 + */ + this.referenceCount = 0; + + } + + /** + * Accumulates data in the `incoming` region into `accu`. + * + * @param {number} accuIndex - The accumulation index. + * @param {number} weight - The weight. + */ + accumulate( accuIndex, weight ) { + + // note: happily accumulating nothing when weight = 0, the caller knows + // the weight and shouldn't have made the call in the first place + + const buffer = this.buffer, + stride = this.valueSize, + offset = accuIndex * stride + stride; + + let currentWeight = this.cumulativeWeight; + + if ( currentWeight === 0 ) { + + // accuN := incoming * weight + + for ( let i = 0; i !== stride; ++ i ) { + + buffer[ offset + i ] = buffer[ i ]; + + } + + currentWeight = weight; + + } else { + + // accuN := accuN + incoming * weight + + currentWeight += weight; + const mix = weight / currentWeight; + this._mixBufferRegion( buffer, offset, 0, mix, stride ); + + } + + this.cumulativeWeight = currentWeight; + + } + + /** + * Accumulates data in the `incoming` region into `add`. + * + * @param {number} weight - The weight. + */ + accumulateAdditive( weight ) { + + const buffer = this.buffer, + stride = this.valueSize, + offset = stride * this._addIndex; + + if ( this.cumulativeWeightAdditive === 0 ) { + + // add = identity + + this._setIdentity(); + + } + + // add := add + incoming * weight + + this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride ); + this.cumulativeWeightAdditive += weight; + + } + + /** + * Applies the state of `accu` to the binding when accus differ. + * + * @param {number} accuIndex - The accumulation index. + */ + apply( accuIndex ) { + + const stride = this.valueSize, + buffer = this.buffer, + offset = accuIndex * stride + stride, + + weight = this.cumulativeWeight, + weightAdditive = this.cumulativeWeightAdditive, + + binding = this.binding; + + this.cumulativeWeight = 0; + this.cumulativeWeightAdditive = 0; + + if ( weight < 1 ) { + + // accuN := accuN + original * ( 1 - cumulativeWeight ) + + const originalValueOffset = stride * this._origIndex; + + this._mixBufferRegion( + buffer, offset, originalValueOffset, 1 - weight, stride ); + + } + + if ( weightAdditive > 0 ) { + + // accuN := accuN + additive accuN + + this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride ); + + } + + for ( let i = stride, e = stride + stride; i !== e; ++ i ) { + + if ( buffer[ i ] !== buffer[ i + stride ] ) { + + // value has changed -> update scene graph + + binding.setValue( buffer, offset ); + break; + + } + + } + + } + + + /** + * Remembers the state of the bound property and copy it to both accus. + */ + saveOriginalState() { + + const binding = this.binding; + + const buffer = this.buffer, + stride = this.valueSize, + + originalValueOffset = stride * this._origIndex; + + binding.getValue( buffer, originalValueOffset ); + + // accu[0..1] := orig -- initially detect changes against the original + for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) { + + buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ]; + + } + + // Add to identity for additive + this._setIdentity(); + + this.cumulativeWeight = 0; + this.cumulativeWeightAdditive = 0; + + } + + /** + * Applies the state previously taken via {@link PropertyMixer#saveOriginalState} to the binding. + */ + restoreOriginalState() { + + const originalValueOffset = this.valueSize * 3; + this.binding.setValue( this.buffer, originalValueOffset ); + + } + + // internals + + _setAdditiveIdentityNumeric() { + + const startIndex = this._addIndex * this.valueSize; + const endIndex = startIndex + this.valueSize; + + for ( let i = startIndex; i < endIndex; i ++ ) { + + this.buffer[ i ] = 0; + + } + + } + + _setAdditiveIdentityQuaternion() { + + this._setAdditiveIdentityNumeric(); + this.buffer[ this._addIndex * this.valueSize + 3 ] = 1; + + } + + _setAdditiveIdentityOther() { + + const startIndex = this._origIndex * this.valueSize; + const targetIndex = this._addIndex * this.valueSize; + + for ( let i = 0; i < this.valueSize; i ++ ) { + + this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ]; + + } + + } + + + // mix functions + + _select( buffer, dstOffset, srcOffset, t, stride ) { + + if ( t >= 0.5 ) { + + for ( let i = 0; i !== stride; ++ i ) { + + buffer[ dstOffset + i ] = buffer[ srcOffset + i ]; + + } + + } + + } + + _slerp( buffer, dstOffset, srcOffset, t ) { + + Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t ); + + } + + _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) { + + const workOffset = this._workIndex * stride; + + // Store result in intermediate buffer offset + Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset ); + + // Slerp to the intermediate result + Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t ); + + } + + _lerp( buffer, dstOffset, srcOffset, t, stride ) { + + const s = 1 - t; + + for ( let i = 0; i !== stride; ++ i ) { + + const j = dstOffset + i; + + buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t; + + } + + } + + _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) { + + for ( let i = 0; i !== stride; ++ i ) { + + const j = dstOffset + i; + + buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t; + + } + + } + +} + +// Characters [].:/ are reserved for track binding syntax. +const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/'; +const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' ); + +// Attempts to allow node names from any language. ES5's `\w` regexp matches +// only latin characters, and the unicode \p{L} is not yet supported. So +// instead, we exclude reserved characters and match everything else. +const _wordChar = '[^' + _RESERVED_CHARS_RE + ']'; +const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']'; + +// Parent directories, delimited by '/' or ':'. Currently unused, but must +// be matched to parse the rest of the track name. +const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar ); + +// Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'. +const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot ); + +// Object on target node, and accessor. May not contain reserved +// characters. Accessor may contain any character except closing bracket. +const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar ); + +// Property and accessor. May not contain reserved characters. Accessor may +// contain any non-bracket characters. +const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar ); + +const _trackRe = new RegExp( '' + + '^' + + _directoryRe + + _nodeRe + + _objectRe + + _propertyRe + + '$' +); + +const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ]; + +class Composite { + + constructor( targetGroup, path, optionalParsedPath ) { + + const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path ); + + this._targetGroup = targetGroup; + this._bindings = targetGroup.subscribe_( path, parsedPath ); + + } + + getValue( array, offset ) { + + this.bind(); // bind all binding + + const firstValidIndex = this._targetGroup.nCachedObjects_, + binding = this._bindings[ firstValidIndex ]; + + // and only call .getValue on the first + if ( binding !== undefined ) binding.getValue( array, offset ); + + } + + setValue( array, offset ) { + + const bindings = this._bindings; + + for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) { + + bindings[ i ].setValue( array, offset ); + + } + + } + + bind() { + + const bindings = this._bindings; + + for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) { + + bindings[ i ].bind(); + + } + + } + + unbind() { + + const bindings = this._bindings; + + for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) { + + bindings[ i ].unbind(); + + } + + } + +} + +// Note: This class uses a State pattern on a per-method basis: +// 'bind' sets 'this.getValue' / 'setValue' and shadows the +// prototype version of these methods with one that represents +// the bound state. When the property is not found, the methods +// become no-ops. + + +/** + * This holds a reference to a real property in the scene graph; used internally. + */ +class PropertyBinding { + + /** + * Constructs a new property binding. + * + * @param {Object} rootNode - The root node. + * @param {string} path - The path. + * @param {?Object} [parsedPath] - The parsed path. + */ + constructor( rootNode, path, parsedPath ) { + + /** + * The object path to the animated property. + * + * @type {string} + */ + this.path = path; + + /** + * An object holding information about the path. + * + * @type {Object} + */ + this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path ); + + /** + * The object owns the animated property. + * + * @type {?Object} + */ + this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName ); + + /** + * The root node. + * + * @type {Object3D|Skeleton} + */ + this.rootNode = rootNode; + + // initial state of these methods that calls 'bind' + this.getValue = this._getValue_unbound; + this.setValue = this._setValue_unbound; + + } + + + /** + * Factory method for creating a property binding from the given parameters. + * + * @static + * @param {Object} root - The root node. + * @param {string} path - The path. + * @param {?Object} [parsedPath] - The parsed path. + * @return {PropertyBinding|Composite} The created property binding or composite. + */ + static create( root, path, parsedPath ) { + + if ( ! ( root && root.isAnimationObjectGroup ) ) { + + return new PropertyBinding( root, path, parsedPath ); + + } else { + + return new PropertyBinding.Composite( root, path, parsedPath ); + + } + + } + + /** + * Replaces spaces with underscores and removes unsupported characters from + * node names, to ensure compatibility with parseTrackName(). + * + * @param {string} name - Node name to be sanitized. + * @return {string} The sanitized node name. + */ + static sanitizeNodeName( name ) { + + return name.replace( /\s/g, '_' ).replace( _reservedRe, '' ); + + } + + /** + * Parses the given track name (an object path to an animated property) and + * returns an object with information about the path. Matches strings in the following forms: + * + * - nodeName.property + * - nodeName.property[accessor] + * - nodeName.material.property[accessor] + * - uuid.property[accessor] + * - uuid.objectName[objectIndex].propertyName[propertyIndex] + * - parentName/nodeName.property + * - parentName/parentName/nodeName.property[index] + * - .bone[Armature.DEF_cog].position + * - scene:helium_balloon_model:helium_balloon_model.position + * + * @static + * @param {string} trackName - The track name to parse. + * @return {Object} The parsed track name as an object. + */ + static parseTrackName( trackName ) { + + const matches = _trackRe.exec( trackName ); + + if ( matches === null ) { + + throw new Error( 'THREE.PropertyBinding: Cannot parse trackName: ' + trackName ); + + } + + const results = { + // directoryName: matches[ 1 ], // (tschw) currently unused + nodeName: matches[ 2 ], + objectName: matches[ 3 ], + objectIndex: matches[ 4 ], + propertyName: matches[ 5 ], // required + propertyIndex: matches[ 6 ] + }; + + const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' ); + + if ( lastDot !== undefined && lastDot !== -1 ) { + + const objectName = results.nodeName.substring( lastDot + 1 ); + + // Object names must be checked against an allowlist. Otherwise, there + // is no way to parse 'foo.bar.baz': 'baz' must be a property, but + // 'bar' could be the objectName, or part of a nodeName (which can + // include '.' characters). + if ( _supportedObjectNames.indexOf( objectName ) !== -1 ) { + + results.nodeName = results.nodeName.substring( 0, lastDot ); + results.objectName = objectName; + + } + + } + + if ( results.propertyName === null || results.propertyName.length === 0 ) { + + throw new Error( 'THREE.PropertyBinding: can not parse propertyName from trackName: ' + trackName ); + + } + + return results; + + } + + /** + * Searches for a node in the hierarchy of the given root object by the given + * node name. + * + * @static + * @param {Object} root - The root object. + * @param {string|number} nodeName - The name of the node. + * @return {?Object} The found node. Returns `null` if no object was found. + */ + static findNode( root, nodeName ) { + + if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === -1 || nodeName === root.name || nodeName === root.uuid ) { + + return root; + + } + + // search into skeleton bones. + if ( root.skeleton ) { + + const bone = root.skeleton.getBoneByName( nodeName ); + + if ( bone !== undefined ) { + + return bone; + + } + + } + + // search into node subtree. + if ( root.children ) { + + const searchNodeSubtree = function ( children ) { + + for ( let i = 0; i < children.length; i ++ ) { + + const childNode = children[ i ]; + + if ( childNode.name === nodeName || childNode.uuid === nodeName ) { + + return childNode; + + } + + const result = searchNodeSubtree( childNode.children ); + + if ( result ) return result; + + } + + return null; + + }; + + const subTreeNode = searchNodeSubtree( root.children ); + + if ( subTreeNode ) { + + return subTreeNode; + + } + + } + + return null; + + } + + // these are used to "bind" a nonexistent property + _getValue_unavailable() {} + _setValue_unavailable() {} + + // Getters + + _getValue_direct( buffer, offset ) { + + buffer[ offset ] = this.targetObject[ this.propertyName ]; + + } + + _getValue_array( buffer, offset ) { + + const source = this.resolvedProperty; + + for ( let i = 0, n = source.length; i !== n; ++ i ) { + + buffer[ offset ++ ] = source[ i ]; + + } + + } + + _getValue_arrayElement( buffer, offset ) { + + buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ]; + + } + + _getValue_toArray( buffer, offset ) { + + this.resolvedProperty.toArray( buffer, offset ); + + } + + // Direct + + _setValue_direct( buffer, offset ) { + + this.targetObject[ this.propertyName ] = buffer[ offset ]; + + } + + _setValue_direct_setNeedsUpdate( buffer, offset ) { + + this.targetObject[ this.propertyName ] = buffer[ offset ]; + this.targetObject.needsUpdate = true; + + } + + _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) { + + this.targetObject[ this.propertyName ] = buffer[ offset ]; + this.targetObject.matrixWorldNeedsUpdate = true; + + } + + // EntireArray + + _setValue_array( buffer, offset ) { + + const dest = this.resolvedProperty; + + for ( let i = 0, n = dest.length; i !== n; ++ i ) { + + dest[ i ] = buffer[ offset ++ ]; + + } + + } + + _setValue_array_setNeedsUpdate( buffer, offset ) { + + const dest = this.resolvedProperty; + + for ( let i = 0, n = dest.length; i !== n; ++ i ) { + + dest[ i ] = buffer[ offset ++ ]; + + } + + this.targetObject.needsUpdate = true; + + } + + _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) { + + const dest = this.resolvedProperty; + + for ( let i = 0, n = dest.length; i !== n; ++ i ) { + + dest[ i ] = buffer[ offset ++ ]; + + } + + this.targetObject.matrixWorldNeedsUpdate = true; + + } + + // ArrayElement + + _setValue_arrayElement( buffer, offset ) { + + this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ]; + + } + + _setValue_arrayElement_setNeedsUpdate( buffer, offset ) { + + this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ]; + this.targetObject.needsUpdate = true; + + } + + _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) { + + this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ]; + this.targetObject.matrixWorldNeedsUpdate = true; + + } + + // HasToFromArray + + _setValue_fromArray( buffer, offset ) { + + this.resolvedProperty.fromArray( buffer, offset ); + + } + + _setValue_fromArray_setNeedsUpdate( buffer, offset ) { + + this.resolvedProperty.fromArray( buffer, offset ); + this.targetObject.needsUpdate = true; + + } + + _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) { + + this.resolvedProperty.fromArray( buffer, offset ); + this.targetObject.matrixWorldNeedsUpdate = true; + + } + + _getValue_unbound( targetArray, offset ) { + + this.bind(); + this.getValue( targetArray, offset ); + + } + + _setValue_unbound( sourceArray, offset ) { + + this.bind(); + this.setValue( sourceArray, offset ); + + } + + /** + * Creates a getter / setter pair for the property tracked by this binding. + */ + bind() { + + let targetObject = this.node; + const parsedPath = this.parsedPath; + + const objectName = parsedPath.objectName; + const propertyName = parsedPath.propertyName; + let propertyIndex = parsedPath.propertyIndex; + + if ( ! targetObject ) { + + targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName ); + + this.node = targetObject; + + } + + // set fail state so we can just 'return' on error + this.getValue = this._getValue_unavailable; + this.setValue = this._setValue_unavailable; + + // ensure there is a value node + if ( ! targetObject ) { + + warn( 'PropertyBinding: No target node found for track: ' + this.path + '.' ); + return; + + } + + if ( objectName ) { + + let objectIndex = parsedPath.objectIndex; + + // special cases were we need to reach deeper into the hierarchy to get the face materials.... + switch ( objectName ) { + + case 'materials': + + if ( ! targetObject.material ) { + + error( 'PropertyBinding: Can not bind to material as node does not have a material.', this ); + return; + + } + + if ( ! targetObject.material.materials ) { + + error( 'PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this ); + return; + + } + + targetObject = targetObject.material.materials; + + break; + + case 'bones': + + if ( ! targetObject.skeleton ) { + + error( 'PropertyBinding: Can not bind to bones as node does not have a skeleton.', this ); + return; + + } + + // potential future optimization: skip this if propertyIndex is already an integer + // and convert the integer string to a true integer. + + targetObject = targetObject.skeleton.bones; + + // support resolving morphTarget names into indices. + for ( let i = 0; i < targetObject.length; i ++ ) { + + if ( targetObject[ i ].name === objectIndex ) { + + objectIndex = i; + break; + + } + + } + + break; + + case 'map': + + if ( 'map' in targetObject ) { + + targetObject = targetObject.map; + break; + + } + + if ( ! targetObject.material ) { + + error( 'PropertyBinding: Can not bind to material as node does not have a material.', this ); + return; + + } + + if ( ! targetObject.material.map ) { + + error( 'PropertyBinding: Can not bind to material.map as node.material does not have a map.', this ); + return; + + } + + targetObject = targetObject.material.map; + break; + + default: + + if ( targetObject[ objectName ] === undefined ) { + + error( 'PropertyBinding: Can not bind to objectName of node undefined.', this ); + return; + + } + + targetObject = targetObject[ objectName ]; + + } + + + if ( objectIndex !== undefined ) { + + if ( targetObject[ objectIndex ] === undefined ) { + + error( 'PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject ); + return; + + } + + targetObject = targetObject[ objectIndex ]; + + } + + } + + // resolve property + const nodeProperty = targetObject[ propertyName ]; + + if ( nodeProperty === undefined ) { + + const nodeName = parsedPath.nodeName; + + error( 'PropertyBinding: Trying to update property for track: ' + nodeName + + '.' + propertyName + ' but it wasn\'t found.', targetObject ); + return; + + } + + // determine versioning scheme + let versioning = this.Versioning.None; + + this.targetObject = targetObject; + + if ( targetObject.isMaterial === true ) { + + versioning = this.Versioning.NeedsUpdate; + + } else if ( targetObject.isObject3D === true ) { + + versioning = this.Versioning.MatrixWorldNeedsUpdate; + + } + + // determine how the property gets bound + let bindingType = this.BindingType.Direct; + + if ( propertyIndex !== undefined ) { + + // access a sub element of the property array (only primitives are supported right now) + + if ( propertyName === 'morphTargetInfluences' ) { + + // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer. + + // support resolving morphTarget names into indices. + if ( ! targetObject.geometry ) { + + error( 'PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this ); + return; + + } + + if ( ! targetObject.geometry.morphAttributes ) { + + error( 'PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this ); + return; + + } + + if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) { + + propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ]; + + } + + } + + bindingType = this.BindingType.ArrayElement; + + this.resolvedProperty = nodeProperty; + this.propertyIndex = propertyIndex; + + } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) { + + // must use copy for Object3D.Euler/Quaternion + + bindingType = this.BindingType.HasFromToArray; + + this.resolvedProperty = nodeProperty; + + } else if ( Array.isArray( nodeProperty ) ) { + + bindingType = this.BindingType.EntireArray; + + this.resolvedProperty = nodeProperty; + + } else { + + this.propertyName = propertyName; + + } + + // select getter / setter + this.getValue = this.GetterByBindingType[ bindingType ]; + this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ]; + + } + + /** + * Unbinds the property. + */ + unbind() { + + this.node = null; + + // back to the prototype version of getValue / setValue + // note: avoiding to mutate the shape of 'this' via 'delete' + this.getValue = this._getValue_unbound; + this.setValue = this._setValue_unbound; + + } + +} + +PropertyBinding.Composite = Composite; + +PropertyBinding.prototype.BindingType = { + Direct: 0, + EntireArray: 1, + ArrayElement: 2, + HasFromToArray: 3 +}; + +PropertyBinding.prototype.Versioning = { + None: 0, + NeedsUpdate: 1, + MatrixWorldNeedsUpdate: 2 +}; + +PropertyBinding.prototype.GetterByBindingType = [ + + PropertyBinding.prototype._getValue_direct, + PropertyBinding.prototype._getValue_array, + PropertyBinding.prototype._getValue_arrayElement, + PropertyBinding.prototype._getValue_toArray, + +]; + +PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [ + + [ + // Direct + PropertyBinding.prototype._setValue_direct, + PropertyBinding.prototype._setValue_direct_setNeedsUpdate, + PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate, + + ], [ + + // EntireArray + + PropertyBinding.prototype._setValue_array, + PropertyBinding.prototype._setValue_array_setNeedsUpdate, + PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate, + + ], [ + + // ArrayElement + PropertyBinding.prototype._setValue_arrayElement, + PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate, + PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate, + + ], [ + + // HasToFromArray + PropertyBinding.prototype._setValue_fromArray, + PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate, + PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate, + + ] + +]; + +/** + * A group of objects that receives a shared animation state. + * + * Usage: + * + * - Add objects you would otherwise pass as 'root' to the + * constructor or the .clipAction method of AnimationMixer. + * - Instead pass this object as 'root'. + * - You can also add and remove objects later when the mixer is running. + * + * Note: + * + * - Objects of this class appear as one object to the mixer, + * so cache control of the individual objects must be done on the group. + * + * Limitation: + * + * - The animated properties must be compatible among the all objects in the group. + * - A single property can either be controlled through a target group or directly, but not both. + */ +class AnimationObjectGroup { + + /** + * Constructs a new animation group. + * + * @param {...Object3D} arguments - An arbitrary number of 3D objects that share the same animation state. + */ + constructor() { + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isAnimationObjectGroup = true; + + /** + * The UUID of the 3D object. + * + * @type {string} + * @readonly + */ + this.uuid = generateUUID(); + + // cached objects followed by the active ones + this._objects = Array.prototype.slice.call( arguments ); + + this.nCachedObjects_ = 0; // threshold + // note: read by PropertyBinding.Composite + + const indices = {}; + this._indicesByUUID = indices; // for bookkeeping + + for ( let i = 0, n = arguments.length; i !== n; ++ i ) { + + indices[ arguments[ i ].uuid ] = i; + + } + + this._paths = []; // inside: string + this._parsedPaths = []; // inside: { we don't care, here } + this._bindings = []; // inside: Array< PropertyBinding > + this._bindingsIndicesByPath = {}; // inside: indices in these arrays + + const scope = this; + + this.stats = { + + objects: { + get total() { + + return scope._objects.length; + + }, + get inUse() { + + return this.total - scope.nCachedObjects_; + + } + }, + get bindingsPerObject() { + + return scope._bindings.length; + + } + + }; + + } + + /** + * Adds an arbitrary number of objects to this animation group. + * + * @param {...Object3D} arguments - The 3D objects to add. + */ + add() { + + const objects = this._objects, + indicesByUUID = this._indicesByUUID, + paths = this._paths, + parsedPaths = this._parsedPaths, + bindings = this._bindings, + nBindings = bindings.length; + + let knownObject = undefined, + nObjects = objects.length, + nCachedObjects = this.nCachedObjects_; + + for ( let i = 0, n = arguments.length; i !== n; ++ i ) { + + const object = arguments[ i ], + uuid = object.uuid; + let index = indicesByUUID[ uuid ]; + + if ( index === undefined ) { + + // unknown object -> add it to the ACTIVE region + + index = nObjects ++; + indicesByUUID[ uuid ] = index; + objects.push( object ); + + // accounting is done, now do the same for all bindings + + for ( let j = 0, m = nBindings; j !== m; ++ j ) { + + bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) ); + + } + + } else if ( index < nCachedObjects ) { + + knownObject = objects[ index ]; + + // move existing object to the ACTIVE region + + const firstActiveIndex = -- nCachedObjects, + lastCachedObject = objects[ firstActiveIndex ]; + + indicesByUUID[ lastCachedObject.uuid ] = index; + objects[ index ] = lastCachedObject; + + indicesByUUID[ uuid ] = firstActiveIndex; + objects[ firstActiveIndex ] = object; + + // accounting is done, now do the same for all bindings + + for ( let j = 0, m = nBindings; j !== m; ++ j ) { + + const bindingsForPath = bindings[ j ], + lastCached = bindingsForPath[ firstActiveIndex ]; + + let binding = bindingsForPath[ index ]; + + bindingsForPath[ index ] = lastCached; + + if ( binding === undefined ) { + + // since we do not bother to create new bindings + // for objects that are cached, the binding may + // or may not exist + + binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ); + + } + + bindingsForPath[ firstActiveIndex ] = binding; + + } + + } else if ( objects[ index ] !== knownObject ) { + + error( 'AnimationObjectGroup: Different objects with the same UUID ' + + 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' ); + + } // else the object is already where we want it to be + + } // for arguments + + this.nCachedObjects_ = nCachedObjects; + + } + + /** + * Removes an arbitrary number of objects to this animation group + * + * @param {...Object3D} arguments - The 3D objects to remove. + */ + remove() { + + const objects = this._objects, + indicesByUUID = this._indicesByUUID, + bindings = this._bindings, + nBindings = bindings.length; + + let nCachedObjects = this.nCachedObjects_; + + for ( let i = 0, n = arguments.length; i !== n; ++ i ) { + + const object = arguments[ i ], + uuid = object.uuid, + index = indicesByUUID[ uuid ]; + + if ( index !== undefined && index >= nCachedObjects ) { + + // move existing object into the CACHED region + + const lastCachedIndex = nCachedObjects ++, + firstActiveObject = objects[ lastCachedIndex ]; + + indicesByUUID[ firstActiveObject.uuid ] = index; + objects[ index ] = firstActiveObject; + + indicesByUUID[ uuid ] = lastCachedIndex; + objects[ lastCachedIndex ] = object; + + // accounting is done, now do the same for all bindings + + for ( let j = 0, m = nBindings; j !== m; ++ j ) { + + const bindingsForPath = bindings[ j ], + firstActive = bindingsForPath[ lastCachedIndex ], + binding = bindingsForPath[ index ]; + + bindingsForPath[ index ] = firstActive; + bindingsForPath[ lastCachedIndex ] = binding; + + } + + } + + } // for arguments + + this.nCachedObjects_ = nCachedObjects; + + } + + /** + * Deallocates all memory resources for the passed 3D objects of this animation group. + * + * @param {...Object3D} arguments - The 3D objects to uncache. + */ + uncache() { + + const objects = this._objects, + indicesByUUID = this._indicesByUUID, + bindings = this._bindings, + nBindings = bindings.length; + + let nCachedObjects = this.nCachedObjects_, + nObjects = objects.length; + + for ( let i = 0, n = arguments.length; i !== n; ++ i ) { + + const object = arguments[ i ], + uuid = object.uuid, + index = indicesByUUID[ uuid ]; + + if ( index !== undefined ) { + + delete indicesByUUID[ uuid ]; + + if ( index < nCachedObjects ) { + + // object is cached, shrink the CACHED region + + const firstActiveIndex = -- nCachedObjects, + lastCachedObject = objects[ firstActiveIndex ], + lastIndex = -- nObjects, + lastObject = objects[ lastIndex ]; + + if ( index !== firstActiveIndex ) { + + // last cached object takes this object's place + + indicesByUUID[ lastCachedObject.uuid ] = index; + + } + + objects[ index ] = lastCachedObject; + + if ( firstActiveIndex !== lastIndex ) { + + // last object goes to the activated slot and pop + + indicesByUUID[ lastObject.uuid ] = firstActiveIndex; + + } + + objects[ firstActiveIndex ] = lastObject; + objects.pop(); + + // accounting is done, now do the same for all bindings + + for ( let j = 0, m = nBindings; j !== m; ++ j ) { + + const bindingsForPath = bindings[ j ], + lastCached = bindingsForPath[ firstActiveIndex ], + last = bindingsForPath[ lastIndex ]; + + bindingsForPath[ index ] = lastCached; + bindingsForPath[ firstActiveIndex ] = last; + bindingsForPath.pop(); + + } + + } else { + + // object is active, just swap with the last and pop + + const lastIndex = -- nObjects, + lastObject = objects[ lastIndex ]; + + if ( index !== lastIndex ) { + + indicesByUUID[ lastObject.uuid ] = index; + + } + + objects[ index ] = lastObject; + objects.pop(); + + // accounting is done, now do the same for all bindings + + for ( let j = 0, m = nBindings; j !== m; ++ j ) { + + const bindingsForPath = bindings[ j ]; + + bindingsForPath[ index ] = bindingsForPath[ lastIndex ]; + bindingsForPath.pop(); + + } + + } // cached or active + + } // if object is known + + } // for arguments + + this.nCachedObjects_ = nCachedObjects; + + } + + // Internal interface used by befriended PropertyBinding.Composite: + + subscribe_( path, parsedPath ) { + + // returns an array of bindings for the given path that is changed + // according to the contained objects in the group + + const indicesByPath = this._bindingsIndicesByPath; + let index = indicesByPath[ path ]; + const bindings = this._bindings; + + if ( index !== undefined ) return bindings[ index ]; + + const paths = this._paths, + parsedPaths = this._parsedPaths, + objects = this._objects, + nObjects = objects.length, + nCachedObjects = this.nCachedObjects_, + bindingsForPath = new Array( nObjects ); + + index = bindings.length; + + indicesByPath[ path ] = index; + + paths.push( path ); + parsedPaths.push( parsedPath ); + bindings.push( bindingsForPath ); + + for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) { + + const object = objects[ i ]; + bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath ); + + } + + return bindingsForPath; + + } + + unsubscribe_( path ) { + + // tells the group to forget about a property path and no longer + // update the array previously obtained with 'subscribe_' + + const indicesByPath = this._bindingsIndicesByPath, + index = indicesByPath[ path ]; + + if ( index !== undefined ) { + + const paths = this._paths, + parsedPaths = this._parsedPaths, + bindings = this._bindings, + lastBindingsIndex = bindings.length - 1, + lastBindings = bindings[ lastBindingsIndex ], + lastBindingsPath = paths[ lastBindingsIndex ]; + + indicesByPath[ lastBindingsPath ] = index; + + bindings[ index ] = lastBindings; + bindings.pop(); + + parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ]; + parsedPaths.pop(); + + paths[ index ] = paths[ lastBindingsIndex ]; + paths.pop(); + + } + + } + +} + +/** + * An instance of `AnimationAction` schedules the playback of an animation which is + * stored in {@link AnimationClip}. + */ +class AnimationAction { + + /** + * Constructs a new animation action. + * + * @param {AnimationMixer} mixer - The mixer that is controlled by this action. + * @param {AnimationClip} clip - The animation clip that holds the actual keyframes. + * @param {?Object3D} [localRoot=null] - The root object on which this action is performed. + * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode] - The blend mode. + */ + constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) { + + this._mixer = mixer; + this._clip = clip; + this._localRoot = localRoot; + + /** + * Defines how the animation is blended/combined when two or more animations + * are simultaneously played. + * + * @type {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} + */ + this.blendMode = blendMode; + + const tracks = clip.tracks, + nTracks = tracks.length, + interpolants = new Array( nTracks ); + + const interpolantSettings = { + endingStart: ZeroCurvatureEnding, + endingEnd: ZeroCurvatureEnding + }; + + for ( let i = 0; i !== nTracks; ++ i ) { + + const interpolant = tracks[ i ].createInterpolant( null ); + interpolants[ i ] = interpolant; + interpolant.settings = interpolantSettings; + + } + + this._interpolantSettings = interpolantSettings; + + this._interpolants = interpolants; // bound by the mixer + + // inside: PropertyMixer (managed by the mixer) + this._propertyBindings = new Array( nTracks ); + + this._cacheIndex = null; // for the memory manager + this._byClipCacheIndex = null; // for the memory manager + + this._timeScaleInterpolant = null; + this._restoreTimeScale = null; + this._weightInterpolant = null; + + /** + * The loop mode, set via {@link AnimationAction#setLoop}. + * + * @type {(LoopRepeat|LoopOnce|LoopPingPong)} + * @default LoopRepeat + */ + this.loop = LoopRepeat; + this._loopCount = -1; + + // global mixer time when the action is to be started + // it's set back to 'null' upon start of the action + this._startTime = null; + + /** + * The local time of this action (in seconds, starting with `0`). + * + * The value gets clamped or wrapped to `[0,clip.duration]` (according to the + * loop state). + * + * @type {number} + * @default Infinity + */ + this.time = 0; + + /** + * Scaling factor for the {@link AnimationAction#time}. A value of `0` causes the + * animation to pause. Negative values cause the animation to play backwards. + * + * @type {number} + * @default 1 + */ + this.timeScale = 1; + this._effectiveTimeScale = 1; + + /** + * The degree of influence of this action (in the interval `[0, 1]`). Values + * between `0` (no impact) and `1` (full impact) can be used to blend between + * several actions. + * + * @type {number} + * @default 1 + */ + this.weight = 1; + this._effectiveWeight = 1; + + /** + * The number of repetitions of the performed clip over the course of this action. + * Can be set via {@link AnimationAction#setLoop}. + * + * Setting this number has no effect if {@link AnimationAction#loop} is set to + * `THREE:LoopOnce`. + * + * @type {number} + * @default Infinity + */ + this.repetitions = Infinity; + + /** + * If set to `true`, the playback of the action is paused. + * + * @type {boolean} + * @default false + */ + this.paused = false; + + /** + * If set to `false`, the action is disabled so it has no impact. + * + * When the action is re-enabled, the animation continues from its current + * time (setting `enabled` to `false` doesn't reset the action). + * + * @type {boolean} + * @default true + */ + this.enabled = true; + + /** + * If set to true the animation will automatically be paused on its last frame. + * + * If set to false, {@link AnimationAction#enabled} will automatically be switched + * to `false` when the last loop of the action has finished, so that this action has + * no further impact. + * + * Note: This member has no impact if the action is interrupted (it + * has only an effect if its last loop has really finished). + * + * @type {boolean} + * @default false + */ + this.clampWhenFinished = false; + + /** + * Enables smooth interpolation without separate clips for start, loop and end. + * + * @type {boolean} + * @default true + */ + this.zeroSlopeAtStart = true; + + /** + * Enables smooth interpolation without separate clips for start, loop and end. + * + * @type {boolean} + * @default true + */ + this.zeroSlopeAtEnd = true; + + } + + /** + * Starts the playback of the animation. + * + * @return {AnimationAction} A reference to this animation action. + */ + play() { + + this._mixer._activateAction( this ); + + return this; + + } + + /** + * Stops the playback of the animation. + * + * @return {AnimationAction} A reference to this animation action. + */ + stop() { + + this._mixer._deactivateAction( this ); + + return this.reset(); + + } + + /** + * Resets the playback of the animation. + * + * @return {AnimationAction} A reference to this animation action. + */ + reset() { + + this.paused = false; + this.enabled = true; + + this.time = 0; // restart clip + this._loopCount = -1;// forget previous loops + this._startTime = null;// forget scheduling + + return this.stopFading().stopWarping(); + + } + + /** + * Returns `true` if the animation is running. + * + * @return {boolean} Whether the animation is running or not. + */ + isRunning() { + + return this.enabled && ! this.paused && this.timeScale !== 0 && + this._startTime === null && this._mixer._isActiveAction( this ); + + } + + /** + * Returns `true` when {@link AnimationAction#play} has been called. + * + * @return {boolean} Whether the animation is scheduled or not. + */ + isScheduled() { + + return this._mixer._isActiveAction( this ); + + } + + /** + * Defines the time when the animation should start. + * + * @param {number} time - The start time in seconds. + * @return {AnimationAction} A reference to this animation action. + */ + startAt( time ) { + + this._startTime = time; + + return this; + + } + + /** + * Configures the loop settings for this action. + * + * @param {(LoopRepeat|LoopOnce|LoopPingPong)} mode - The loop mode. + * @param {number} repetitions - The number of repetitions. + * @return {AnimationAction} A reference to this animation action. + */ + setLoop( mode, repetitions ) { + + this.loop = mode; + this.repetitions = repetitions; + + return this; + + } + + /** + * Sets the effective weight of this action. + * + * An action has no effect and thus an effective weight of zero when the + * action is disabled. + * + * @param {number} weight - The weight to set. + * @return {AnimationAction} A reference to this animation action. + */ + setEffectiveWeight( weight ) { + + this.weight = weight; + + // note: same logic as when updated at runtime + this._effectiveWeight = this.enabled ? weight : 0; + + return this.stopFading(); + + } + + /** + * Returns the effective weight of this action. + * + * @return {number} The effective weight. + */ + getEffectiveWeight() { + + return this._effectiveWeight; + + } + + /** + * Fades the animation in by increasing its weight gradually from `0` to `1`, + * within the passed time interval. + * + * @param {number} duration - The duration of the fade. + * @return {AnimationAction} A reference to this animation action. + */ + fadeIn( duration ) { + + return this._scheduleFading( duration, 0, 1 ); + + } + + /** + * Fades the animation out by decreasing its weight gradually from `1` to `0`, + * within the passed time interval. + * + * @param {number} duration - The duration of the fade. + * @return {AnimationAction} A reference to this animation action. + */ + fadeOut( duration ) { + + return this._scheduleFading( duration, 1, 0 ); + + } + + /** + * Causes this action to fade in and the given action to fade out, + * within the passed time interval. + * + * @param {AnimationAction} fadeOutAction - The animation action to fade out. + * @param {number} duration - The duration of the fade. + * @param {boolean} [warp=false] - Whether warping should be used or not. + * @return {AnimationAction} A reference to this animation action. + */ + crossFadeFrom( fadeOutAction, duration, warp = false ) { + + fadeOutAction.fadeOut( duration ); + this.fadeIn( duration ); + + if ( warp === true ) { + + const fadeInDuration = this._clip.duration, + fadeOutDuration = fadeOutAction._clip.duration, + + startEndRatio = fadeOutDuration / fadeInDuration, + endStartRatio = fadeInDuration / fadeOutDuration; + + + fadeOutAction._restoreTimeScale = fadeOutAction.timeScale; + this._restoreTimeScale = this.timeScale; + + fadeOutAction.warp( 1.0, startEndRatio, duration ); + this.warp( endStartRatio, 1.0, duration ); + + } + + return this; + + } + + /** + * Causes this action to fade out and the given action to fade in, + * within the passed time interval. + * + * @param {AnimationAction} fadeInAction - The animation action to fade in. + * @param {number} duration - The duration of the fade. + * @param {boolean} [warp=false] - Whether warping should be used or not. + * @return {AnimationAction} A reference to this animation action. + */ + crossFadeTo( fadeInAction, duration, warp = false ) { + + return fadeInAction.crossFadeFrom( this, duration, warp ); + + } + + /** + * Stops any fading which is applied to this action. + * + * @return {AnimationAction} A reference to this animation action. + */ + stopFading() { + + const weightInterpolant = this._weightInterpolant; + + if ( weightInterpolant !== null ) { + + this._weightInterpolant = null; + this._mixer._takeBackControlInterpolant( weightInterpolant ); + + } + + return this; + + } + + /** + * Sets the effective time scale of this action. + * + * An action has no effect and thus an effective time scale of zero when the + * action is paused. + * + * @param {number} timeScale - The time scale to set. + * @return {AnimationAction} A reference to this animation action. + */ + setEffectiveTimeScale( timeScale ) { + + this.timeScale = timeScale; + this._effectiveTimeScale = this.paused ? 0 : timeScale; + + return this.stopWarping(); + + } + + /** + * Returns the effective time scale of this action. + * + * @return {number} The effective time scale. + */ + getEffectiveTimeScale() { + + return this._effectiveTimeScale; + + } + + /** + * Sets the duration for a single loop of this action. + * + * @param {number} duration - The duration to set. + * @return {AnimationAction} A reference to this animation action. + */ + setDuration( duration ) { + + this.timeScale = this._clip.duration / duration; + + return this.stopWarping(); + + } + + /** + * Synchronizes this action with the passed other action. + * + * @param {AnimationAction} action - The action to sync with. + * @return {AnimationAction} A reference to this animation action. + */ + syncWith( action ) { + + this.time = action.time; + this.timeScale = action.timeScale; + + return this.stopWarping(); + + } + + /** + * Decelerates this animation's speed to `0` within the passed time interval. + * + * @param {number} duration - The duration. + * @return {AnimationAction} A reference to this animation action. + */ + halt( duration ) { + + return this.warp( this._effectiveTimeScale, 0, duration ); + + } + + /** + * Changes the playback speed, within the passed time interval, by modifying + * {@link AnimationAction#timeScale} gradually from `startTimeScale` to + * `endTimeScale`. + * + * @param {number} startTimeScale - The start time scale. + * @param {number} endTimeScale - The end time scale. + * @param {number} duration - The duration. + * @return {AnimationAction} A reference to this animation action. + */ + warp( startTimeScale, endTimeScale, duration ) { + + const mixer = this._mixer, + now = mixer.time, + timeScale = this.timeScale; + + let interpolant = this._timeScaleInterpolant; + + if ( interpolant === null ) { + + interpolant = mixer._lendControlInterpolant(); + this._timeScaleInterpolant = interpolant; + + } + + const times = interpolant.parameterPositions, + values = interpolant.sampleValues; + + times[ 0 ] = now; + times[ 1 ] = now + duration; + + values[ 0 ] = startTimeScale / timeScale; + values[ 1 ] = endTimeScale / timeScale; + + return this; + + } + + /** + * Stops any scheduled warping which is applied to this action. + * + * @return {AnimationAction} A reference to this animation action. + */ + stopWarping() { + + const timeScaleInterpolant = this._timeScaleInterpolant; + + if ( timeScaleInterpolant !== null ) { + + this._timeScaleInterpolant = null; + this._mixer._takeBackControlInterpolant( timeScaleInterpolant ); + + } + + this._restoreTimeScale = null; + + return this; + + } + + /** + * Returns the animation mixer of this animation action. + * + * @return {AnimationMixer} The animation mixer. + */ + getMixer() { + + return this._mixer; + + } + + /** + * Returns the animation clip of this animation action. + * + * @return {AnimationClip} The animation clip. + */ + getClip() { + + return this._clip; + + } + + /** + * Returns the root object of this animation action. + * + * @return {Object3D} The root object. + */ + getRoot() { + + return this._localRoot || this._mixer._root; + + } + + // Internal + + _update( time, deltaTime, timeDirection, accuIndex ) { + + // called by the mixer + + if ( ! this.enabled ) { + + // call ._updateWeight() to update ._effectiveWeight + + this._updateWeight( time ); + return; + + } + + const startTime = this._startTime; + + if ( startTime !== null ) { + + // check for scheduled start of action + + const timeRunning = ( time - startTime ) * timeDirection; + if ( timeRunning < 0 || timeDirection === 0 ) { + + deltaTime = 0; + + } else { + + + this._startTime = null; // unschedule + deltaTime = timeDirection * timeRunning; + + } + + } + + // apply time scale and advance time + + deltaTime *= this._updateTimeScale( time ); + const clipTime = this._updateTime( deltaTime ); + + // note: _updateTime may disable the action resulting in + // an effective weight of 0 + + const weight = this._updateWeight( time ); + + if ( weight > 0 ) { + + const interpolants = this._interpolants; + const propertyMixers = this._propertyBindings; + + switch ( this.blendMode ) { + + case AdditiveAnimationBlendMode: + + for ( let j = 0, m = interpolants.length; j !== m; ++ j ) { + + interpolants[ j ].evaluate( clipTime ); + propertyMixers[ j ].accumulateAdditive( weight ); + + } + + break; + + case NormalAnimationBlendMode: + default: + + for ( let j = 0, m = interpolants.length; j !== m; ++ j ) { + + interpolants[ j ].evaluate( clipTime ); + propertyMixers[ j ].accumulate( accuIndex, weight ); + + } + + } + + } + + } + + _updateWeight( time ) { + + let weight = 0; + + if ( this.enabled ) { + + weight = this.weight; + const interpolant = this._weightInterpolant; + + if ( interpolant !== null ) { + + const interpolantValue = interpolant.evaluate( time )[ 0 ]; + + weight *= interpolantValue; + + if ( time > interpolant.parameterPositions[ 1 ] ) { + + this.stopFading(); + + if ( interpolantValue === 0 ) { + + // faded out, disable + this.enabled = false; + + } + + } + + } + + } + + this._effectiveWeight = weight; + return weight; + + } + + _updateTimeScale( time ) { + + let timeScale = 0; + + if ( ! this.paused ) { + + timeScale = this.timeScale; + + const interpolant = this._timeScaleInterpolant; + + if ( interpolant !== null ) { + + const interpolantValue = interpolant.evaluate( time )[ 0 ]; + + timeScale *= interpolantValue; + + if ( time > interpolant.parameterPositions[ 1 ] ) { + + if ( timeScale === 0 ) { + + // motion has halted, pause + this.paused = true; + + } else { + + if ( this._restoreTimeScale !== null ) { + + timeScale = this._restoreTimeScale; + + } + + // warp done - apply final time scale + this.timeScale = timeScale; + + } + + this.stopWarping(); + + } + + } + + } + + this._effectiveTimeScale = timeScale; + return timeScale; + + } + + _updateTime( deltaTime ) { + + const duration = this._clip.duration; + const loop = this.loop; + + let time = this.time + deltaTime; + let loopCount = this._loopCount; + + const pingPong = ( loop === LoopPingPong ); + + if ( deltaTime === 0 ) { + + if ( loopCount === -1 ) return time; + + return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time; + + } + + if ( loop === LoopOnce ) { + + if ( loopCount === -1 ) { + + // just started + + this._loopCount = 0; + this._setEndings( true, true, false ); + + } + + handle_stop: { + + if ( time >= duration ) { + + time = duration; + + } else if ( time < 0 ) { + + time = 0; + + } else { + + this.time = time; + + break handle_stop; + + } + + if ( this.clampWhenFinished ) this.paused = true; + else this.enabled = false; + + this.time = time; + + this._mixer.dispatchEvent( { + type: 'finished', action: this, + direction: deltaTime < 0 ? -1 : 1 + } ); + + } + + } else { // repetitive Repeat or PingPong + + if ( loopCount === -1 ) { + + // just started + + if ( deltaTime >= 0 ) { + + loopCount = 0; + + this._setEndings( true, this.repetitions === 0, pingPong ); + + } else { + + // when looping in reverse direction, the initial + // transition through zero counts as a repetition, + // so leave loopCount at -1 + + this._setEndings( this.repetitions === 0, true, pingPong ); + + } + + } + + if ( time >= duration || time < 0 ) { + + // wrap around + + const loopDelta = Math.floor( time / duration ); // signed + time -= duration * loopDelta; + + loopCount += Math.abs( loopDelta ); + + const pending = this.repetitions - loopCount; + + if ( pending <= 0 ) { + + // have to stop (switch state, clamp time, fire event) + + if ( this.clampWhenFinished ) this.paused = true; + else this.enabled = false; + + time = deltaTime > 0 ? duration : 0; + + this.time = time; + + this._mixer.dispatchEvent( { + type: 'finished', action: this, + direction: deltaTime > 0 ? 1 : -1 + } ); + + } else { + + // keep running + + if ( pending === 1 ) { + + // entering the last round + + const atStart = deltaTime < 0; + this._setEndings( atStart, ! atStart, pingPong ); + + } else { + + this._setEndings( false, false, pingPong ); + + } + + this._loopCount = loopCount; + + this.time = time; + + this._mixer.dispatchEvent( { + type: 'loop', action: this, loopDelta: loopDelta + } ); + + } + + } else { + + this._loopCount = loopCount; + this.time = time; + + } + + if ( pingPong && ( loopCount & 1 ) === 1 ) { + + // invert time for the "pong round" + + return duration - time; + + } + + } + + return time; + + } + + _setEndings( atStart, atEnd, pingPong ) { + + const settings = this._interpolantSettings; + + if ( pingPong ) { + + settings.endingStart = ZeroSlopeEnding; + settings.endingEnd = ZeroSlopeEnding; + + } else { + + // assuming for LoopOnce atStart == atEnd == true + + if ( atStart ) { + + settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding; + + } else { + + settings.endingStart = WrapAroundEnding; + + } + + if ( atEnd ) { + + settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding; + + } else { + + settings.endingEnd = WrapAroundEnding; + + } + + } + + } + + _scheduleFading( duration, weightNow, weightThen ) { + + const mixer = this._mixer, now = mixer.time; + let interpolant = this._weightInterpolant; + + if ( interpolant === null ) { + + interpolant = mixer._lendControlInterpolant(); + this._weightInterpolant = interpolant; + + } + + const times = interpolant.parameterPositions, + values = interpolant.sampleValues; + + times[ 0 ] = now; + values[ 0 ] = weightNow; + times[ 1 ] = now + duration; + values[ 1 ] = weightThen; + + return this; + + } + +} + +const _controlInterpolantsResultBuffer = new Float32Array( 1 ); + +/** + * `AnimationMixer` is a player for animations on a particular object in + * the scene. When multiple objects in the scene are animated independently, + * one `AnimationMixer` may be used for each object. + */ +class AnimationMixer extends EventDispatcher { + + /** + * Constructs a new animation mixer. + * + * @param {Object3D} root - The object whose animations shall be played by this mixer. + */ + constructor( root ) { + + super(); + + this._root = root; + this._initMemoryManager(); + this._accuIndex = 0; + + /** + * The global mixer time (in seconds; starting with `0` on the mixer's creation). + * + * @type {number} + * @default 0 + */ + this.time = 0; + + /** + * A scaling factor for the global time. + * + * Note: Setting this member to `0` and later back to `1` is a + * possibility to pause/unpause all actions that are controlled by this + * mixer. + * + * @type {number} + * @default 1 + */ + this.timeScale = 1.0; + + if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) { + + __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) ); + + } + + } + + _bindAction( action, prototypeAction ) { + + const root = action._localRoot || this._root, + tracks = action._clip.tracks, + nTracks = tracks.length, + bindings = action._propertyBindings, + interpolants = action._interpolants, + rootUuid = root.uuid, + bindingsByRoot = this._bindingsByRootAndName; + + let bindingsByName = bindingsByRoot[ rootUuid ]; + + if ( bindingsByName === undefined ) { + + bindingsByName = {}; + bindingsByRoot[ rootUuid ] = bindingsByName; + + } + + for ( let i = 0; i !== nTracks; ++ i ) { + + const track = tracks[ i ], + trackName = track.name; + + let binding = bindingsByName[ trackName ]; + + if ( binding !== undefined ) { + + ++ binding.referenceCount; + bindings[ i ] = binding; + + } else { + + binding = bindings[ i ]; + + if ( binding !== undefined ) { + + // existing binding, make sure the cache knows + + if ( binding._cacheIndex === null ) { + + ++ binding.referenceCount; + this._addInactiveBinding( binding, rootUuid, trackName ); + + } + + continue; + + } + + const path = prototypeAction && prototypeAction. + _propertyBindings[ i ].binding.parsedPath; + + binding = new PropertyMixer( + PropertyBinding.create( root, trackName, path ), + track.ValueTypeName, track.getValueSize() ); + + ++ binding.referenceCount; + this._addInactiveBinding( binding, rootUuid, trackName ); + + bindings[ i ] = binding; + + } + + interpolants[ i ].resultBuffer = binding.buffer; + + } + + } + + _activateAction( action ) { + + if ( ! this._isActiveAction( action ) ) { + + if ( action._cacheIndex === null ) { + + // this action has been forgotten by the cache, but the user + // appears to be still using it -> rebind + + const rootUuid = ( action._localRoot || this._root ).uuid, + clipUuid = action._clip.uuid, + actionsForClip = this._actionsByClip[ clipUuid ]; + + this._bindAction( action, + actionsForClip && actionsForClip.knownActions[ 0 ] ); + + this._addInactiveAction( action, clipUuid, rootUuid ); + + } + + const bindings = action._propertyBindings; + + // increment reference counts / sort out state + for ( let i = 0, n = bindings.length; i !== n; ++ i ) { + + const binding = bindings[ i ]; + + if ( binding.useCount ++ === 0 ) { + + this._lendBinding( binding ); + binding.saveOriginalState(); + + } + + } + + this._lendAction( action ); + + } + + } + + _deactivateAction( action ) { + + if ( this._isActiveAction( action ) ) { + + const bindings = action._propertyBindings; + + // decrement reference counts / sort out state + for ( let i = 0, n = bindings.length; i !== n; ++ i ) { + + const binding = bindings[ i ]; + + if ( -- binding.useCount === 0 ) { + + binding.restoreOriginalState(); + this._takeBackBinding( binding ); + + } + + } + + this._takeBackAction( action ); + + } + + } + + // Memory manager + + _initMemoryManager() { + + this._actions = []; // 'nActiveActions' followed by inactive ones + this._nActiveActions = 0; + + this._actionsByClip = {}; + // inside: + // { + // knownActions: Array< AnimationAction > - used as prototypes + // actionByRoot: AnimationAction - lookup + // } + + + this._bindings = []; // 'nActiveBindings' followed by inactive ones + this._nActiveBindings = 0; + + this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer > + + + this._controlInterpolants = []; // same game as above + this._nActiveControlInterpolants = 0; + + const scope = this; + + this.stats = { + + actions: { + get total() { + + return scope._actions.length; + + }, + get inUse() { + + return scope._nActiveActions; + + } + }, + bindings: { + get total() { + + return scope._bindings.length; + + }, + get inUse() { + + return scope._nActiveBindings; + + } + }, + controlInterpolants: { + get total() { + + return scope._controlInterpolants.length; + + }, + get inUse() { + + return scope._nActiveControlInterpolants; + + } + } + + }; + + } + + // Memory management for AnimationAction objects + + _isActiveAction( action ) { + + const index = action._cacheIndex; + return index !== null && index < this._nActiveActions; + + } + + _addInactiveAction( action, clipUuid, rootUuid ) { + + const actions = this._actions, + actionsByClip = this._actionsByClip; + + let actionsForClip = actionsByClip[ clipUuid ]; + + if ( actionsForClip === undefined ) { + + actionsForClip = { + + knownActions: [ action ], + actionByRoot: {} + + }; + + action._byClipCacheIndex = 0; + + actionsByClip[ clipUuid ] = actionsForClip; + + } else { + + const knownActions = actionsForClip.knownActions; + + action._byClipCacheIndex = knownActions.length; + knownActions.push( action ); + + } + + action._cacheIndex = actions.length; + actions.push( action ); + + actionsForClip.actionByRoot[ rootUuid ] = action; + + } + + _removeInactiveAction( action ) { + + const actions = this._actions, + lastInactiveAction = actions[ actions.length - 1 ], + cacheIndex = action._cacheIndex; + + lastInactiveAction._cacheIndex = cacheIndex; + actions[ cacheIndex ] = lastInactiveAction; + actions.pop(); + + action._cacheIndex = null; + + + const clipUuid = action._clip.uuid, + actionsByClip = this._actionsByClip, + actionsForClip = actionsByClip[ clipUuid ], + knownActionsForClip = actionsForClip.knownActions, + + lastKnownAction = + knownActionsForClip[ knownActionsForClip.length - 1 ], + + byClipCacheIndex = action._byClipCacheIndex; + + lastKnownAction._byClipCacheIndex = byClipCacheIndex; + knownActionsForClip[ byClipCacheIndex ] = lastKnownAction; + knownActionsForClip.pop(); + + action._byClipCacheIndex = null; + + + const actionByRoot = actionsForClip.actionByRoot, + rootUuid = ( action._localRoot || this._root ).uuid; + + delete actionByRoot[ rootUuid ]; + + if ( knownActionsForClip.length === 0 ) { + + delete actionsByClip[ clipUuid ]; + + } + + this._removeInactiveBindingsForAction( action ); + + } + + _removeInactiveBindingsForAction( action ) { + + const bindings = action._propertyBindings; + + for ( let i = 0, n = bindings.length; i !== n; ++ i ) { + + const binding = bindings[ i ]; + + if ( -- binding.referenceCount === 0 ) { + + this._removeInactiveBinding( binding ); + + } + + } + + } + + _lendAction( action ) { + + // [ active actions | inactive actions ] + // [ active actions >| inactive actions ] + // s a + // <-swap-> + // a s + + const actions = this._actions, + prevIndex = action._cacheIndex, + + lastActiveIndex = this._nActiveActions ++, + + firstInactiveAction = actions[ lastActiveIndex ]; + + action._cacheIndex = lastActiveIndex; + actions[ lastActiveIndex ] = action; + + firstInactiveAction._cacheIndex = prevIndex; + actions[ prevIndex ] = firstInactiveAction; + + } + + _takeBackAction( action ) { + + // [ active actions | inactive actions ] + // [ active actions |< inactive actions ] + // a s + // <-swap-> + // s a + + const actions = this._actions, + prevIndex = action._cacheIndex, + + firstInactiveIndex = -- this._nActiveActions, + + lastActiveAction = actions[ firstInactiveIndex ]; + + action._cacheIndex = firstInactiveIndex; + actions[ firstInactiveIndex ] = action; + + lastActiveAction._cacheIndex = prevIndex; + actions[ prevIndex ] = lastActiveAction; + + } + + // Memory management for PropertyMixer objects + + _addInactiveBinding( binding, rootUuid, trackName ) { + + const bindingsByRoot = this._bindingsByRootAndName, + bindings = this._bindings; + + let bindingByName = bindingsByRoot[ rootUuid ]; + + if ( bindingByName === undefined ) { + + bindingByName = {}; + bindingsByRoot[ rootUuid ] = bindingByName; + + } + + bindingByName[ trackName ] = binding; + + binding._cacheIndex = bindings.length; + bindings.push( binding ); + + } + + _removeInactiveBinding( binding ) { + + const bindings = this._bindings, + propBinding = binding.binding, + rootUuid = propBinding.rootNode.uuid, + trackName = propBinding.path, + bindingsByRoot = this._bindingsByRootAndName, + bindingByName = bindingsByRoot[ rootUuid ], + + lastInactiveBinding = bindings[ bindings.length - 1 ], + cacheIndex = binding._cacheIndex; + + lastInactiveBinding._cacheIndex = cacheIndex; + bindings[ cacheIndex ] = lastInactiveBinding; + bindings.pop(); + + delete bindingByName[ trackName ]; + + if ( Object.keys( bindingByName ).length === 0 ) { + + delete bindingsByRoot[ rootUuid ]; + + } + + } + + _lendBinding( binding ) { + + const bindings = this._bindings, + prevIndex = binding._cacheIndex, + + lastActiveIndex = this._nActiveBindings ++, + + firstInactiveBinding = bindings[ lastActiveIndex ]; + + binding._cacheIndex = lastActiveIndex; + bindings[ lastActiveIndex ] = binding; + + firstInactiveBinding._cacheIndex = prevIndex; + bindings[ prevIndex ] = firstInactiveBinding; + + } + + _takeBackBinding( binding ) { + + const bindings = this._bindings, + prevIndex = binding._cacheIndex, + + firstInactiveIndex = -- this._nActiveBindings, + + lastActiveBinding = bindings[ firstInactiveIndex ]; + + binding._cacheIndex = firstInactiveIndex; + bindings[ firstInactiveIndex ] = binding; + + lastActiveBinding._cacheIndex = prevIndex; + bindings[ prevIndex ] = lastActiveBinding; + + } + + + // Memory management of Interpolants for weight and time scale + + _lendControlInterpolant() { + + const interpolants = this._controlInterpolants, + lastActiveIndex = this._nActiveControlInterpolants ++; + + let interpolant = interpolants[ lastActiveIndex ]; + + if ( interpolant === undefined ) { + + interpolant = new LinearInterpolant( + new Float32Array( 2 ), new Float32Array( 2 ), + 1, _controlInterpolantsResultBuffer ); + + interpolant.__cacheIndex = lastActiveIndex; + interpolants[ lastActiveIndex ] = interpolant; + + } + + return interpolant; + + } + + _takeBackControlInterpolant( interpolant ) { + + const interpolants = this._controlInterpolants, + prevIndex = interpolant.__cacheIndex, + + firstInactiveIndex = -- this._nActiveControlInterpolants, + + lastActiveInterpolant = interpolants[ firstInactiveIndex ]; + + interpolant.__cacheIndex = firstInactiveIndex; + interpolants[ firstInactiveIndex ] = interpolant; + + lastActiveInterpolant.__cacheIndex = prevIndex; + interpolants[ prevIndex ] = lastActiveInterpolant; + + } + + /** + * Returns an instance of {@link AnimationAction} for the passed clip. + * + * If an action fitting the clip and root parameters doesn't yet exist, it + * will be created by this method. Calling this method several times with the + * same clip and root parameters always returns the same action. + * + * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip. + * @param {Object3D} [optionalRoot] - An alternative root object. + * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode] - The blend mode. + * @return {?AnimationAction} The animation action. + */ + clipAction( clip, optionalRoot, blendMode ) { + + const root = optionalRoot || this._root, + rootUuid = root.uuid; + + let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip; + + const clipUuid = clipObject !== null ? clipObject.uuid : clip; + + const actionsForClip = this._actionsByClip[ clipUuid ]; + let prototypeAction = null; + + if ( blendMode === undefined ) { + + if ( clipObject !== null ) { + + blendMode = clipObject.blendMode; + + } else { + + blendMode = NormalAnimationBlendMode; + + } + + } + + if ( actionsForClip !== undefined ) { + + const existingAction = actionsForClip.actionByRoot[ rootUuid ]; + + if ( existingAction !== undefined && existingAction.blendMode === blendMode ) { + + return existingAction; + + } + + // we know the clip, so we don't have to parse all + // the bindings again but can just copy + prototypeAction = actionsForClip.knownActions[ 0 ]; + + // also, take the clip from the prototype action + if ( clipObject === null ) + clipObject = prototypeAction._clip; + + } + + // clip must be known when specified via string + if ( clipObject === null ) return null; + + // allocate all resources required to run it + const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode ); + + this._bindAction( newAction, prototypeAction ); + + // and make the action known to the memory manager + this._addInactiveAction( newAction, clipUuid, rootUuid ); + + return newAction; + + } + + /** + * Returns an existing animation action for the passed clip. + * + * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip. + * @param {Object3D} [optionalRoot] - An alternative root object. + * @return {?AnimationAction} The animation action. Returns `null` if no action was found. + */ + existingAction( clip, optionalRoot ) { + + const root = optionalRoot || this._root, + rootUuid = root.uuid, + + clipObject = typeof clip === 'string' ? + AnimationClip.findByName( root, clip ) : clip, + + clipUuid = clipObject ? clipObject.uuid : clip, + + actionsForClip = this._actionsByClip[ clipUuid ]; + + if ( actionsForClip !== undefined ) { + + return actionsForClip.actionByRoot[ rootUuid ] || null; + + } + + return null; + + } + + /** + * Deactivates all previously scheduled actions on this mixer. + * + * @return {AnimationMixer} A reference to this animation mixer. + */ + stopAllAction() { + + const actions = this._actions, + nActions = this._nActiveActions; + + for ( let i = nActions - 1; i >= 0; -- i ) { + + actions[ i ].stop(); + + } + + return this; + + } + + /** + * Advances the global mixer time and updates the animation. + * + * This is usually done in the render loop by passing the delta + * time from {@link Clock} or {@link Timer}. + * + * @param {number} deltaTime - The delta time in seconds. + * @return {AnimationMixer} A reference to this animation mixer. + */ + update( deltaTime ) { + + deltaTime *= this.timeScale; + + const actions = this._actions, + nActions = this._nActiveActions, + + time = this.time += deltaTime, + timeDirection = Math.sign( deltaTime ), + + accuIndex = this._accuIndex ^= 1; + + // run active actions + + for ( let i = 0; i !== nActions; ++ i ) { + + const action = actions[ i ]; + + action._update( time, deltaTime, timeDirection, accuIndex ); + + } + + // update scene graph + + const bindings = this._bindings, + nBindings = this._nActiveBindings; + + for ( let i = 0; i !== nBindings; ++ i ) { + + bindings[ i ].apply( accuIndex ); + + } + + return this; + + } + + /** + * Sets the global mixer to a specific time and updates the animation accordingly. + * + * This is useful when you need to jump to an exact time in an animation. The + * input parameter will be scaled by {@link AnimationMixer#timeScale} + * + * @param {number} time - The time to set in seconds. + * @return {AnimationMixer} A reference to this animation mixer. + */ + setTime( time ) { + + this.time = 0; // Zero out time attribute for AnimationMixer object; + for ( let i = 0; i < this._actions.length; i ++ ) { + + this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects. + + } + + return this.update( time ); // Update used to set exact time. Returns "this" AnimationMixer object. + + } + + /** + * Returns this mixer's root object. + * + * @return {Object3D} The mixer's root object. + */ + getRoot() { + + return this._root; + + } + + /** + * Deallocates all memory resources for a clip. Before using this method make + * sure to call {@link AnimationAction#stop} for all related actions. + * + * @param {AnimationClip} clip - The clip to uncache. + */ + uncacheClip( clip ) { + + const actions = this._actions, + clipUuid = clip.uuid, + actionsByClip = this._actionsByClip, + actionsForClip = actionsByClip[ clipUuid ]; + + if ( actionsForClip !== undefined ) { + + // note: just calling _removeInactiveAction would mess up the + // iteration state and also require updating the state we can + // just throw away + + const actionsToRemove = actionsForClip.knownActions; + + for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) { + + const action = actionsToRemove[ i ]; + + this._deactivateAction( action ); + + const cacheIndex = action._cacheIndex, + lastInactiveAction = actions[ actions.length - 1 ]; + + action._cacheIndex = null; + action._byClipCacheIndex = null; + + lastInactiveAction._cacheIndex = cacheIndex; + actions[ cacheIndex ] = lastInactiveAction; + actions.pop(); + + this._removeInactiveBindingsForAction( action ); + + } + + delete actionsByClip[ clipUuid ]; + + } + + } + + /** + * Deallocates all memory resources for a root object. Before using this + * method make sure to call {@link AnimationAction#stop} for all related + * actions or alternatively {@link AnimationMixer#stopAllAction} when the + * mixer operates on a single root. + * + * @param {Object3D} root - The root object to uncache. + */ + uncacheRoot( root ) { + + const rootUuid = root.uuid, + actionsByClip = this._actionsByClip; + + for ( const clipUuid in actionsByClip ) { + + const actionByRoot = actionsByClip[ clipUuid ].actionByRoot, + action = actionByRoot[ rootUuid ]; + + if ( action !== undefined ) { + + this._deactivateAction( action ); + this._removeInactiveAction( action ); + + } + + } + + const bindingsByRoot = this._bindingsByRootAndName, + bindingByName = bindingsByRoot[ rootUuid ]; + + if ( bindingByName !== undefined ) { + + for ( const trackName in bindingByName ) { + + const binding = bindingByName[ trackName ]; + binding.restoreOriginalState(); + this._removeInactiveBinding( binding ); + + } + + } + + } + + /** + * Deallocates all memory resources for an action. The action is identified by the + * given clip and an optional root object. Before using this method make + * sure to call {@link AnimationAction#stop} to deactivate the action. + * + * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip. + * @param {Object3D} [optionalRoot] - An alternative root object. + */ + uncacheAction( clip, optionalRoot ) { + + const action = this.existingAction( clip, optionalRoot ); + + if ( action !== null ) { + + this._deactivateAction( action ); + this._removeInactiveAction( action ); + + } + + } + +} + +/** + * Represents a 3D render target. + * + * @augments RenderTarget + */ +class RenderTarget3D extends RenderTarget { + + /** + * Constructs a new 3D render target. + * + * @param {number} [width=1] - The width of the render target. + * @param {number} [height=1] - The height of the render target. + * @param {number} [depth=1] - The height of the render target. + * @param {RenderTarget~Options} [options] - The configuration object. + */ + constructor( width = 1, height = 1, depth = 1, options = {} ) { + + super( width, height, options ); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isRenderTarget3D = true; + + this.depth = depth; + + // overwrite attachments with 3D textures + + for ( let i = 0; i < this.textures.length; i ++ ) { + + const texture = new Data3DTexture( null, width, height, depth ); + texture.isRenderTargetTexture = true; + texture.renderTarget = this; + + this.textures[ i ] = texture; + + } + + this._setTextureOptions( options ); + + } + +} + +/** + * Represents a uniform which is a global shader variable. They are passed to shader programs. + * + * When declaring a uniform of a {@link ShaderMaterial}, it is declared by value or by object. + * ```js + * uniforms: { + * time: { value: 1.0 }, + * resolution: new Uniform( new Vector2() ) + * }; + * ``` + * Since this class can only be used in context of {@link ShaderMaterial}, it is only supported + * in {@link WebGLRenderer}. + */ +class Uniform { + + /** + * Constructs a new uniform. + * + * @param {any} value - The uniform value. + */ + constructor( value ) { + + /** + * The uniform value. + * + * @type {any} + */ + this.value = value; + + } + + /** + * Returns a new uniform with copied values from this instance. + * If the value has a `clone()` method, the value is cloned as well. + * + * @return {Uniform} A clone of this instance. + */ + clone() { + + return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() ); + + } + +} + +let _id = 0; + +/** + * A class for managing multiple uniforms in a single group. The renderer will process + * such a definition as a single UBO. + * + * Since this class can only be used in context of {@link ShaderMaterial}, it is only supported + * in {@link WebGLRenderer}. + * + * @augments EventDispatcher + */ +class UniformsGroup extends EventDispatcher { + + /** + * Constructs a new uniforms group. + */ + constructor() { + + super(); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isUniformsGroup = true; + + /** + * The ID of the 3D object. + * + * @name UniformsGroup#id + * @type {number} + * @readonly + */ + Object.defineProperty( this, 'id', { value: _id ++ } ); + + /** + * The name of the uniforms group. + * + * @type {string} + */ + this.name = ''; + + /** + * The buffer usage. + * + * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} + * @default StaticDrawUsage + */ + this.usage = StaticDrawUsage; + + /** + * An array holding the uniforms. + * + * @type {Array} + */ + this.uniforms = []; + + } + + /** + * Adds the given uniform to this uniforms group. + * + * @param {Uniform} uniform - The uniform to add. + * @return {UniformsGroup} A reference to this uniforms group. + */ + add( uniform ) { + + this.uniforms.push( uniform ); + + return this; + + } + + /** + * Removes the given uniform from this uniforms group. + * + * @param {Uniform} uniform - The uniform to remove. + * @return {UniformsGroup} A reference to this uniforms group. + */ + remove( uniform ) { + + const index = this.uniforms.indexOf( uniform ); + + if ( index !== -1 ) this.uniforms.splice( index, 1 ); + + return this; + + } + + /** + * Sets the name of this uniforms group. + * + * @param {string} name - The name to set. + * @return {UniformsGroup} A reference to this uniforms group. + */ + setName( name ) { + + this.name = name; + + return this; + + } + + /** + * Sets the usage of this uniforms group. + * + * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set. + * @return {UniformsGroup} A reference to this uniforms group. + */ + setUsage( value ) { + + this.usage = value; + + return this; + + } + + /** + * Frees the GPU-related resources allocated by this instance. Call this + * method whenever this instance is no longer used in your app. + * + * @fires Texture#dispose + */ + dispose() { + + this.dispatchEvent( { type: 'dispose' } ); + + } + + /** + * Copies the values of the given uniforms group to this instance. + * + * @param {UniformsGroup} source - The uniforms group to copy. + * @return {UniformsGroup} A reference to this uniforms group. + */ + copy( source ) { + + this.name = source.name; + this.usage = source.usage; + + const uniformsSource = source.uniforms; + + this.uniforms.length = 0; + + for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) { + + const uniforms = Array.isArray( uniformsSource[ i ] ) ? uniformsSource[ i ] : [ uniformsSource[ i ] ]; + + for ( let j = 0; j < uniforms.length; j ++ ) { + + this.uniforms.push( uniforms[ j ].clone() ); + + } + + } + + return this; + + } + + /** + * Returns a new uniforms group with copied values from this instance. + * + * @return {UniformsGroup} A clone of this instance. + */ + clone() { + + return new this.constructor().copy( this ); + + } + +} + +/** + * An instanced version of an interleaved buffer. + * + * @augments InterleavedBuffer + */ +class InstancedInterleavedBuffer extends InterleavedBuffer { + + /** + * Constructs a new instanced interleaved buffer. + * + * @param {TypedArray} array - A typed array with a shared buffer storing attribute data. + * @param {number} stride - The number of typed-array elements per vertex. + * @param {number} [meshPerAttribute=1] - Defines how often a value of this interleaved buffer should be repeated. + */ + constructor( array, stride, meshPerAttribute = 1 ) { + + super( array, stride ); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isInstancedInterleavedBuffer = true; + + /** + * Defines how often a value of this buffer attribute should be repeated, + * see {@link InstancedBufferAttribute#meshPerAttribute}. + * + * @type {number} + * @default 1 + */ + this.meshPerAttribute = meshPerAttribute; + + } + + copy( source ) { + + super.copy( source ); + + this.meshPerAttribute = source.meshPerAttribute; + + return this; + + } + + clone( data ) { + + const ib = super.clone( data ); + + ib.meshPerAttribute = this.meshPerAttribute; + + return ib; + + } + + toJSON( data ) { + + const json = super.toJSON( data ); + + json.isInstancedInterleavedBuffer = true; + json.meshPerAttribute = this.meshPerAttribute; + + return json; + + } + +} + +/** + * An alternative version of a buffer attribute with more control over the VBO. + * + * The renderer does not construct a VBO for this kind of attribute. Instead, it uses + * whatever VBO is passed in constructor and can later be altered via the `buffer` property. + * + * The most common use case for this class is when some kind of GPGPU calculation interferes + * or even produces the VBOs in question. + * + * Notice that this class can only be used with {@link WebGLRenderer}. + */ +class GLBufferAttribute { + + /** + * Constructs a new GL buffer attribute. + * + * @param {WebGLBuffer} buffer - The native WebGL buffer. + * @param {number} type - The native data type (e.g. `gl.FLOAT`). + * @param {number} itemSize - The item size. + * @param {number} elementSize - The corresponding size (in bytes) for the given `type` parameter. + * @param {number} count - The expected number of vertices in VBO. + * @param {boolean} [normalized=false] - Whether the data are normalized or not. + */ + constructor( buffer, type, itemSize, elementSize, count, normalized = false ) { + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isGLBufferAttribute = true; + + /** + * The name of the buffer attribute. + * + * @type {string} + */ + this.name = ''; + + /** + * The native WebGL buffer. + * + * @type {WebGLBuffer} + */ + this.buffer = buffer; + + /** + * The native data type. + * + * @type {number} + */ + this.type = type; + + /** + * The item size, see {@link BufferAttribute#itemSize}. + * + * @type {number} + */ + this.itemSize = itemSize; + + /** + * The corresponding size (in bytes) for the given `type` parameter. + * + * @type {number} + */ + this.elementSize = elementSize; + + /** + * The expected number of vertices in VBO. + * + * @type {number} + */ + this.count = count; + + /** + * Applies to integer data only. Indicates how the underlying data in the buffer maps to + * the values in the GLSL code. For instance, if `buffer` contains data of `gl.UNSIGNED_SHORT`, + * and `normalized` is `true`, the values `0 - +65535` in the buffer data will be mapped to + * `0.0f - +1.0f` in the GLSL attribute. If `normalized` is `false`, the values will be converted + * to floats unmodified, i.e. `65535` becomes `65535.0f`. + * + * @type {boolean} + */ + this.normalized = normalized; + + /** + * A version number, incremented every time the `needsUpdate` is set to `true`. + * + * @type {number} + */ + this.version = 0; + + } + + /** + * Flag to indicate that this attribute has changed and should be re-sent to + * the GPU. Set this to `true` when you modify the value of the array. + * + * @type {number} + * @default false + * @param {boolean} value + */ + set needsUpdate( value ) { + + if ( value === true ) this.version ++; + + } + + /** + * Sets the given native WebGL buffer. + * + * @param {WebGLBuffer} buffer - The buffer to set. + * @return {BufferAttribute} A reference to this instance. + */ + setBuffer( buffer ) { + + this.buffer = buffer; + + return this; + + } + + /** + * Sets the given native data type and element size. + * + * @param {number} type - The native data type (e.g. `gl.FLOAT`). + * @param {number} elementSize - The corresponding size (in bytes) for the given `type` parameter. + * @return {BufferAttribute} A reference to this instance. + */ + setType( type, elementSize ) { + + this.type = type; + this.elementSize = elementSize; + + return this; + + } + + /** + * Sets the item size. + * + * @param {number} itemSize - The item size. + * @return {BufferAttribute} A reference to this instance. + */ + setItemSize( itemSize ) { + + this.itemSize = itemSize; + + return this; + + } + + /** + * Sets the count (the expected number of vertices in VBO). + * + * @param {number} count - The count. + * @return {BufferAttribute} A reference to this instance. + */ + setCount( count ) { + + this.count = count; + + return this; + + } + +} + +const _matrix = /*@__PURE__*/ new Matrix4(); + +/** + * This class is designed to assist with raycasting. Raycasting is used for + * mouse picking (working out what objects in the 3d space the mouse is over) + * amongst other things. + */ +class Raycaster { + + /** + * Constructs a new raycaster. + * + * @param {Vector3} origin - The origin vector where the ray casts from. + * @param {Vector3} direction - The (normalized) direction vector that gives direction to the ray. + * @param {number} [near=0] - All results returned are further away than near. Near can't be negative. + * @param {number} [far=Infinity] - All results returned are closer than far. Far can't be lower than near. + */ + constructor( origin, direction, near = 0, far = Infinity ) { + + /** + * The ray used for raycasting. + * + * @type {Ray} + */ + this.ray = new Ray( origin, direction ); + + /** + * All results returned are further away than near. Near can't be negative. + * + * @type {number} + * @default 0 + */ + this.near = near; + + /** + * All results returned are closer than far. Far can't be lower than near. + * + * @type {number} + * @default Infinity + */ + this.far = far; + + /** + * The camera to use when raycasting against view-dependent objects such as + * billboarded objects like sprites. This field can be set manually or + * is set when calling `setFromCamera()`. + * + * @type {?Camera} + * @default null + */ + this.camera = null; + + /** + * Allows to selectively ignore 3D objects when performing intersection tests. + * The following code example ensures that only 3D objects on layer `1` will be + * honored by raycaster. + * ```js + * raycaster.layers.set( 1 ); + * object.layers.enable( 1 ); + * ``` + * + * @type {Layers} + */ + this.layers = new Layers(); + + + /** + * A parameter object that configures the raycasting. It has the structure: + * + * ``` + * { + * Mesh: {}, + * Line: { threshold: 1 }, + * LOD: {}, + * Points: { threshold: 1 }, + * Sprite: {} + * } + * ``` + * Where `threshold` is the precision of the raycaster when intersecting objects, in world units. + * + * @type {Object} + */ + this.params = { + Mesh: {}, + Line: { threshold: 1 }, + LOD: {}, + Points: { threshold: 1 }, + Sprite: {} + }; + + } + + /** + * Updates the ray with a new origin and direction by copying the values from the arguments. + * + * @param {Vector3} origin - The origin vector where the ray casts from. + * @param {Vector3} direction - The (normalized) direction vector that gives direction to the ray. + */ + set( origin, direction ) { + + // direction is assumed to be normalized (for accurate distance calculations) + + this.ray.set( origin, direction ); + + } + + /** + * Uses the given coordinates and camera to compute a new origin and direction for the internal ray. + * + * @param {Vector2} coords - 2D coordinates of the mouse, in normalized device coordinates (NDC). + * X and Y components should be between `-1` and `1`. + * @param {Camera} camera - The camera from which the ray should originate. + */ + setFromCamera( coords, camera ) { + + if ( camera.isPerspectiveCamera ) { + + this.ray.origin.setFromMatrixPosition( camera.matrixWorld ); + this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize(); + this.camera = camera; + + } else if ( camera.isOrthographicCamera ) { + + this.ray.origin.set( coords.x, coords.y, camera.projectionMatrix.elements[ 14 ] ).unproject( camera ); // set origin in plane of camera + this.ray.direction.set( 0, 0, -1 ).transformDirection( camera.matrixWorld ); + this.camera = camera; + + } else { + + error( 'Raycaster: Unsupported camera type: ' + camera.type ); + + } + + } + + /** + * Uses the given WebXR controller to compute a new origin and direction for the internal ray. + * + * @param {WebXRController} controller - The controller to copy the position and direction from. + * @return {Raycaster} A reference to this raycaster. + */ + setFromXRController( controller ) { + + _matrix.identity().extractRotation( controller.matrixWorld ); + + this.ray.origin.setFromMatrixPosition( controller.matrixWorld ); + this.ray.direction.set( 0, 0, -1 ).applyMatrix4( _matrix ); + + return this; + + } + + /** + * The intersection point of a raycaster intersection test. + * @typedef {Object} Raycaster~Intersection + * @property {number} distance - The distance from the ray's origin to the intersection point. + * @property {number} distanceToRay - Some 3D objects e.g. {@link Points} provide the distance of the + * intersection to the nearest point on the ray. For other objects it will be `undefined`. + * @property {Vector3} point - The intersection point, in world coordinates. + * @property {Object} face - The face that has been intersected. + * @property {number} faceIndex - The face index. + * @property {Object3D} object - The 3D object that has been intersected. + * @property {Vector2} uv - U,V coordinates at point of intersection. + * @property {Vector2} uv1 - Second set of U,V coordinates at point of intersection. + * @property {Vector3} normal - Interpolated normal vector at point of intersection. + * @property {number} instanceId - The index number of the instance where the ray + * intersects the {@link InstancedMesh}. + */ + + /** + * Checks all intersection between the ray and the object with or without the + * descendants. Intersections are returned sorted by distance, closest first. + * + * `Raycaster` delegates to the `raycast()` method of the passed 3D object, when + * evaluating whether the ray intersects the object or not. This allows meshes to respond + * differently to ray casting than lines or points. + * + * Note that for meshes, faces must be pointed towards the origin of the ray in order + * to be detected; intersections of the ray passing through the back of a face will not + * be detected. To raycast against both faces of an object, you'll want to set {@link Material#side} + * to `THREE.DoubleSide`. + * + * Note that a ray hitting a triangle mesh exactly along an edge shared by two faces may be + * reported by both faces, resulting in two coincident intersections (identical point and + * distance) in the returned array. + * + * @param {Object3D} object - The 3D object to check for intersection with the ray. + * @param {boolean} [recursive=true] - If set to `true`, it also checks all descendants. + * Otherwise it only checks intersection with the object. + * @param {Array} [intersects=[]] The target array that holds the result of the method. + * @return {Array} An array holding the intersection points. + */ + intersectObject( object, recursive = true, intersects = [] ) { + + intersect( object, this, intersects, recursive ); + + intersects.sort( ascSort ); + + return intersects; + + } + + /** + * Checks all intersection between the ray and the objects with or without + * the descendants. Intersections are returned sorted by distance, closest first. + * + * @param {Array} objects - The 3D objects to check for intersection with the ray. + * @param {boolean} [recursive=true] - If set to `true`, it also checks all descendants. + * Otherwise it only checks intersection with the object. + * @param {Array} [intersects=[]] The target array that holds the result of the method. + * @return {Array} An array holding the intersection points. + */ + intersectObjects( objects, recursive = true, intersects = [] ) { + + for ( let i = 0, l = objects.length; i < l; i ++ ) { + + intersect( objects[ i ], this, intersects, recursive ); + + } + + intersects.sort( ascSort ); + + return intersects; + + } + +} + +function ascSort( a, b ) { + + return a.distance - b.distance; + +} + +function intersect( object, raycaster, intersects, recursive ) { + + let propagate = true; + + if ( object.layers.test( raycaster.layers ) ) { + + const result = object.raycast( raycaster, intersects ); + + if ( result === false ) propagate = false; + + } + + if ( propagate === true && recursive === true ) { + + const children = object.children; + + for ( let i = 0, l = children.length; i < l; i ++ ) { + + intersect( children[ i ], raycaster, intersects, true ); + + } + + } + +} + +/** + * Class for keeping track of time. + * + * @deprecated since r183. + */ +class Clock { + + /** + * Constructs a new clock. + * + * @deprecated since 183. + * @param {boolean} [autoStart=true] - Whether to automatically start the clock when + * `getDelta()` is called for the first time. + */ + constructor( autoStart = true ) { + + /** + * If set to `true`, the clock starts automatically when `getDelta()` is called + * for the first time. + * + * @type {boolean} + * @default true + */ + this.autoStart = autoStart; + + /** + * Holds the time at which the clock's `start()` method was last called. + * + * @type {number} + * @default 0 + */ + this.startTime = 0; + + /** + * Holds the time at which the clock's `start()`, `getElapsedTime()` or + * `getDelta()` methods were last called. + * + * @type {number} + * @default 0 + */ + this.oldTime = 0; + + /** + * Keeps track of the total time that the clock has been running. + * + * @type {number} + * @default 0 + */ + this.elapsedTime = 0; + + /** + * Whether the clock is running or not. + * + * @type {boolean} + * @default true + */ + this.running = false; + + warn( 'Clock: This module has been deprecated. Please use THREE.Timer instead.' ); // @deprecated, r183 + + } + + /** + * Starts the clock. When `autoStart` is set to `true`, the method is automatically + * called by the class. + */ + start() { + + this.startTime = performance.now(); + + this.oldTime = this.startTime; + this.elapsedTime = 0; + this.running = true; + + } + + /** + * Stops the clock. + */ + stop() { + + this.getElapsedTime(); + this.running = false; + this.autoStart = false; + + } + + /** + * Returns the elapsed time in seconds. + * + * @return {number} The elapsed time. + */ + getElapsedTime() { + + this.getDelta(); + return this.elapsedTime; + + } + + /** + * Returns the delta time in seconds. + * + * @return {number} The delta time. + */ + getDelta() { + + let diff = 0; + + if ( this.autoStart && ! this.running ) { + + this.start(); + return 0; + + } + + if ( this.running ) { + + const newTime = performance.now(); + + diff = ( newTime - this.oldTime ) / 1000; + this.oldTime = newTime; + + this.elapsedTime += diff; + + } + + return diff; + + } + +} + +/** + * This class can be used to represent points in 3D space as + * [Spherical coordinates](https://en.wikipedia.org/wiki/Spherical_coordinate_system). + */ +class Spherical { + + /** + * Constructs a new spherical. + * + * @param {number} [radius=1] - The radius, or the Euclidean distance (straight-line distance) from the point to the origin. + * @param {number} [phi=0] - The polar angle in radians from the y (up) axis. + * @param {number} [theta=0] - The equator/azimuthal angle in radians around the y (up) axis. + */ + constructor( radius = 1, phi = 0, theta = 0 ) { + + /** + * The radius, or the Euclidean distance (straight-line distance) from the point to the origin. + * + * @type {number} + * @default 1 + */ + this.radius = radius; + + /** + * The polar angle in radians from the y (up) axis. + * + * @type {number} + * @default 0 + */ + this.phi = phi; + + /** + * The equator/azimuthal angle in radians around the y (up) axis. + * + * @type {number} + * @default 0 + */ + this.theta = theta; + + } + + /** + * Sets the spherical components by copying the given values. + * + * @param {number} radius - The radius. + * @param {number} phi - The polar angle. + * @param {number} theta - The azimuthal angle. + * @return {Spherical} A reference to this spherical. + */ + set( radius, phi, theta ) { + + this.radius = radius; + this.phi = phi; + this.theta = theta; + + return this; + + } + + /** + * Copies the values of the given spherical to this instance. + * + * @param {Spherical} other - The spherical to copy. + * @return {Spherical} A reference to this spherical. + */ + copy( other ) { + + this.radius = other.radius; + this.phi = other.phi; + this.theta = other.theta; + + return this; + + } + + /** + * Restricts the polar angle [page:.phi phi] to be between `0.000001` and pi - + * `0.000001`. + * + * @return {Spherical} A reference to this spherical. + */ + makeSafe() { + + const EPS = 0.000001; + this.phi = clamp( this.phi, EPS, Math.PI - EPS ); + + return this; + + } + + /** + * Sets the spherical components from the given vector which is assumed to hold + * Cartesian coordinates. + * + * @param {Vector3} v - The vector to set. + * @return {Spherical} A reference to this spherical. + */ + setFromVector3( v ) { + + return this.setFromCartesianCoords( v.x, v.y, v.z ); + + } + + /** + * Sets the spherical components from the given Cartesian coordinates. + * + * @param {number} x - The x value. + * @param {number} y - The y value. + * @param {number} z - The z value. + * @return {Spherical} A reference to this spherical. + */ + setFromCartesianCoords( x, y, z ) { + + this.radius = Math.sqrt( x * x + y * y + z * z ); + + if ( this.radius === 0 ) { + + this.theta = 0; + this.phi = 0; + + } else { + + this.theta = Math.atan2( x, z ); + this.phi = Math.acos( clamp( y / this.radius, -1, 1 ) ); + + } + + return this; + + } + + /** + * Returns a new spherical with copied values from this instance. + * + * @return {Spherical} A clone of this instance. + */ + clone() { + + return new this.constructor().copy( this ); + + } + +} + +/** + * This class can be used to represent points in 3D space as + * [Cylindrical coordinates](https://en.wikipedia.org/wiki/Cylindrical_coordinate_system). + */ +class Cylindrical { + + /** + * Constructs a new cylindrical. + * + * @param {number} [radius=1] - The distance from the origin to a point in the x-z plane. + * @param {number} [theta=0] - A counterclockwise angle in the x-z plane measured in radians from the positive z-axis. + * @param {number} [y=0] - The height above the x-z plane. + */ + constructor( radius = 1, theta = 0, y = 0 ) { + + /** + * The distance from the origin to a point in the x-z plane. + * + * @type {number} + * @default 1 + */ + this.radius = radius; + + /** + * A counterclockwise angle in the x-z plane measured in radians from the positive z-axis. + * + * @type {number} + * @default 0 + */ + this.theta = theta; + + /** + * The height above the x-z plane. + * + * @type {number} + * @default 0 + */ + this.y = y; + + } + + /** + * Sets the cylindrical components by copying the given values. + * + * @param {number} radius - The radius. + * @param {number} theta - The theta angle. + * @param {number} y - The height value. + * @return {Cylindrical} A reference to this cylindrical. + */ + set( radius, theta, y ) { + + this.radius = radius; + this.theta = theta; + this.y = y; + + return this; + + } + + /** + * Copies the values of the given cylindrical to this instance. + * + * @param {Cylindrical} other - The cylindrical to copy. + * @return {Cylindrical} A reference to this cylindrical. + */ + copy( other ) { + + this.radius = other.radius; + this.theta = other.theta; + this.y = other.y; + + return this; + + } + + /** + * Sets the cylindrical components from the given vector which is assumed to hold + * Cartesian coordinates. + * + * @param {Vector3} v - The vector to set. + * @return {Cylindrical} A reference to this cylindrical. + */ + setFromVector3( v ) { + + return this.setFromCartesianCoords( v.x, v.y, v.z ); + + } + + /** + * Sets the cylindrical components from the given Cartesian coordinates. + * + * @param {number} x - The x value. + * @param {number} y - The x value. + * @param {number} z - The x value. + * @return {Cylindrical} A reference to this cylindrical. + */ + setFromCartesianCoords( x, y, z ) { + + this.radius = Math.sqrt( x * x + z * z ); + this.theta = Math.atan2( x, z ); + this.y = y; + + return this; + + } + + /** + * Returns a new cylindrical with copied values from this instance. + * + * @return {Cylindrical} A clone of this instance. + */ + clone() { + + return new this.constructor().copy( this ); + + } + +} + +/** + * Represents a 2x2 matrix. + * + * A Note on Row-Major and Column-Major Ordering: + * + * The constructor and {@link Matrix2#set} method take arguments in + * [row-major](https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order) + * order, while internally they are stored in the {@link Matrix2#elements} array in column-major order. + * This means that calling: + * ```js + * const m = new THREE.Matrix2(); + * m.set( 11, 12, + * 21, 22 ); + * ``` + * will result in the elements array containing: + * ```js + * m.elements = [ 11, 21, + * 12, 22 ]; + * ``` + * and internally all calculations are performed using column-major ordering. + * However, as the actual ordering makes no difference mathematically and + * most people are used to thinking about matrices in row-major order, the + * three.js documentation shows matrices in row-major order. Just bear in + * mind that if you are reading the source code, you'll have to take the + * transpose of any matrices outlined here to make sense of the calculations. + */ +class Matrix2 { + + static { + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + Matrix2.prototype.isMatrix2 = true; + + } + + /** + * Constructs a new 2x2 matrix. The arguments are supposed to be + * in row-major order. If no arguments are provided, the constructor + * initializes the matrix as an identity matrix. + * + * @param {number} [n11] - 1-1 matrix element. + * @param {number} [n12] - 1-2 matrix element. + * @param {number} [n21] - 2-1 matrix element. + * @param {number} [n22] - 2-2 matrix element. + */ + constructor( n11, n12, n21, n22 ) { + + /** + * A column-major list of matrix values. + * + * @type {Array} + */ + this.elements = [ + 1, 0, + 0, 1, + ]; + + if ( n11 !== undefined ) { + + this.set( n11, n12, n21, n22 ); + + } + + } + + /** + * Sets this matrix to the 2x2 identity matrix. + * + * @return {Matrix2} A reference to this matrix. + */ + identity() { + + this.set( + 1, 0, + 0, 1, + ); + + return this; + + } + + /** + * Sets the elements of the matrix from the given array. + * + * @param {Array} array - The matrix elements in column-major order. + * @param {number} [offset=0] - Index of the first element in the array. + * @return {Matrix2} A reference to this matrix. + */ + fromArray( array, offset = 0 ) { + + for ( let i = 0; i < 4; i ++ ) { + + this.elements[ i ] = array[ i + offset ]; + + } + + return this; + + } + + /** + * Sets the elements of the matrix.The arguments are supposed to be + * in row-major order. + * + * @param {number} n11 - 1-1 matrix element. + * @param {number} n12 - 1-2 matrix element. + * @param {number} n21 - 2-1 matrix element. + * @param {number} n22 - 2-2 matrix element. + * @return {Matrix2} A reference to this matrix. + */ + set( n11, n12, n21, n22 ) { + + const te = this.elements; + + te[ 0 ] = n11; te[ 2 ] = n12; + te[ 1 ] = n21; te[ 3 ] = n22; + + return this; + + } + +} + +const _vector$4 = /*@__PURE__*/ new Vector2(); + +/** + * Represents an axis-aligned bounding box (AABB) in 2D space. + */ +class Box2 { + + /** + * Constructs a new bounding box. + * + * @param {Vector2} [min=(Infinity,Infinity)] - A vector representing the lower boundary of the box. + * @param {Vector2} [max=(-Infinity,-Infinity)] - A vector representing the upper boundary of the box. + */ + constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) { + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isBox2 = true; + + /** + * The lower boundary of the box. + * + * @type {Vector2} + */ + this.min = min; + + /** + * The upper boundary of the box. + * + * @type {Vector2} + */ + this.max = max; + + } + + /** + * Sets the lower and upper boundaries of this box. + * Please note that this method only copies the values from the given objects. + * + * @param {Vector2} min - The lower boundary of the box. + * @param {Vector2} max - The upper boundary of the box. + * @return {Box2} A reference to this bounding box. + */ + set( min, max ) { + + this.min.copy( min ); + this.max.copy( max ); + + return this; + + } + + /** + * Sets the upper and lower bounds of this box so it encloses the position data + * in the given array. + * + * @param {Array} points - An array holding 2D position data as instances of {@link Vector2}. + * @return {Box2} A reference to this bounding box. + */ + setFromPoints( points ) { + + this.makeEmpty(); + + for ( let i = 0, il = points.length; i < il; i ++ ) { + + this.expandByPoint( points[ i ] ); + + } + + return this; + + } + + /** + * Centers this box on the given center vector and sets this box's width, height and + * depth to the given size values. + * + * @param {Vector2} center - The center of the box. + * @param {Vector2} size - The x and y dimensions of the box. + * @return {Box2} A reference to this bounding box. + */ + setFromCenterAndSize( center, size ) { + + const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 ); + this.min.copy( center ).sub( halfSize ); + this.max.copy( center ).add( halfSize ); + + return this; + + } + + /** + * Returns a new box with copied values from this instance. + * + * @return {Box2} A clone of this instance. + */ + clone() { + + return new this.constructor().copy( this ); + + } + + /** + * Copies the values of the given box to this instance. + * + * @param {Box2} box - The box to copy. + * @return {Box2} A reference to this bounding box. + */ + copy( box ) { + + this.min.copy( box.min ); + this.max.copy( box.max ); + + return this; + + } + + /** + * Makes this box empty which means in encloses a zero space in 2D. + * + * @return {Box2} A reference to this bounding box. + */ + makeEmpty() { + + this.min.x = this.min.y = + Infinity; + this.max.x = this.max.y = - Infinity; + + return this; + + } + + /** + * Returns true if this box includes zero points within its bounds. + * Note that a box with equal lower and upper bounds still includes one + * point, the one both bounds share. + * + * @return {boolean} Whether this box is empty or not. + */ + isEmpty() { + + // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes + + return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ); + + } + + /** + * Returns the center point of this box. + * + * @param {Vector2} target - The target vector that is used to store the method's result. + * @return {Vector2} The center point. + */ + getCenter( target ) { + + return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 ); + + } + + /** + * Returns the dimensions of this box. + * + * @param {Vector2} target - The target vector that is used to store the method's result. + * @return {Vector2} The size. + */ + getSize( target ) { + + return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min ); + + } + + /** + * Expands the boundaries of this box to include the given point. + * + * @param {Vector2} point - The point that should be included by the bounding box. + * @return {Box2} A reference to this bounding box. + */ + expandByPoint( point ) { + + this.min.min( point ); + this.max.max( point ); + + return this; + + } + + /** + * Expands this box equilaterally by the given vector. The width of this + * box will be expanded by the x component of the vector in both + * directions. The height of this box will be expanded by the y component of + * the vector in both directions. + * + * @param {Vector2} vector - The vector that should expand the bounding box. + * @return {Box2} A reference to this bounding box. + */ + expandByVector( vector ) { + + this.min.sub( vector ); + this.max.add( vector ); + + return this; + + } + + /** + * Expands each dimension of the box by the given scalar. If negative, the + * dimensions of the box will be contracted. + * + * @param {number} scalar - The scalar value that should expand the bounding box. + * @return {Box2} A reference to this bounding box. + */ + expandByScalar( scalar ) { + + this.min.addScalar( - scalar ); + this.max.addScalar( scalar ); + + return this; + + } + + /** + * Returns `true` if the given point lies within or on the boundaries of this box. + * + * @param {Vector2} point - The point to test. + * @return {boolean} Whether the bounding box contains the given point or not. + */ + containsPoint( point ) { + + return point.x >= this.min.x && point.x <= this.max.x && + point.y >= this.min.y && point.y <= this.max.y; + + } + + /** + * Returns `true` if this bounding box includes the entirety of the given bounding box. + * If this box and the given one are identical, this function also returns `true`. + * + * @param {Box2} box - The bounding box to test. + * @return {boolean} Whether the bounding box contains the given bounding box or not. + */ + containsBox( box ) { + + return this.min.x <= box.min.x && box.max.x <= this.max.x && + this.min.y <= box.min.y && box.max.y <= this.max.y; + + } + + /** + * Returns a point as a proportion of this box's width and height. + * + * @param {Vector2} point - A point in 2D space. + * @param {Vector2} target - The target vector that is used to store the method's result. + * @return {Vector2} A point as a proportion of this box's width and height. + */ + getParameter( point, target ) { + + // This can potentially have a divide by zero if the box + // has a size dimension of 0. + + return target.set( + ( point.x - this.min.x ) / ( this.max.x - this.min.x ), + ( point.y - this.min.y ) / ( this.max.y - this.min.y ) + ); + + } + + /** + * Returns `true` if the given bounding box intersects with this bounding box. + * + * @param {Box2} box - The bounding box to test. + * @return {boolean} Whether the given bounding box intersects with this bounding box. + */ + intersectsBox( box ) { + + // using 4 splitting planes to rule out intersections + + return box.max.x >= this.min.x && box.min.x <= this.max.x && + box.max.y >= this.min.y && box.min.y <= this.max.y; + + } + + /** + * Clamps the given point within the bounds of this box. + * + * @param {Vector2} point - The point to clamp. + * @param {Vector2} target - The target vector that is used to store the method's result. + * @return {Vector2} The clamped point. + */ + clampPoint( point, target ) { + + return target.copy( point ).clamp( this.min, this.max ); + + } + + /** + * Returns the euclidean distance from any edge of this box to the specified point. If + * the given point lies inside of this box, the distance will be `0`. + * + * @param {Vector2} point - The point to compute the distance to. + * @return {number} The euclidean distance. + */ + distanceToPoint( point ) { + + return this.clampPoint( point, _vector$4 ).distanceTo( point ); + + } + + /** + * Computes the intersection of this bounding box and the given one, setting the upper + * bound of this box to the lesser of the two boxes' upper bounds and the + * lower bound of this box to the greater of the two boxes' lower bounds. If + * there's no overlap, makes this box empty. + * + * @param {Box2} box - The bounding box to intersect with. + * @return {Box2} A reference to this bounding box. + */ + intersect( box ) { + + this.min.max( box.min ); + this.max.min( box.max ); + + if ( this.isEmpty() ) this.makeEmpty(); + + return this; + + } + + /** + * Computes the union of this box and another and the given one, setting the upper + * bound of this box to the greater of the two boxes' upper bounds and the + * lower bound of this box to the lesser of the two boxes' lower bounds. + * + * @param {Box2} box - The bounding box that will be unioned with this instance. + * @return {Box2} A reference to this bounding box. + */ + union( box ) { + + this.min.min( box.min ); + this.max.max( box.max ); + + return this; + + } + + /** + * Adds the given offset to both the upper and lower bounds of this bounding box, + * effectively moving it in 2D space. + * + * @param {Vector2} offset - The offset that should be used to translate the bounding box. + * @return {Box2} A reference to this bounding box. + */ + translate( offset ) { + + this.min.add( offset ); + this.max.add( offset ); + + return this; + + } + + /** + * Returns `true` if this bounding box is equal with the given one. + * + * @param {Box2} box - The box to test for equality. + * @return {boolean} Whether this bounding box is equal with the given one. + */ + equals( box ) { + + return box.min.equals( this.min ) && box.max.equals( this.max ); + + } + +} + +const _startP = /*@__PURE__*/ new Vector3(); +const _startEnd = /*@__PURE__*/ new Vector3(); + +const _d1 = /*@__PURE__*/ new Vector3(); +const _d2 = /*@__PURE__*/ new Vector3(); +const _r = /*@__PURE__*/ new Vector3(); +const _c1 = /*@__PURE__*/ new Vector3(); +const _c2 = /*@__PURE__*/ new Vector3(); + +/** + * An analytical line segment in 3D space represented by a start and end point. + */ +class Line3 { + + /** + * Constructs a new line segment. + * + * @param {Vector3} [start=(0,0,0)] - Start of the line segment. + * @param {Vector3} [end=(0,0,0)] - End of the line segment. + */ + constructor( start = new Vector3(), end = new Vector3() ) { + + /** + * Start of the line segment. + * + * @type {Vector3} + */ + this.start = start; + + /** + * End of the line segment. + * + * @type {Vector3} + */ + this.end = end; + + } + + /** + * Sets the start and end values by copying the given vectors. + * + * @param {Vector3} start - The start point. + * @param {Vector3} end - The end point. + * @return {Line3} A reference to this line segment. + */ + set( start, end ) { + + this.start.copy( start ); + this.end.copy( end ); + + return this; + + } + + /** + * Copies the values of the given line segment to this instance. + * + * @param {Line3} line - The line segment to copy. + * @return {Line3} A reference to this line segment. + */ + copy( line ) { + + this.start.copy( line.start ); + this.end.copy( line.end ); + + return this; + + } + + /** + * Returns the center of the line segment. + * + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {Vector3} The center point. + */ + getCenter( target ) { + + return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 ); + + } + + /** + * Returns the delta vector of the line segment's start and end point. + * + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {Vector3} The delta vector. + */ + delta( target ) { + + return target.subVectors( this.end, this.start ); + + } + + /** + * Returns the squared Euclidean distance between the line' start and end point. + * + * @return {number} The squared Euclidean distance. + */ + distanceSq() { + + return this.start.distanceToSquared( this.end ); + + } + + /** + * Returns the Euclidean distance between the line' start and end point. + * + * @return {number} The Euclidean distance. + */ + distance() { + + return this.start.distanceTo( this.end ); + + } + + /** + * Returns a vector at a certain position along the line segment. + * + * @param {number} t - A value between `[0,1]` to represent a position along the line segment. + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {Vector3} The delta vector. + */ + at( t, target ) { + + return this.delta( target ).multiplyScalar( t ).add( this.start ); + + } + + /** + * Returns a point parameter based on the closest point as projected on the line segment. + * + * @param {Vector3} point - The point for which to return a point parameter. + * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not. + * @return {number} The point parameter. + */ + closestPointToPointParameter( point, clampToLine ) { + + _startP.subVectors( point, this.start ); + _startEnd.subVectors( this.end, this.start ); + + const startEnd2 = _startEnd.dot( _startEnd ); + + if ( startEnd2 === 0 ) return 0; + + const startEnd_startP = _startEnd.dot( _startP ); + + let t = startEnd_startP / startEnd2; + + if ( clampToLine ) { + + t = clamp( t, 0, 1 ); + + } + + return t; + + } + + /** + * Returns the closest point on the line for a given point. + * + * @param {Vector3} point - The point to compute the closest point on the line for. + * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not. + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {Vector3} The closest point on the line. + */ + closestPointToPoint( point, clampToLine, target ) { + + const t = this.closestPointToPointParameter( point, clampToLine ); + + return this.delta( target ).multiplyScalar( t ).add( this.start ); + + } + + /** + * Returns the closest squared distance between this line segment and the given one. + * + * @param {Line3} line - The line segment to compute the closest squared distance to. + * @param {Vector3} [c1] - The closest point on this line segment. + * @param {Vector3} [c2] - The closest point on the given line segment. + * @return {number} The squared distance between this line segment and the given one. + */ + distanceSqToLine3( line, c1 = _c1, c2 = _c2 ) { + + // from Real-Time Collision Detection by Christer Ericson, chapter 5.1.9 + + // Computes closest points C1 and C2 of S1(s)=P1+s*(Q1-P1) and + // S2(t)=P2+t*(Q2-P2), returning s and t. Function result is squared + // distance between between S1(s) and S2(t) + + const EPSILON = 1e-8 * 1e-8; // must be squared since we compare squared length + let s, t; + + const p1 = this.start; + const p2 = line.start; + const q1 = this.end; + const q2 = line.end; + + _d1.subVectors( q1, p1 ); // Direction vector of segment S1 + _d2.subVectors( q2, p2 ); // Direction vector of segment S2 + _r.subVectors( p1, p2 ); + + const a = _d1.dot( _d1 ); // Squared length of segment S1, always nonnegative + const e = _d2.dot( _d2 ); // Squared length of segment S2, always nonnegative + const f = _d2.dot( _r ); + + // Check if either or both segments degenerate into points + + if ( a <= EPSILON && e <= EPSILON ) { + + // Both segments degenerate into points + + c1.copy( p1 ); + c2.copy( p2 ); + + c1.sub( c2 ); + + return c1.dot( c1 ); + + } + + if ( a <= EPSILON ) { + + // First segment degenerates into a point + + s = 0; + t = f / e; // s = 0 => t = (b*s + f) / e = f / e + t = clamp( t, 0, 1 ); + + + } else { + + const c = _d1.dot( _r ); + + if ( e <= EPSILON ) { + + // Second segment degenerates into a point + + t = 0; + s = clamp( - c / a, 0, 1 ); // t = 0 => s = (b*t - c) / a = -c / a + + } else { + + // The general nondegenerate case starts here + + const b = _d1.dot( _d2 ); + const denom = a * e - b * b; // Always nonnegative + + // If segments not parallel, compute closest point on L1 to L2 and + // clamp to segment S1. Else pick arbitrary s (here 0) + + if ( denom !== 0 ) { + + s = clamp( ( b * f - c * e ) / denom, 0, 1 ); + + } else { + + s = 0; + + } + + // Compute point on L2 closest to S1(s) using + // t = Dot((P1 + D1*s) - P2,D2) / Dot(D2,D2) = (b*s + f) / e + + t = ( b * s + f ) / e; + + // If t in [0,1] done. Else clamp t, recompute s for the new value + // of t using s = Dot((P2 + D2*t) - P1,D1) / Dot(D1,D1)= (t*b - c) / a + // and clamp s to [0, 1] + + if ( t < 0 ) { + + t = 0.; + s = clamp( - c / a, 0, 1 ); + + } else if ( t > 1 ) { + + t = 1; + s = clamp( ( b - c ) / a, 0, 1 ); + + } + + } + + } + + c1.copy( p1 ).addScaledVector( _d1, s ); + c2.copy( p2 ).addScaledVector( _d2, t ); + + return c1.distanceToSquared( c2 ); + + } + + /** + * Applies a 4x4 transformation matrix to this line segment. + * + * @param {Matrix4} matrix - The transformation matrix. + * @return {Line3} A reference to this line segment. + */ + applyMatrix4( matrix ) { + + this.start.applyMatrix4( matrix ); + this.end.applyMatrix4( matrix ); + + return this; + + } + + /** + * Returns `true` if this line segment is equal with the given one. + * + * @param {Line3} line - The line segment to test for equality. + * @return {boolean} Whether this line segment is equal with the given one. + */ + equals( line ) { + + return line.start.equals( this.start ) && line.end.equals( this.end ); + + } + + /** + * Returns a new line segment with copied values from this instance. + * + * @return {Line3} A clone of this instance. + */ + clone() { + + return new this.constructor().copy( this ); + + } + +} + +const _vector$3 = /*@__PURE__*/ new Vector3(); + +/** + * This displays a cone shaped helper object for a {@link SpotLight}. + * + * When the spot light or its target are transformed or light properties are + * changed, it's necessary to call the `update()` method of the respective helper. + * + * ```js + * const spotLight = new THREE.SpotLight( 0xffffff ); + * spotLight.position.set( 10, 10, 10 ); + * scene.add( spotLight ); + * + * const spotLightHelper = new THREE.SpotLightHelper( spotLight ); + * scene.add( spotLightHelper ); + * ``` + * + * @augments Object3D + */ +class SpotLightHelper extends Object3D { + + /** + * Constructs a new spot light helper. + * + * @param {HemisphereLight} light - The light to be visualized. + * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take + * the color of the light. + */ + constructor( light, color ) { + + super(); + + /** + * The light being visualized. + * + * @type {SpotLight} + */ + this.light = light; + + this.matrixAutoUpdate = false; + + /** + * The color parameter passed in the constructor. + * If not set, the helper will take the color of the light. + * + * @type {number|Color|string} + */ + this.color = color; + + this.type = 'SpotLightHelper'; + + const geometry = new BufferGeometry(); + + const positions = [ + 0, 0, 0, 0, 0, 1, + 0, 0, 0, 1, 0, 1, + 0, 0, 0, -1, 0, 1, + 0, 0, 0, 0, 1, 1, + 0, 0, 0, 0, -1, 1 + ]; + + for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) { + + const p1 = ( i / l ) * Math.PI * 2; + const p2 = ( j / l ) * Math.PI * 2; + + positions.push( + Math.cos( p1 ), Math.sin( p1 ), 1, + Math.cos( p2 ), Math.sin( p2 ), 1 + ); + + } + + geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) ); + + const material = new LineBasicMaterial( { fog: false, toneMapped: false } ); + + this.cone = new LineSegments( geometry, material ); + this.add( this.cone ); + + this.update(); + + } + + /** + * Frees the GPU-related resources allocated by this instance. Call this + * method whenever this instance is no longer used in your app. + */ + dispose() { + + super.dispose(); + + this.cone.geometry.dispose(); + this.cone.material.dispose(); + + } + + /** + * Updates the helper to match the position and direction of the + * light being visualized. + */ + update() { + + this.light.updateWorldMatrix( true, false ); + this.light.target.updateWorldMatrix( true, false ); + + // update the local matrix based on the parent and light target transforms + if ( this.parent ) { + + this.parent.updateWorldMatrix( true ); + + this.matrix + .copy( this.parent.matrixWorld ) + .invert() + .multiply( this.light.matrixWorld ); + + } else { + + this.matrix.copy( this.light.matrixWorld ); + + } + + this.matrixWorldNeedsUpdate = true; + + const coneLength = this.light.distance ? this.light.distance : 1000; + const coneWidth = coneLength * Math.tan( this.light.angle ); + + this.cone.scale.set( coneWidth, coneWidth, coneLength ); + + _vector$3.setFromMatrixPosition( this.light.target.matrixWorld ); + + this.cone.lookAt( _vector$3 ); + + if ( this.color !== undefined ) { + + this.cone.material.color.set( this.color ); + + } else { + + this.cone.material.color.copy( this.light.color ); + + } + + } + +} + +const _vector$2 = /*@__PURE__*/ new Vector3(); +const _boneMatrix = /*@__PURE__*/ new Matrix4(); +const _matrixWorldInv = /*@__PURE__*/ new Matrix4(); + +/** + * A helper object to assist with visualizing a {@link Skeleton}. + * + * ```js + * const helper = new THREE.SkeletonHelper( skinnedMesh ); + * scene.add( helper ); + * ``` + * + * @augments LineSegments + */ +class SkeletonHelper extends LineSegments { + + /** + * Constructs a new skeleton helper. + * + * @param {Object3D} object - Usually an instance of {@link SkinnedMesh}. However, any 3D object + * can be used if it represents a hierarchy of bones (see {@link Bone}). + */ + constructor( object ) { + + const bones = getBoneList( object ); + + const geometry = new BufferGeometry(); + + const vertices = []; + const colors = []; + + for ( let i = 0; i < bones.length; i ++ ) { + + const bone = bones[ i ]; + + if ( bone.parent && bone.parent.isBone ) { + + vertices.push( 0, 0, 0 ); + vertices.push( 0, 0, 0 ); + colors.push( 0, 0, 0 ); + colors.push( 0, 0, 0 ); + + } + + } + + geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) ); + + const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } ); + + super( geometry, material ); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isSkeletonHelper = true; + + this.type = 'SkeletonHelper'; + + /** + * The object being visualized. + * + * @type {Object3D} + */ + this.root = object; + + /** + * The list of bones that the helper visualizes. + * + * @type {Array} + */ + this.bones = bones; + + this.matrix = object.matrixWorld; + this.matrixAutoUpdate = false; + + // colors + + const color1 = new Color( 0x0000ff ); + const color2 = new Color( 0x00ff00 ); + + this.setColors( color1, color2 ); + + } + + updateMatrixWorld( force ) { + + const bones = this.bones; + + const geometry = this.geometry; + const position = geometry.getAttribute( 'position' ); + + _matrixWorldInv.copy( this.root.matrixWorld ).invert(); + + for ( let i = 0, j = 0; i < bones.length; i ++ ) { + + const bone = bones[ i ]; + + if ( bone.parent && bone.parent.isBone ) { + + _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld ); + _vector$2.setFromMatrixPosition( _boneMatrix ); + position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z ); + + _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld ); + _vector$2.setFromMatrixPosition( _boneMatrix ); + position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z ); + + j += 2; + + } + + } + + geometry.getAttribute( 'position' ).needsUpdate = true; + + super.updateMatrixWorld( force ); + + } + + /** + * Defines the colors of the helper. + * + * @param {Color} color1 - The first line color for each bone. + * @param {Color} color2 - The second line color for each bone. + * @return {SkeletonHelper} A reference to this helper. + */ + setColors( color1, color2 ) { + + const geometry = this.geometry; + const colorAttribute = geometry.getAttribute( 'color' ); + + for ( let i = 0; i < colorAttribute.count; i += 2 ) { + + colorAttribute.setXYZ( i, color1.r, color1.g, color1.b ); + colorAttribute.setXYZ( i + 1, color2.r, color2.g, color2.b ); + + } + + colorAttribute.needsUpdate = true; + + return this; + + } + + /** + * Frees the GPU-related resources allocated by this instance. Call this + * method whenever this instance is no longer used in your app. + */ + dispose() { + + super.dispose(); + + this.geometry.dispose(); + this.material.dispose(); + + } + +} + + +function getBoneList( object ) { + + const boneList = []; + + if ( object.isBone === true ) { + + boneList.push( object ); + + } + + for ( let i = 0; i < object.children.length; i ++ ) { + + boneList.push( ...getBoneList( object.children[ i ] ) ); + + } + + return boneList; + +} + +/** + * This displays a helper object consisting of a spherical mesh for + * visualizing an instance of {@link PointLight}. + * + * ```js + * const pointLight = new THREE.PointLight( 0xff0000, 1, 100 ); + * pointLight.position.set( 10, 10, 10 ); + * scene.add( pointLight ); + * + * const sphereSize = 1; + * const pointLightHelper = new THREE.PointLightHelper( pointLight, sphereSize ); + * scene.add( pointLightHelper ); + * ``` + * + * @augments Mesh + */ +class PointLightHelper extends Mesh { + + /** + * Constructs a new point light helper. + * + * @param {PointLight} light - The light to be visualized. + * @param {number} [sphereSize=1] - The size of the sphere helper. + * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take + * the color of the light. + */ + constructor( light, sphereSize, color ) { + + const geometry = new SphereGeometry( sphereSize, 4, 2 ); + const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } ); + + super( geometry, material ); + + /** + * The light being visualized. + * + * @type {PointLight} + */ + this.light = light; + + /** + * The color parameter passed in the constructor. + * If not set, the helper will take the color of the light. + * + * @type {number|Color|string} + */ + this.color = color; + + this.type = 'PointLightHelper'; + + this.matrix = this.light.matrixWorld; + this.matrixAutoUpdate = false; + + this.update(); + + } + + /** + * Frees the GPU-related resources allocated by this instance. Call this + * method whenever this instance is no longer used in your app. + */ + dispose() { + + super.dispose(); + + this.geometry.dispose(); + this.material.dispose(); + + } + + /** + * Updates the helper to match the position of the + * light being visualized. + */ + update() { + + this.matrixWorldNeedsUpdate = true; + + this.light.updateWorldMatrix( true, false ); + + if ( this.color !== undefined ) { + + this.material.color.set( this.color ); + + } else { + + this.material.color.copy( this.light.color ); + + } + + /* + const d = this.light.distance; + + if ( d === 0.0 ) { + + this.lightDistance.visible = false; + + } else { + + this.lightDistance.visible = true; + this.lightDistance.scale.set( d, d, d ); + + } + */ + + } + +} + +const _vector$1 = /*@__PURE__*/ new Vector3(); +const _color1 = /*@__PURE__*/ new Color(); +const _color2 = /*@__PURE__*/ new Color(); + +/** + * Creates a visual aid consisting of a spherical mesh for a + * given {@link HemisphereLight}. + * + * When the hemisphere light is transformed or its light properties are changed, + * it's necessary to call the `update()` method of the respective helper. + * + * ```js + * const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 ); + * const helper = new THREE.HemisphereLightHelper( light, 5 ); + * scene.add( helper ); + * ``` + * + * @augments Object3D + */ +class HemisphereLightHelper extends Object3D { + + /** + * Constructs a new hemisphere light helper. + * + * @param {HemisphereLight} light - The light to be visualized. + * @param {number} [size=1] - The size of the mesh used to visualize the light. + * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take + * the color of the light. + */ + constructor( light, size, color ) { + + super(); + + /** + * The light being visualized. + * + * @type {HemisphereLight} + */ + this.light = light; + + this.matrix = light.matrixWorld; + this.matrixAutoUpdate = false; + + /** + * The color parameter passed in the constructor. + * If not set, the helper will take the color of the light. + * + * @type {number|Color|string} + */ + this.color = color; + + this.type = 'HemisphereLightHelper'; + + const geometry = new OctahedronGeometry( size ); + geometry.rotateY( Math.PI * 0.5 ); + + this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } ); + if ( this.color === undefined ) this.material.vertexColors = true; + + const position = geometry.getAttribute( 'position' ); + const colors = new Float32Array( position.count * 3 ); + + geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) ); + + this.add( new Mesh( geometry, this.material ) ); + + this.update(); + + } + + /** + * Frees the GPU-related resources allocated by this instance. Call this + * method whenever this instance is no longer used in your app. + */ + dispose() { + + super.dispose(); + + this.children[ 0 ].geometry.dispose(); + this.children[ 0 ].material.dispose(); + + } + + /** + * Updates the helper to match the position and direction of the + * light being visualized. + */ + update() { + + const mesh = this.children[ 0 ]; + + if ( this.color !== undefined ) { + + this.material.color.set( this.color ); + + } else { + + const colors = mesh.geometry.getAttribute( 'color' ); + + _color1.copy( this.light.color ); + _color2.copy( this.light.groundColor ); + + for ( let i = 0, l = colors.count; i < l; i ++ ) { + + const color = ( i < ( l / 2 ) ) ? _color1 : _color2; + + colors.setXYZ( i, color.r, color.g, color.b ); + + } + + colors.needsUpdate = true; + + } + + this.matrixWorldNeedsUpdate = true; + + this.light.updateWorldMatrix( true, false ); + + mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() ); + + } + +} + +/** + * The helper is an object to define grids. Grids are two-dimensional + * arrays of lines. + * + * ```js + * const size = 10; + * const divisions = 10; + * + * const gridHelper = new THREE.GridHelper( size, divisions ); + * scene.add( gridHelper ); + * ``` + * + * @augments LineSegments + */ +class GridHelper extends LineSegments { + + /** + * Constructs a new grid helper. + * + * @param {number} [size=10] - The size of the grid. + * @param {number} [divisions=10] - The number of divisions across the grid. + * @param {number|Color|string} [color1=0x444444] - The color of the center line. + * @param {number|Color|string} [color2=0x888888] - The color of the lines of the grid. + */ + constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) { + + color1 = new Color( color1 ); + color2 = new Color( color2 ); + + const center = divisions / 2; + const step = size / divisions; + const halfSize = size / 2; + + const vertices = [], colors = []; + + for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) { + + vertices.push( - halfSize, 0, k, halfSize, 0, k ); + vertices.push( k, 0, - halfSize, k, 0, halfSize ); + + const color = i === center ? color1 : color2; + + color.toArray( colors, j ); j += 3; + color.toArray( colors, j ); j += 3; + color.toArray( colors, j ); j += 3; + color.toArray( colors, j ); j += 3; + + } + + const geometry = new BufferGeometry(); + geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) ); + + const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } ); + + super( geometry, material ); + + this.type = 'GridHelper'; + + } + + /** + * Frees the GPU-related resources allocated by this instance. Call this + * method whenever this instance is no longer used in your app. + */ + dispose() { + + super.dispose(); + + this.geometry.dispose(); + this.material.dispose(); + + } + +} + +/** + * This helper is an object to define polar grids. Grids are + * two-dimensional arrays of lines. + * + * ```js + * const radius = 10; + * const sectors = 16; + * const rings = 8; + * const divisions = 64; + * + * const helper = new THREE.PolarGridHelper( radius, sectors, rings, divisions ); + * scene.add( helper ); + * ``` + * + * @augments LineSegments + */ +class PolarGridHelper extends LineSegments { + + /** + * Constructs a new polar grid helper. + * + * @param {number} [radius=10] - The radius of the polar grid. This can be any positive number. + * @param {number} [sectors=16] - The number of sectors the grid will be divided into. This can be any positive integer. + * @param {number} [rings=16] - The number of rings. This can be any positive integer. + * @param {number} [divisions=64] - The number of line segments used for each circle. This can be any positive integer. + * @param {number|Color|string} [color1=0x444444] - The first color used for grid elements. + * @param {number|Color|string} [color2=0x888888] - The second color used for grid elements. + */ + constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) { + + color1 = new Color( color1 ); + color2 = new Color( color2 ); + + const vertices = []; + const colors = []; + + // create the sectors + + if ( sectors > 1 ) { + + for ( let i = 0; i < sectors; i ++ ) { + + const v = ( i / sectors ) * ( Math.PI * 2 ); + + const x = Math.sin( v ) * radius; + const z = Math.cos( v ) * radius; + + vertices.push( 0, 0, 0 ); + vertices.push( x, 0, z ); + + const color = ( i & 1 ) ? color1 : color2; + + colors.push( color.r, color.g, color.b ); + colors.push( color.r, color.g, color.b ); + + } + + } + + // create the rings + + for ( let i = 0; i < rings; i ++ ) { + + const color = ( i & 1 ) ? color1 : color2; + + const r = radius - ( radius / rings * i ); + + for ( let j = 0; j < divisions; j ++ ) { + + // first vertex + + let v = ( j / divisions ) * ( Math.PI * 2 ); + + let x = Math.sin( v ) * r; + let z = Math.cos( v ) * r; + + vertices.push( x, 0, z ); + colors.push( color.r, color.g, color.b ); + + // second vertex + + v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 ); + + x = Math.sin( v ) * r; + z = Math.cos( v ) * r; + + vertices.push( x, 0, z ); + colors.push( color.r, color.g, color.b ); + + } + + } + + const geometry = new BufferGeometry(); + geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) ); + + const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } ); + + super( geometry, material ); + + this.type = 'PolarGridHelper'; + + } + + /** + * Frees the GPU-related resources allocated by this instance. Call this + * method whenever this instance is no longer used in your app. + */ + dispose() { + + super.dispose(); + + this.geometry.dispose(); + this.material.dispose(); + + } + +} + +const _v1 = /*@__PURE__*/ new Vector3(); +const _v2 = /*@__PURE__*/ new Vector3(); +const _v3 = /*@__PURE__*/ new Vector3(); + +/** + * Helper object to assist with visualizing a {@link DirectionalLight}'s + * effect on the scene. This consists of a plane and a line representing the + * light's position and direction. + * + * When the directional light or its target are transformed or light properties + * are changed, it's necessary to call the `update()` method of the respective helper. + * + * ```js + * const light = new THREE.DirectionalLight( 0xFFFFFF ); + * scene.add( light ); + * + * const helper = new THREE.DirectionalLightHelper( light, 5 ); + * scene.add( helper ); + * ``` + * + * @augments Object3D + */ +class DirectionalLightHelper extends Object3D { + + /** + * Constructs a new directional light helper. + * + * @param {DirectionalLight} light - The light to be visualized. + * @param {number} [size=1] - The dimensions of the plane. + * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take + * the color of the light. + */ + constructor( light, size, color ) { + + super(); + + /** + * The light being visualized. + * + * @type {DirectionalLight} + */ + this.light = light; + + this.matrix = light.matrixWorld; + this.matrixAutoUpdate = false; + + /** + * The color parameter passed in the constructor. + * If not set, the helper will take the color of the light. + * + * @type {number|Color|string} + */ + this.color = color; + + this.type = 'DirectionalLightHelper'; + + if ( size === undefined ) size = 1; + + let geometry = new BufferGeometry(); + geometry.setAttribute( 'position', new Float32BufferAttribute( [ + - size, size, 0, + size, size, 0, + size, - size, 0, + - size, - size, 0, + - size, size, 0 + ], 3 ) ); + + const material = new LineBasicMaterial( { fog: false, toneMapped: false } ); + + /** + * Contains the line showing the location of the directional light. + * + * @type {Line} + */ + this.lightPlane = new Line( geometry, material ); + this.add( this.lightPlane ); + + geometry = new BufferGeometry(); + geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) ); + + /** + * Represents the target line of the directional light. + * + * @type {Line} + */ + this.targetLine = new Line( geometry, material ); + this.add( this.targetLine ); + + this.update(); + + } + + /** + * Frees the GPU-related resources allocated by this instance. Call this + * method whenever this instance is no longer used in your app. + */ + dispose() { + + super.dispose(); + + this.lightPlane.geometry.dispose(); + this.lightPlane.material.dispose(); + this.targetLine.geometry.dispose(); + this.targetLine.material.dispose(); + + } + + /** + * Updates the helper to match the position and direction of the + * light being visualized. + */ + update() { + + this.matrixWorldNeedsUpdate = true; + + this.light.updateWorldMatrix( true, false ); + this.light.target.updateWorldMatrix( true, false ); + + _v1.setFromMatrixPosition( this.light.matrixWorld ); + _v2.setFromMatrixPosition( this.light.target.matrixWorld ); + _v3.subVectors( _v2, _v1 ); + + this.lightPlane.lookAt( _v2 ); + + if ( this.color !== undefined ) { + + this.lightPlane.material.color.set( this.color ); + this.targetLine.material.color.set( this.color ); + + } else { + + this.lightPlane.material.color.copy( this.light.color ); + this.targetLine.material.color.copy( this.light.color ); + + } + + this.targetLine.lookAt( _v2 ); + this.targetLine.scale.z = _v3.length(); + + } + +} + +const _vector = /*@__PURE__*/ new Vector3(); +const _camera = /*@__PURE__*/ new Camera(); + +/** + * This helps with visualizing what a camera contains in its frustum. It + * visualizes the frustum of a camera using a line segments. + * + * Based on frustum visualization in [lightgl.js shadowmap example](https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html). + * + * `CameraHelper` must be a child of the scene. + * + * When the camera is transformed or its projection matrix is changed, it's necessary + * to call the `update()` method of the respective helper. + * + * ```js + * const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 ); + * const helper = new THREE.CameraHelper( camera ); + * scene.add( helper ); + * ``` + * + * @augments LineSegments + */ +class CameraHelper extends LineSegments { + + /** + * Constructs a new arrow helper. + * + * @param {Camera} camera - The camera to visualize. + */ + constructor( camera ) { + + const geometry = new BufferGeometry(); + const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } ); + + const vertices = []; + const colors = []; + + const pointMap = {}; + + // near + + addLine( 'n1', 'n2' ); + addLine( 'n2', 'n4' ); + addLine( 'n4', 'n3' ); + addLine( 'n3', 'n1' ); + + // far + + addLine( 'f1', 'f2' ); + addLine( 'f2', 'f4' ); + addLine( 'f4', 'f3' ); + addLine( 'f3', 'f1' ); + + // sides + + addLine( 'n1', 'f1' ); + addLine( 'n2', 'f2' ); + addLine( 'n3', 'f3' ); + addLine( 'n4', 'f4' ); + + // cone + + addLine( 'p', 'n1' ); + addLine( 'p', 'n2' ); + addLine( 'p', 'n3' ); + addLine( 'p', 'n4' ); + + // up + + addLine( 'u1', 'u2' ); + addLine( 'u2', 'u3' ); + addLine( 'u3', 'u1' ); + + // target + + addLine( 'c', 't' ); + addLine( 'p', 'c' ); + + // cross + + addLine( 'cn1', 'cn2' ); + addLine( 'cn3', 'cn4' ); + + addLine( 'cf1', 'cf2' ); + addLine( 'cf3', 'cf4' ); + + function addLine( a, b ) { + + addPoint( a ); + addPoint( b ); + + } + + function addPoint( id ) { + + vertices.push( 0, 0, 0 ); + colors.push( 0, 0, 0 ); + + if ( pointMap[ id ] === undefined ) { + + pointMap[ id ] = []; + + } + + pointMap[ id ].push( ( vertices.length / 3 ) - 1 ); + + } + + geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) ); + + super( geometry, material ); + + this.type = 'CameraHelper'; + + /** + * The camera being visualized. + * + * @type {Camera} + */ + this.camera = camera; + if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix(); + + this.matrix = camera.matrixWorld; + this.matrixAutoUpdate = false; + + /** + * This contains the points used to visualize the camera. + * + * @type {Object>} + */ + this.pointMap = pointMap; + + this.update(); + + // colors + + const colorFrustum = new Color( 0xffaa00 ); + const colorCone = new Color( 0xff0000 ); + const colorUp = new Color( 0x00aaff ); + const colorTarget = new Color( 0xffffff ); + const colorCross = new Color( 0x333333 ); + + this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross ); + + } + + /** + * Defines the colors of the helper. + * + * @param {Color} frustum - The frustum line color. + * @param {Color} cone - The cone line color. + * @param {Color} up - The up line color. + * @param {Color} target - The target line color. + * @param {Color} cross - The cross line color. + * @return {CameraHelper} A reference to this helper. + */ + setColors( frustum, cone, up, target, cross ) { + + const geometry = this.geometry; + + const colorAttribute = geometry.getAttribute( 'color' ); + + // near + + colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2 + colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4 + colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3 + colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1 + + // far + + colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2 + colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4 + colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3 + colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1 + + // sides + + colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1 + colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2 + colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3 + colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4 + + // cone + + colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1 + colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2 + colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3 + colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4 + + // up + + colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2 + colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3 + colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1 + + // target + + colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t + colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c + + // cross + + colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2 + colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4 + + colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2 + colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4 + + colorAttribute.needsUpdate = true; + + return this; + + } + + /** + * Updates the helper based on the projection matrix of the camera. + */ + update() { + + const geometry = this.geometry; + const pointMap = this.pointMap; + + const w = 1, h = 1; + + let nearZ, farZ; + + // we need just camera projection matrix inverse + // world matrix must be identity + + _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse ); + + // Adjust z values based on coordinate system + + if ( this.camera.reversedDepth === true ) { + + nearZ = 1; + farZ = 0; + + } else { + + if ( this.camera.coordinateSystem === WebGLCoordinateSystem ) { + + nearZ = -1; + farZ = 1; + + } else if ( this.camera.coordinateSystem === WebGPUCoordinateSystem ) { + + nearZ = 0; + farZ = 1; + + } else { + + throw new Error( 'THREE.CameraHelper.update(): Invalid coordinate system: ' + this.camera.coordinateSystem ); + + } + + } + + + // center / target + setPoint( 'c', pointMap, geometry, _camera, 0, 0, nearZ ); + setPoint( 't', pointMap, geometry, _camera, 0, 0, farZ ); + + // near + + setPoint( 'n1', pointMap, geometry, _camera, - w, - h, nearZ ); + setPoint( 'n2', pointMap, geometry, _camera, w, - h, nearZ ); + setPoint( 'n3', pointMap, geometry, _camera, - w, h, nearZ ); + setPoint( 'n4', pointMap, geometry, _camera, w, h, nearZ ); + + // far + + setPoint( 'f1', pointMap, geometry, _camera, - w, - h, farZ ); + setPoint( 'f2', pointMap, geometry, _camera, w, - h, farZ ); + setPoint( 'f3', pointMap, geometry, _camera, - w, h, farZ ); + setPoint( 'f4', pointMap, geometry, _camera, w, h, farZ ); + + // up + + setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, nearZ ); + setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, nearZ ); + setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, nearZ ); + + // cross + + setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, farZ ); + setPoint( 'cf2', pointMap, geometry, _camera, w, 0, farZ ); + setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, farZ ); + setPoint( 'cf4', pointMap, geometry, _camera, 0, h, farZ ); + + setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, nearZ ); + setPoint( 'cn2', pointMap, geometry, _camera, w, 0, nearZ ); + setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, nearZ ); + setPoint( 'cn4', pointMap, geometry, _camera, 0, h, nearZ ); + + geometry.getAttribute( 'position' ).needsUpdate = true; + + } + + /** + * Frees the GPU-related resources allocated by this instance. Call this + * method whenever this instance is no longer used in your app. + */ + dispose() { + + super.dispose(); + + this.geometry.dispose(); + this.material.dispose(); + + } + +} + + +function setPoint( point, pointMap, geometry, camera, x, y, z ) { + + _vector.set( x, y, z ).unproject( camera ); + + const points = pointMap[ point ]; + + if ( points !== undefined ) { + + const position = geometry.getAttribute( 'position' ); + + for ( let i = 0, l = points.length; i < l; i ++ ) { + + position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z ); + + } + + } + +} + +const _box = /*@__PURE__*/ new Box3(); + +/** + * Helper object to graphically show the world-axis-aligned bounding box + * around an object. The actual bounding box is handled with {@link Box3}, + * this is just a visual helper for debugging. It can be automatically + * resized with {@link BoxHelper#update} when the object it's created from + * is transformed. Note that the object must have a geometry for this to work, + * so it won't work with sprites. + * + * ```js + * const sphere = new THREE.SphereGeometry(); + * const object = new THREE.Mesh( sphere, new THREE.MeshBasicMaterial( 0xff0000 ) ); + * const box = new THREE.BoxHelper( object, 0xffff00 ); + * scene.add( box ); + * ``` + * + * @augments LineSegments + */ +class BoxHelper extends LineSegments { + + /** + * Constructs a new box helper. + * + * @param {Object3D} [object] - The 3D object to show the world-axis-aligned bounding box. + * @param {number|Color|string} [color=0xffff00] - The box's color. + */ + constructor( object, color = 0xffff00 ) { + + const indices = new Uint16Array( [ 0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7 ] ); + const positions = new Float32Array( 8 * 3 ); + + const geometry = new BufferGeometry(); + geometry.setIndex( new BufferAttribute( indices, 1 ) ); + geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) ); + + super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) ); + + /** + * The 3D object being visualized. + * + * @type {Object3D} + */ + this.object = object; + this.type = 'BoxHelper'; + + this.matrixAutoUpdate = false; + + this.update(); + + } + + /** + * Updates the helper's geometry to match the dimensions of the object, + * including any children. + */ + update() { + + if ( this.object !== undefined ) { + + _box.setFromObject( this.object ); + + } + + if ( _box.isEmpty() ) return; + + const min = _box.min; + const max = _box.max; + + /* + 5____4 + 1/___0/| + | 6__|_7 + 2/___3/ + + 0: max.x, max.y, max.z + 1: min.x, max.y, max.z + 2: min.x, min.y, max.z + 3: max.x, min.y, max.z + 4: max.x, max.y, min.z + 5: min.x, max.y, min.z + 6: min.x, min.y, min.z + 7: max.x, min.y, min.z + */ + + const position = this.geometry.attributes.position; + const array = position.array; + + array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z; + array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z; + array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z; + array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z; + array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z; + array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z; + array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z; + array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z; + + position.needsUpdate = true; + + this.geometry.computeBoundingSphere(); + + } + + /** + * Updates the wireframe box for the passed object. + * + * @param {Object3D} object - The 3D object to create the helper for. + * @return {BoxHelper} A reference to this instance. + */ + setFromObject( object ) { + + this.object = object; + this.update(); + + return this; + + } + + copy( source, recursive ) { + + super.copy( source, recursive ); + + this.object = source.object; + + return this; + + } + + /** + * Frees the GPU-related resources allocated by this instance. Call this + * method whenever this instance is no longer used in your app. + */ + dispose() { + + super.dispose(); + + this.geometry.dispose(); + this.material.dispose(); + + } + +} + +/** + * A helper object to visualize an instance of {@link Box3}. + * + * ```js + * const box = new THREE.Box3(); + * box.setFromCenterAndSize( new THREE.Vector3( 1, 1, 1 ), new THREE.Vector3( 2, 1, 3 ) ); + * + * const helper = new THREE.Box3Helper( box, 0xffff00 ); + * scene.add( helper ) + * ``` + * + * @augments LineSegments + */ +class Box3Helper extends LineSegments { + + /** + * Constructs a new box3 helper. + * + * @param {Box3} box - The box to visualize. + * @param {number|Color|string} [color=0xffff00] - The box's color. + */ + constructor( box, color = 0xffff00 ) { + + const indices = new Uint16Array( [ 0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7 ] ); + + const positions = [ 1, 1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1, 1, 1, -1, -1, 1, -1, -1, -1, -1, 1, -1, -1 ]; + + const geometry = new BufferGeometry(); + + geometry.setIndex( new BufferAttribute( indices, 1 ) ); + + geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) ); + + super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) ); + + /** + * The box being visualized. + * + * @type {Box3} + */ + this.box = box; + + this.type = 'Box3Helper'; + + this.geometry.computeBoundingSphere(); + + } + + updateMatrixWorld( force ) { + + const box = this.box; + + if ( box.isEmpty() ) return; + + box.getCenter( this.position ); + + box.getSize( this.scale ); + + this.scale.multiplyScalar( 0.5 ); + + super.updateMatrixWorld( force ); + + } + + /** + * Frees the GPU-related resources allocated by this instance. Call this + * method whenever this instance is no longer used in your app. + */ + dispose() { + + super.dispose(); + + this.geometry.dispose(); + this.material.dispose(); + + } + +} + +/** + * A helper object to visualize an instance of {@link Plane}. + * + * ```js + * const plane = new THREE.Plane( new THREE.Vector3( 1, 1, 0.2 ), 3 ); + * const helper = new THREE.PlaneHelper( plane, 1, 0xffff00 ); + * scene.add( helper ); + * ``` + * + * @augments Line + */ +class PlaneHelper extends Line { + + /** + * Constructs a new plane helper. + * + * @param {Plane} plane - The plane to be visualized. + * @param {number} [size=1] - The side length of plane helper. + * @param {number|Color|string} [hex=0xffff00] - The helper's color. + */ + constructor( plane, size = 1, hex = 0xffff00 ) { + + const color = hex; + + const positions = [ 1, -1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, 1, 0, -1, -1, 0, 1, -1, 0, 1, 1, 0 ]; + + const geometry = new BufferGeometry(); + geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) ); + geometry.computeBoundingSphere(); + + super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) ); + + this.type = 'PlaneHelper'; + + /** + * The plane being visualized. + * + * @type {Plane} + */ + this.plane = plane; + + /** + * The side length of plane helper. + * + * @type {number} + * @default 1 + */ + this.size = size; + + const positions2 = [ 1, 1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, -1, 0, 1, -1, 0 ]; + + const geometry2 = new BufferGeometry(); + geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) ); + geometry2.computeBoundingSphere(); + + this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) ); + + } + + updateMatrixWorld( force ) { + + this.position.set( 0, 0, 0 ); + + this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 ); + + this.lookAt( this.plane.normal ); + + this.translateZ( - this.plane.constant ); + + super.updateMatrixWorld( force ); + + } + + /** + * Updates the helper to match the position and direction of the + * light being visualized. + */ + dispose() { + + super.dispose(); + + this.geometry.dispose(); + this.material.dispose(); + this.children[ 0 ].geometry.dispose(); + this.children[ 0 ].material.dispose(); + + } + +} + +const _axis = /*@__PURE__*/ new Vector3(); +let _lineGeometry, _coneGeometry; + +/** + * An 3D arrow object for visualizing directions. + * + * ```js + * const dir = new THREE.Vector3( 1, 2, 0 ); + * + * //normalize the direction vector (convert to vector of length 1) + * dir.normalize(); + * + * const origin = new THREE.Vector3( 0, 0, 0 ); + * const length = 1; + * const hex = 0xffff00; + * + * const arrowHelper = new THREE.ArrowHelper( dir, origin, length, hex ); + * scene.add( arrowHelper ); + * ``` + * + * @augments Object3D + */ +class ArrowHelper extends Object3D { + + /** + * Constructs a new arrow helper. + * + * @param {Vector3} [dir=(0, 0, 1)] - The (normalized) direction vector. + * @param {Vector3} [origin=(0, 0, 0)] - Point at which the arrow starts. + * @param {number} [length=1] - Length of the arrow in world units. + * @param {(number|Color|string)} [color=0xffff00] - Color of the arrow. + * @param {number} [headLength=length*0.2] - The length of the head of the arrow. + * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow. + */ + constructor( dir = new Vector3( 0, 0, 1 ), origin = new Vector3( 0, 0, 0 ), length = 1, color = 0xffff00, headLength = length * 0.2, headWidth = headLength * 0.2 ) { + + super(); + + this.type = 'ArrowHelper'; + + if ( _lineGeometry === undefined ) { + + _lineGeometry = new BufferGeometry(); + _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) ); + + _coneGeometry = new ConeGeometry( 0.5, 1, 5, 1 ); + _coneGeometry.translate( 0, -0.5, 0 ); + + } + + this.position.copy( origin ); + + /** + * The line part of the arrow helper. + * + * @type {Line} + */ + this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) ); + this.line.matrixAutoUpdate = false; + this.add( this.line ); + + /** + * The cone part of the arrow helper. + * + * @type {Mesh} + */ + this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) ); + this.cone.matrixAutoUpdate = false; + this.add( this.cone ); + + this.setDirection( dir ); + this.setLength( length, headLength, headWidth ); + + } + + /** + * Sets the direction of the helper. + * + * @param {Vector3} dir - The normalized direction vector. + */ + setDirection( dir ) { + + // dir is assumed to be normalized + + if ( dir.y > 0.99999 ) { + + this.quaternion.set( 0, 0, 0, 1 ); + + } else if ( dir.y < -0.99999 ) { + + this.quaternion.set( 1, 0, 0, 0 ); + + } else { + + _axis.set( dir.z, 0, - dir.x ).normalize(); + + const radians = Math.acos( dir.y ); + + this.quaternion.setFromAxisAngle( _axis, radians ); + + } + + } + + /** + * Sets the length of the helper. + * + * @param {number} length - Length of the arrow in world units. + * @param {number} [headLength=length*0.2] - The length of the head of the arrow. + * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow. + */ + setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) { + + this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458 + this.line.updateMatrix(); + + this.cone.scale.set( headWidth, headLength, headWidth ); + this.cone.position.y = length; + this.cone.updateMatrix(); + + } + + /** + * Sets the color of the helper. + * + * @param {number|Color|string} color - The color to set. + */ + setColor( color ) { + + this.line.material.color.set( color ); + this.cone.material.color.set( color ); + + } + + copy( source ) { + + super.copy( source, false ); + + this.line.copy( source.line ); + this.cone.copy( source.cone ); + + return this; + + } + + /** + * Frees the GPU-related resources allocated by this instance. Call this + * method whenever this instance is no longer used in your app. + */ + dispose() { + + super.dispose(); + + this.line.geometry.dispose(); + this.line.material.dispose(); + this.cone.geometry.dispose(); + this.cone.material.dispose(); + + } + +} + +/** + * An axis object to visualize the 3 axes in a simple way. + * The X axis is red. The Y axis is green. The Z axis is blue. + * + * ```js + * const axesHelper = new THREE.AxesHelper( 5 ); + * scene.add( axesHelper ); + * ``` + * + * @augments LineSegments + */ +class AxesHelper extends LineSegments { + + /** + * Constructs a new axes helper. + * + * @param {number} [size=1] - Size of the lines representing the axes. + */ + constructor( size = 1 ) { + + const vertices = [ + 0, 0, 0, size, 0, 0, + 0, 0, 0, 0, size, 0, + 0, 0, 0, 0, 0, size + ]; + + const colors = [ + 1, 0, 0, 1, 0.6, 0, + 0, 1, 0, 0.6, 1, 0, + 0, 0, 1, 0, 0.6, 1 + ]; + + const geometry = new BufferGeometry(); + geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) ); + + const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } ); + + super( geometry, material ); + + this.type = 'AxesHelper'; + + } + + /** + * Defines the colors of the axes helper. + * + * @param {number|Color|string} xAxisColor - The color for the x axis. + * @param {number|Color|string} yAxisColor - The color for the y axis. + * @param {number|Color|string} zAxisColor - The color for the z axis. + * @return {AxesHelper} A reference to this axes helper. + */ + setColors( xAxisColor, yAxisColor, zAxisColor ) { + + const color = new Color(); + const array = this.geometry.attributes.color.array; + + color.set( xAxisColor ); + color.toArray( array, 0 ); + color.toArray( array, 3 ); + + color.set( yAxisColor ); + color.toArray( array, 6 ); + color.toArray( array, 9 ); + + color.set( zAxisColor ); + color.toArray( array, 12 ); + color.toArray( array, 15 ); + + this.geometry.attributes.color.needsUpdate = true; + + return this; + + } + + /** + * Frees the GPU-related resources allocated by this instance. Call this + * method whenever this instance is no longer used in your app. + */ + dispose() { + + super.dispose(); + + this.geometry.dispose(); + this.material.dispose(); + + } + +} + +/** + * This class is used to convert a series of paths to an array of + * shapes. It is specifically used in context of fonts and SVG. + */ +class ShapePath { + + /** + * Constructs a new shape path. + */ + constructor() { + + this.type = 'ShapePath'; + + /** + * The color of the shape. + * + * @type {Color} + */ + this.color = new Color(); + + /** + * The paths that have been generated for this shape. + * + * @type {Array} + * @default null + */ + this.subPaths = []; + + /** + * The current path that is being generated. + * + * @type {?Path} + * @default null + */ + this.currentPath = null; + + /** + * An object that can be used to store custom data about the shape path. + * Mainly used by SVGLoader to store style information. + * + * @type {Object} + */ + this.userData = {}; + + } + + /** + * Creates a new path and moves it current point to the given one. + * + * @param {number} x - The x coordinate. + * @param {number} y - The y coordinate. + * @return {ShapePath} A reference to this shape path. + */ + moveTo( x, y ) { + + this.currentPath = new Path(); + this.subPaths.push( this.currentPath ); + this.currentPath.moveTo( x, y ); + + return this; + + } + + /** + * Adds an instance of {@link LineCurve} to the path by connecting + * the current point with the given one. + * + * @param {number} x - The x coordinate of the end point. + * @param {number} y - The y coordinate of the end point. + * @return {ShapePath} A reference to this shape path. + */ + lineTo( x, y ) { + + this.currentPath.lineTo( x, y ); + + return this; + + } + + /** + * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting + * the current point with the given one. + * + * @param {number} aCPx - The x coordinate of the control point. + * @param {number} aCPy - The y coordinate of the control point. + * @param {number} aX - The x coordinate of the end point. + * @param {number} aY - The y coordinate of the end point. + * @return {ShapePath} A reference to this shape path. + */ + quadraticCurveTo( aCPx, aCPy, aX, aY ) { + + this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY ); + + return this; + + } + + /** + * Adds an instance of {@link CubicBezierCurve} to the path by connecting + * the current point with the given one. + * + * @param {number} aCP1x - The x coordinate of the first control point. + * @param {number} aCP1y - The y coordinate of the first control point. + * @param {number} aCP2x - The x coordinate of the second control point. + * @param {number} aCP2y - The y coordinate of the second control point. + * @param {number} aX - The x coordinate of the end point. + * @param {number} aY - The y coordinate of the end point. + * @return {ShapePath} A reference to this shape path. + */ + bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) { + + this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ); + + return this; + + } + + /** + * Adds an instance of {@link SplineCurve} to the path by connecting + * the current point with the given list of points. + * + * @param {Array} pts - An array of points in 2D space. + * @return {ShapePath} A reference to this shape path. + */ + splineThru( pts ) { + + this.currentPath.splineThru( pts ); + + return this; + + } + + /** + * Converts the paths into an array of shapes. + * + * @return {Array} An array of shapes. + */ + toShapes() { + + // Point-in-polygon test using the even-odd ray-casting rule. Valid for + // simple (non self-intersecting) polygons. + function pointInPolygon( p, polygon ) { + + let inside = false; + const n = polygon.length; + + for ( let i = 0, j = n - 1; i < n; j = i ++ ) { + + const a = polygon[ i ]; + const b = polygon[ j ]; + + if ( ( a.y > p.y ) !== ( b.y > p.y ) && + p.x < ( b.x - a.x ) * ( p.y - a.y ) / ( b.y - a.y ) + a.x ) { + + inside = ! inside; + + } + + } + + return inside; + + } + + // Returns a point guaranteed to be strictly inside the given simple + // polygon. First tries the bounding-box center; if that falls outside + // the polygon, casts a horizontal ray at the center's y and picks the + // midpoint between the first two sorted intercepts. + // + // Port of paper.js' Path#getInteriorPoint() + // https://github.com/paperjs/paper.js/blob/develop/src/path/PathItem.Boolean.js + function getInteriorPoint( polygon, boundingBox ) { + + const point = boundingBox.getCenter( new Vector2() ); + + if ( pointInPolygon( point, polygon ) ) return point; + + const y = point.y; + const intercepts = []; + const n = polygon.length; + + for ( let i = 0; i < n; i ++ ) { + + const a = polygon[ i ]; + const b = polygon[ ( i + 1 ) % n ]; + + // Half-open crossing rule — counts each vertex exactly once and + // skips horizontal edges. + if ( ( a.y > y ) !== ( b.y > y ) ) { + + const x = a.x + ( y - a.y ) * ( b.x - a.x ) / ( b.y - a.y ); + intercepts.push( x ); + + } + + } + + if ( intercepts.length > 1 ) { + + intercepts.sort( ( a, b ) => a - b ); + point.x = ( intercepts[ 0 ] + intercepts[ 1 ] ) / 2; + + } + + return point; + + } + + // Resolve fill-rule. Defaults to 'nonzero'. + let fillRule = ( this.userData.style && this.userData.style.fillRule ) || 'nonzero'; + + if ( fillRule !== 'nonzero' && fillRule !== 'evenodd' ) { + + warn( 'Fill-rule "' + fillRule + '" is not supported, falling back to "nonzero".' ); + fillRule = 'nonzero'; + + } + + // Predicate that decides whether a winding number falls inside the fill + // region, per the SVG fill-rule spec. Works for negative windings too, + // because JavaScript's bitwise AND preserves odd/even under two's + // complement. + const isInside = fillRule === 'nonzero' + ? ( w => w !== 0 ) + : ( w => ( w & 1 ) !== 0 ); + + // Build an entry per usable subpath. Self-winding follows the standard + // convention used by ShapeUtils: counter-clockwise (signed area > 0) + // contributes +1 to the winding number at an interior point, + // clockwise contributes -1. + const entries = []; + + for ( const subPath of this.subPaths ) { + + const points = subPath.getPoints(); + if ( points.length < 3 ) continue; + + const area = ShapeUtils.area( points ); + if ( area === 0 ) continue; + + const boundingBox = new Box2(); + for ( let i = 0; i < points.length; i ++ ) boundingBox.expandByPoint( points[ i ] ); + + entries.push( { + subPath: subPath, + points: points, + boundingBox: boundingBox, + interiorPoint: getInteriorPoint( points, boundingBox ), + absArea: Math.abs( area ), + winding: area < 0 ? -1 : 1, + container: null, + exclude: false, + role: null + } ); + + } + + // Sort by area descending. This guarantees that any subpath that could + // contain `entries[i]` is located at a smaller index and has already + // been processed when it's entries[i]'s turn. Port of paper.js' + // reorientPaths() algorithm. + entries.sort( ( a, b ) => b.absArea - a.absArea ); + + // Walk already-processed entries from closest-in-size to largest, + // stopping at the innermost container. Accumulate the container's + // cumulative winding into this entry's winding so that the final value + // equals the winding number at this entry's interior point. + // + // A subpath only contributes to the fill boundary when crossing it + // actually flips the "insideness" per the fill rule; otherwise it's a + // redundant overlap and gets excluded to avoid double-counting. + for ( let i = 0; i < entries.length; i ++ ) { + + const entry = entries[ i ]; + let containerWinding = 0; + + for ( let j = i - 1; j >= 0; j -- ) { + + const candidate = entries[ j ]; + + if ( ! candidate.boundingBox.containsBox( entry.boundingBox ) ) continue; + if ( ! pointInPolygon( entry.interiorPoint, candidate.points ) ) continue; + + entry.container = candidate.exclude ? candidate.container : candidate; + containerWinding = candidate.winding; + entry.winding += containerWinding; + break; + + } + + if ( isInside( entry.winding ) === isInside( containerWinding ) ) { + + entry.exclude = true; + + } + + } + + // Classify retained entries. An entry is an outer shape if it has no + // container or if its container is itself a hole (a solid nested inside + // a hole becomes a new top-level shape); otherwise it's a hole in its + // container. Entries were already sorted outermost-first, so each + // container's role is known by the time we look at it. + for ( const entry of entries ) { + + if ( entry.exclude ) continue; + entry.role = ( entry.container === null || entry.container.role === 'hole' ) ? 'outer' : 'hole'; + + } + + // Build Shapes for outers first, then attach holes to their container's + // Shape. + const shapes = []; + const shapeByEntry = new Map(); + + for ( const entry of entries ) { + + if ( entry.exclude || entry.role !== 'outer' ) continue; + + const shape = new Shape(); + shape.curves = entry.subPath.curves; + shapes.push( shape ); + shapeByEntry.set( entry, shape ); + + } + + for ( const entry of entries ) { + + if ( entry.exclude || entry.role !== 'hole' ) continue; + + const shape = shapeByEntry.get( entry.container ); + if ( ! shape ) continue; + + const hole = new Path(); + hole.curves = entry.subPath.curves; + shape.holes.push( hole ); + + } + + return shapes; + + + } + +} + +/** + * Abstract base class for controls. + * + * @abstract + * @augments EventDispatcher + */ +class Controls extends EventDispatcher { + + /** + * Constructs a new controls instance. + * + * @param {Object3D} object - The object that is managed by the controls. + * @param {?HTMLElement} domElement - The HTML element used for event listeners. + */ + constructor( object, domElement = null ) { + + super(); + + /** + * The object that is managed by the controls. + * + * @type {Object3D} + */ + this.object = object; + + /** + * The HTML element used for event listeners. + * + * @type {?HTMLElement} + * @default null + */ + this.domElement = domElement; + + /** + * Whether the controls responds to user input or not. + * + * @type {boolean} + * @default true + */ + this.enabled = true; + + /** + * The internal state of the controls. + * + * @type {number} + * @default -1 + */ + this.state = -1; + + /** + * This object defines the keyboard input of the controls. + * + * @type {Object} + */ + this.keys = {}; + + /** + * This object defines what type of actions are assigned to the available mouse buttons. + * It depends on the control implementation what kind of mouse buttons and actions are supported. + * + * @type {{LEFT: ?number, MIDDLE: ?number, RIGHT: ?number}} + */ + this.mouseButtons = { LEFT: null, MIDDLE: null, RIGHT: null }; + + /** + * This object defines what type of actions are assigned to what kind of touch interaction. + * It depends on the control implementation what kind of touch interaction and actions are supported. + * + * @type {{ONE: ?number, TWO: ?number}} + */ + this.touches = { ONE: null, TWO: null }; + + } + + /** + * Connects the controls to the DOM. This method has so called "side effects" since + * it adds the module's event listeners to the DOM. + * + * @param {HTMLElement} element - The DOM element to connect to. + */ + connect( element ) { + + if ( this.domElement !== null ) this.disconnect(); + + this.domElement = element; + + } + + /** + * Disconnects the controls from the DOM. + */ + disconnect() {} + + /** + * Call this method if you no longer want use to the controls. It frees all internal + * resources and removes all event listeners. + */ + dispose() {} + + /** + * Controls should implement this method if they have to update their internal state + * per simulation step. + * + * @param {number} [delta] - The time delta in seconds. + */ + update( /* delta */ ) {} + +} + +/** + * Scales the texture as large as possible within its surface without cropping + * or stretching the texture. The method preserves the original aspect ratio of + * the texture. Akin to CSS `object-fit: contain` + * + * @param {Texture} texture - The texture. + * @param {number} aspect - The texture's aspect ratio. + * @return {Texture} The updated texture. + */ +function contain( texture, aspect ) { + + const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1; + + if ( imageAspect > aspect ) { + + texture.repeat.x = 1; + texture.repeat.y = imageAspect / aspect; + + texture.offset.x = 0; + texture.offset.y = ( 1 - texture.repeat.y ) / 2; + + } else { + + texture.repeat.x = aspect / imageAspect; + texture.repeat.y = 1; + + texture.offset.x = ( 1 - texture.repeat.x ) / 2; + texture.offset.y = 0; + + } + + return texture; + +} + +/** + * Scales the texture to the smallest possible size to fill the surface, leaving + * no empty space. The method preserves the original aspect ratio of the texture. + * Akin to CSS `object-fit: cover`. + * + * @param {Texture} texture - The texture. + * @param {number} aspect - The texture's aspect ratio. + * @return {Texture} The updated texture. + */ +function cover( texture, aspect ) { + + const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1; + + if ( imageAspect > aspect ) { + + texture.repeat.x = aspect / imageAspect; + texture.repeat.y = 1; + + texture.offset.x = ( 1 - texture.repeat.x ) / 2; + texture.offset.y = 0; + + } else { + + texture.repeat.x = 1; + texture.repeat.y = imageAspect / aspect; + + texture.offset.x = 0; + texture.offset.y = ( 1 - texture.repeat.y ) / 2; + + } + + return texture; + +} + +/** + * Configures the texture to the default transformation. Akin to CSS `object-fit: fill`. + * + * @param {Texture} texture - The texture. + * @return {Texture} The updated texture. + */ +function fill( texture ) { + + texture.repeat.x = 1; + texture.repeat.y = 1; + + texture.offset.x = 0; + texture.offset.y = 0; + + return texture; + +} + +/** + * Determines how many bytes must be used to represent the texture. + * + * @param {number} width - The width of the texture. + * @param {number} height - The height of the texture. + * @param {number} format - The texture's format. + * @param {number} type - The texture's type. + * @return {number} The byte length. + */ +function getByteLength( width, height, format, type ) { + + const typeByteLength = getTextureTypeByteLength( type ); + + switch ( format ) { + + // https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glTexImage2D.xhtml + case AlphaFormat: + return width * height; + case RedFormat: + return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength; + case RedIntegerFormat: + return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength; + case RGFormat: + return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength; + case RGIntegerFormat: + return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength; + case RGBFormat: + return ( ( width * height * 3 ) / typeByteLength.components ) * typeByteLength.byteLength; + case RGBAFormat: + return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength; + case RGBAIntegerFormat: + return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength; + + // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_s3tc_srgb/ + case RGB_S3TC_DXT1_Format: + case RGBA_S3TC_DXT1_Format: + return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8; + case RGBA_S3TC_DXT3_Format: + case RGBA_S3TC_DXT5_Format: + return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16; + + // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_pvrtc/ + case RGB_PVRTC_2BPPV1_Format: + case RGBA_PVRTC_2BPPV1_Format: + return ( Math.max( width, 16 ) * Math.max( height, 8 ) ) / 4; + case RGB_PVRTC_4BPPV1_Format: + case RGBA_PVRTC_4BPPV1_Format: + return ( Math.max( width, 8 ) * Math.max( height, 8 ) ) / 2; + + // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_etc/ + case RGB_ETC1_Format: + case RGB_ETC2_Format: + case R11_EAC_Format: + case SIGNED_R11_EAC_Format: + return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8; + case RGBA_ETC2_EAC_Format: + case RG11_EAC_Format: + case SIGNED_RG11_EAC_Format: + return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16; + + // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_astc/ + case RGBA_ASTC_4x4_Format: + return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16; + case RGBA_ASTC_5x4_Format: + return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 3 ) / 4 ) * 16; + case RGBA_ASTC_5x5_Format: + return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 4 ) / 5 ) * 16; + case RGBA_ASTC_6x5_Format: + return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 4 ) / 5 ) * 16; + case RGBA_ASTC_6x6_Format: + return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 5 ) / 6 ) * 16; + case RGBA_ASTC_8x5_Format: + return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 4 ) / 5 ) * 16; + case RGBA_ASTC_8x6_Format: + return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 5 ) / 6 ) * 16; + case RGBA_ASTC_8x8_Format: + return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 7 ) / 8 ) * 16; + case RGBA_ASTC_10x5_Format: + return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 4 ) / 5 ) * 16; + case RGBA_ASTC_10x6_Format: + return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 5 ) / 6 ) * 16; + case RGBA_ASTC_10x8_Format: + return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 7 ) / 8 ) * 16; + case RGBA_ASTC_10x10_Format: + return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 9 ) / 10 ) * 16; + case RGBA_ASTC_12x10_Format: + return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 9 ) / 10 ) * 16; + case RGBA_ASTC_12x12_Format: + return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 11 ) / 12 ) * 16; + + // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_bptc/ + case RGBA_BPTC_Format: + case RGB_BPTC_SIGNED_Format: + case RGB_BPTC_UNSIGNED_Format: + return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16; + + // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_rgtc/ + case RED_RGTC1_Format: + case SIGNED_RED_RGTC1_Format: + return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 8; + case RED_GREEN_RGTC2_Format: + case SIGNED_RED_GREEN_RGTC2_Format: + return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16; + + } + + throw new Error( + `Unable to determine texture byte length for ${format} format.`, + ); + +} + +function getTextureTypeByteLength( type ) { + + switch ( type ) { + + case UnsignedByteType: + case ByteType: + return { byteLength: 1, components: 1 }; + case UnsignedShortType: + case ShortType: + case HalfFloatType: + return { byteLength: 2, components: 1 }; + case UnsignedShort4444Type: + case UnsignedShort5551Type: + return { byteLength: 2, components: 4 }; + case UnsignedIntType: + case IntType: + case FloatType: + return { byteLength: 4, components: 1 }; + case UnsignedInt5999Type: + case UnsignedInt101111Type: + return { byteLength: 4, components: 3 }; + + } + + throw new Error( `THREE.TextureUtils: Unknown texture type ${type}.` ); + +} + +/** + * A class containing utility functions for textures. + * + * @hideconstructor + */ +class TextureUtils { + + /** + * Scales the texture as large as possible within its surface without cropping + * or stretching the texture. The method preserves the original aspect ratio of + * the texture. Akin to CSS `object-fit: contain` + * + * @param {Texture} texture - The texture. + * @param {number} aspect - The texture's aspect ratio. + * @return {Texture} The updated texture. + */ + static contain( texture, aspect ) { + + return contain( texture, aspect ); + + } + + /** + * Scales the texture to the smallest possible size to fill the surface, leaving + * no empty space. The method preserves the original aspect ratio of the texture. + * Akin to CSS `object-fit: cover`. + * + * @param {Texture} texture - The texture. + * @param {number} aspect - The texture's aspect ratio. + * @return {Texture} The updated texture. + */ + static cover( texture, aspect ) { + + return cover( texture, aspect ); + + } + + /** + * Configures the texture to the default transformation. Akin to CSS `object-fit: fill`. + * + * @param {Texture} texture - The texture. + * @return {Texture} The updated texture. + */ + static fill( texture ) { + + return fill( texture ); + + } + + /** + * Determines how many bytes must be used to represent the texture. + * + * @param {number} width - The width of the texture. + * @param {number} height - The height of the texture. + * @param {number} format - The texture's format. + * @param {number} type - The texture's type. + * @return {number} The byte length. + */ + static getByteLength( width, height, format, type ) { + + return getByteLength( width, height, format, type ); + + } + +} + +if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) { + + __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: { + revision: REVISION, + } } ) ); + +} + +if ( typeof window !== 'undefined' ) { + + if ( window.__THREE__ ) { + + warn( 'WARNING: Multiple instances of Three.js being imported.' ); + + } else { + + window.__THREE__ = REVISION; + + } + +} + +export { ACESFilmicToneMapping, AddEquation, AddOperation, AdditiveAnimationBlendMode, AdditiveBlending, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AnimationAction, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrayCamera, ArrowHelper, AttachedBindMode, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, BackSide, BasicDepthPacking, BasicShadowMap, BatchedMesh, BezierInterpolant, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxGeometry, BoxHelper, BufferAttribute, BufferGeometry, BufferGeometryLoader, ByteType, Cache, Camera, CameraHelper, CanvasTexture, CapsuleGeometry, CatmullRomCurve3, CineonToneMapping, CircleGeometry, ClampToEdgeWrapping, Clock, Color, ColorKeyframeTrack, ColorManagement, Compatibility, CompressedArrayTexture, CompressedCubeTexture, CompressedTexture, CompressedTextureLoader, ConeGeometry, ConstantAlphaFactor, ConstantColorFactor, Controls, CubeCamera, CubeDepthTexture, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureLoader, CubeUVReflectionMapping, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceBack, CullFaceFront, CullFaceFrontBack, CullFaceNone, Curve, CurvePath, CustomBlending, CustomToneMapping, CylinderGeometry, Cylindrical, Data3DTexture, DataArrayTexture, DataTexture, DataTextureLoader, DataUtils, DecrementStencilOp, DecrementWrapStencilOp, DefaultLoadingManager, DepthFormat, DepthStencilFormat, DepthTexture, DetachedBindMode, DirectionalLight, DirectionalLightHelper, DiscreteInterpolant, DodecahedronGeometry, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicCopyUsage, DynamicDrawUsage, DynamicReadUsage, EdgesGeometry, EllipseCurve, EqualCompare, EqualDepth, EqualStencilFunc, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExternalTexture, ExtrudeGeometry, FileLoader, Float16BufferAttribute, Float32BufferAttribute, FloatType, Fog, FogExp2, FramebufferTexture, FrontSide, Frustum, FrustumArray, GLBufferAttribute, GLSL1, GLSL3, GreaterCompare, GreaterDepth, GreaterEqualCompare, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, GridHelper, Group, HTMLTexture, HalfFloatType, HemisphereLight, HemisphereLightHelper, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, IncrementStencilOp, IncrementWrapStencilOp, InstancedBufferAttribute, InstancedBufferGeometry, InstancedInterleavedBuffer, InstancedMesh, Int16BufferAttribute, Int32BufferAttribute, Int8BufferAttribute, IntType, InterleavedBuffer, InterleavedBufferAttribute, Interpolant, InterpolateBezier, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, InterpolationSamplingMode, InterpolationSamplingType, InvertStencilOp, KeepStencilOp, KeyframeTrack, LOD, LatheGeometry, Layers, LessCompare, LessDepth, LessEqualCompare, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, Light, LightProbe, LightShadow, Line, Line3, LineBasicMaterial, LineCurve, LineCurve3, LineDashedMaterial, LineLoop, LineSegments, LinearFilter, LinearInterpolant, LinearMipMapLinearFilter, LinearMipMapNearestFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearSRGBColorSpace, LinearToneMapping, LinearTransfer, Loader, LoaderUtils, LoadingManager, LoopOnce, LoopPingPong, LoopRepeat, MOUSE, Material, MaterialBlending, MaterialLoader, MathUtils, Matrix2, Matrix3, Matrix4, MaxEquation, Mesh, MeshBasicMaterial, MeshDepthMaterial, MeshDistanceMaterial, MeshLambertMaterial, MeshMatcapMaterial, MeshNormalMaterial, MeshPhongMaterial, MeshPhysicalMaterial, MeshStandardMaterial, MeshToonMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeutralToneMapping, NeverCompare, NeverDepth, NeverStencilFunc, NoBlending, NoColorSpace, NoNormalPacking, NoToneMapping, NormalAnimationBlendMode, NormalBlending, NormalGAPacking, NormalRGPacking, NotEqualCompare, NotEqualDepth, NotEqualStencilFunc, NumberKeyframeTrack, Object3D, ObjectLoader, ObjectSpaceNormalMap, OctahedronGeometry, OneFactor, OneMinusConstantAlphaFactor, OneMinusConstantColorFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OrthographicCamera, PCFShadowMap, PCFSoftShadowMap, Path, PerspectiveCamera, Plane, PlaneGeometry, PlaneHelper, PointLight, PointLightHelper, Points, PointsMaterial, PolarGridHelper, PolyhedronGeometry, PositionalAudio, PropertyBinding, PropertyMixer, QuadraticBezierCurve, QuadraticBezierCurve3, Quaternion, QuaternionKeyframeTrack, QuaternionLinearInterpolant, R11_EAC_Format, RAD2DEG, RED_GREEN_RGTC2_Format, RED_RGTC1_Format, REVISION, RG11_EAC_Format, RGBADepthPacking, RGBAFormat, RGBAIntegerFormat, RGBA_ASTC_10x10_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_BPTC_Format, RGBA_ETC2_EAC_Format, RGBA_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGBDepthPacking, RGBFormat, RGBIntegerFormat, RGB_BPTC_SIGNED_Format, RGB_BPTC_UNSIGNED_Format, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGDepthPacking, RGFormat, RGIntegerFormat, RawShaderMaterial, Ray, Raycaster, RectAreaLight, RedFormat, RedIntegerFormat, ReinhardToneMapping, RenderObjectRefreshType, RenderTarget, RenderTarget3D, RepeatWrapping, ReplaceStencilOp, ReverseSubtractEquation, ReversedDepthFuncs, RingGeometry, SIGNED_R11_EAC_Format, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SIGNED_RG11_EAC_Format, SRGBColorSpace, SRGBTransfer, Scene, ShaderMaterial, ShadowMaterial, Shape, ShapeGeometry, ShapePath, ShapeUtils, ShortType, Skeleton, SkeletonHelper, SkinnedMesh, Source, Sphere, SphereGeometry, Spherical, SphericalHarmonics3, SplineCurve, SpotLight, SpotLightHelper, Sprite, SpriteMaterial, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StaticCopyUsage, StaticDrawUsage, StaticReadUsage, StereoCamera, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, SubtractEquation, SubtractiveBlending, TOUCH, TangentSpaceNormalMap, TetrahedronGeometry, Texture, TextureLoader, TextureSource, TextureUtils, Timer, TimestampQuery, TorusGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeGeometry, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform, UniformsGroup, UniformsUtils, UnsignedByteType, UnsignedInt101111Type, UnsignedInt248Type, UnsignedInt5999Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, VSMShadowMap, Vector2, Vector3, Vector4, VectorKeyframeTrack, VideoFrameTexture, VideoTexture, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGLCoordinateSystem, WebGLRenderTarget, WebGPUCoordinateSystem, WebXRController, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroFactor, ZeroSlopeEnding, ZeroStencilOp, cloneUniforms, createCanvasElement, createElementNS, error, getByteLength, getConsoleFunction, getUnlitUniformColorSpace, isTypedArray, log, mergeUniforms, probeAsync, setConsoleFunction, warn, warnOnce, yieldToMain }; diff --git a/module-test/vendor/three/three.module.js b/module-test/vendor/three/three.module.js new file mode 100644 index 00000000000..c52087acfab --- /dev/null +++ b/module-test/vendor/three/three.module.js @@ -0,0 +1,19719 @@ +/** + * @license + * Copyright 2010-2026 Three.js Authors + * SPDX-License-Identifier: MIT + */ +import { Matrix3, Vector2, Color, Vector3, mergeUniforms, CubeUVReflectionMapping, Mesh, BoxGeometry, ShaderMaterial, BackSide, cloneUniforms, Matrix4, ColorManagement, SRGBTransfer, PlaneGeometry, FrontSide, getUnlitUniformColorSpace, IntType, warn, HalfFloatType, UnsignedByteType, FloatType, RGBAFormat, Plane, CubeReflectionMapping, CubeRefractionMapping, BufferGeometry, OrthographicCamera, PerspectiveCamera, NoToneMapping, MeshBasicMaterial, NoBlending, WebGLRenderTarget, BufferAttribute, LinearSRGBColorSpace, LinearFilter, CubeTexture, LinearMipmapLinearFilter, CubeCamera, EquirectangularReflectionMapping, EquirectangularRefractionMapping, warnOnce, Uint32BufferAttribute, Uint16BufferAttribute, error, DataArrayTexture, Vector4, Float32BufferAttribute, RawShaderMaterial, CustomToneMapping, NeutralToneMapping, AgXToneMapping, ACESFilmicToneMapping, CineonToneMapping, ReinhardToneMapping, LinearToneMapping, Data3DTexture, GreaterEqualCompare, LessEqualCompare, DepthTexture, Texture, GLSL3, VSMShadowMap, PCFShadowMap, AddOperation, MixOperation, MultiplyOperation, LinearTransfer, UniformsUtils, DoubleSide, NormalBlending, TangentSpaceNormalMap, ObjectSpaceNormalMap, Layers, RGFormat, RG11_EAC_Format, RED_GREEN_RGTC2_Format, MeshDepthMaterial, MeshDistanceMaterial, PCFSoftShadowMap, DepthFormat, NearestFilter, CubeDepthTexture, UnsignedIntType, Frustum, LessEqualDepth, ReverseSubtractEquation, SubtractEquation, AddEquation, OneMinusConstantAlphaFactor, ConstantAlphaFactor, OneMinusConstantColorFactor, ConstantColorFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, DstAlphaFactor, DstColorFactor, SrcAlphaSaturateFactor, SrcAlphaFactor, SrcColorFactor, OneFactor, ZeroFactor, NotEqualDepth, GreaterDepth, GreaterEqualDepth, EqualDepth, LessDepth, AlwaysDepth, NeverDepth, CullFaceNone, CullFaceBack, CullFaceFront, CustomBlending, MultiplyBlending, SubtractiveBlending, AdditiveBlending, ReversedDepthFuncs, MinEquation, MaxEquation, MirroredRepeatWrapping, ClampToEdgeWrapping, RepeatWrapping, LinearMipmapNearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NotEqualCompare, GreaterCompare, EqualCompare, LessCompare, AlwaysCompare, NeverCompare, NoColorSpace, DepthStencilFormat, getByteLength, UnsignedInt248Type, UnsignedShortType, createElementNS, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedInt5999Type, UnsignedInt101111Type, ByteType, ShortType, AlphaFormat, RGBFormat, RedFormat, RedIntegerFormat, RGIntegerFormat, RGBAIntegerFormat, RGB_S3TC_DXT1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGB_PVRTC_4BPPV1_Format, RGB_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_PVRTC_2BPPV1_Format, RGB_ETC1_Format, RGB_ETC2_Format, RGBA_ETC2_EAC_Format, R11_EAC_Format, SIGNED_R11_EAC_Format, SIGNED_RG11_EAC_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_10x10_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_BPTC_Format, RGB_BPTC_SIGNED_Format, RGB_BPTC_UNSIGNED_Format, RED_RGTC1_Format, SIGNED_RED_RGTC1_Format, SIGNED_RED_GREEN_RGTC2_Format, ExternalTexture, EventDispatcher, ArrayCamera, WebXRController, RAD2DEG, DataTexture, createCanvasElement, SRGBColorSpace, REVISION, log, WebGLCoordinateSystem, probeAsync } from './three.core.js'; +export { AdditiveAnimationBlendMode, AlwaysStencilFunc, AmbientLight, AnimationAction, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrowHelper, AttachedBindMode, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, BasicDepthPacking, BasicShadowMap, BatchedMesh, BezierInterpolant, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxHelper, BufferGeometryLoader, Cache, Camera, CameraHelper, CanvasTexture, CapsuleGeometry, CatmullRomCurve3, CircleGeometry, Clock, ColorKeyframeTrack, Compatibility, CompressedArrayTexture, CompressedCubeTexture, CompressedTexture, CompressedTextureLoader, ConeGeometry, Controls, CubeTextureLoader, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceFrontBack, Curve, CurvePath, CylinderGeometry, Cylindrical, DataTextureLoader, DataUtils, DecrementStencilOp, DecrementWrapStencilOp, DefaultLoadingManager, DetachedBindMode, DirectionalLight, DirectionalLightHelper, DiscreteInterpolant, DodecahedronGeometry, DynamicCopyUsage, DynamicDrawUsage, DynamicReadUsage, EdgesGeometry, EllipseCurve, EqualStencilFunc, Euler, ExtrudeGeometry, FileLoader, Float16BufferAttribute, Fog, FogExp2, FramebufferTexture, FrustumArray, GLBufferAttribute, GLSL1, GreaterEqualStencilFunc, GreaterStencilFunc, GridHelper, Group, HTMLTexture, HemisphereLight, HemisphereLightHelper, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, IncrementStencilOp, IncrementWrapStencilOp, InstancedBufferAttribute, InstancedBufferGeometry, InstancedInterleavedBuffer, InstancedMesh, Int16BufferAttribute, Int32BufferAttribute, Int8BufferAttribute, InterleavedBuffer, InterleavedBufferAttribute, Interpolant, InterpolateBezier, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, InterpolationSamplingMode, InterpolationSamplingType, InvertStencilOp, KeepStencilOp, KeyframeTrack, LOD, LatheGeometry, LessEqualStencilFunc, LessStencilFunc, Light, LightProbe, LightShadow, Line, Line3, LineBasicMaterial, LineCurve, LineCurve3, LineDashedMaterial, LineLoop, LineSegments, LinearInterpolant, LinearMipMapLinearFilter, LinearMipMapNearestFilter, Loader, LoaderUtils, LoadingManager, LoopOnce, LoopPingPong, LoopRepeat, MOUSE, Material, MaterialBlending, MaterialLoader, MathUtils, Matrix2, MeshLambertMaterial, MeshMatcapMaterial, MeshNormalMaterial, MeshPhongMaterial, MeshPhysicalMaterial, MeshStandardMaterial, MeshToonMaterial, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NeverStencilFunc, NoNormalPacking, NormalAnimationBlendMode, NormalGAPacking, NormalRGPacking, NotEqualStencilFunc, NumberKeyframeTrack, Object3D, ObjectLoader, OctahedronGeometry, Path, PlaneHelper, PointLight, PointLightHelper, Points, PointsMaterial, PolarGridHelper, PolyhedronGeometry, PositionalAudio, PropertyBinding, PropertyMixer, QuadraticBezierCurve, QuadraticBezierCurve3, Quaternion, QuaternionKeyframeTrack, QuaternionLinearInterpolant, RGBADepthPacking, RGBDepthPacking, RGBIntegerFormat, RGDepthPacking, Ray, Raycaster, RectAreaLight, RenderObjectRefreshType, RenderTarget, RenderTarget3D, ReplaceStencilOp, RingGeometry, Scene, ShadowMaterial, Shape, ShapeGeometry, ShapePath, ShapeUtils, Skeleton, SkeletonHelper, SkinnedMesh, Source, Sphere, SphereGeometry, Spherical, SphericalHarmonics3, SplineCurve, SpotLight, SpotLightHelper, Sprite, SpriteMaterial, StaticCopyUsage, StaticDrawUsage, StaticReadUsage, StereoCamera, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, TOUCH, TetrahedronGeometry, TextureLoader, TextureSource, TextureUtils, Timer, TimestampQuery, TorusGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeGeometry, UVMapping, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform, UniformsGroup, VectorKeyframeTrack, VideoFrameTexture, VideoTexture, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGPUCoordinateSystem, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroSlopeEnding, ZeroStencilOp, getConsoleFunction, setConsoleFunction } from './three.core.js'; + +function WebGLAnimation() { + + let context = null; + let isAnimating = false; + let animationLoop = null; + let requestId = null; + + function onAnimationFrame( time, frame ) { + + requestId = context.requestAnimationFrame( onAnimationFrame ); + + animationLoop( time, frame ); + + } + + return { + + start: function () { + + if ( isAnimating === true ) return; + if ( animationLoop === null ) return; + if ( context === null ) return; + + requestId = context.requestAnimationFrame( onAnimationFrame ); + + isAnimating = true; + + }, + + stop: function () { + + if ( context !== null ) context.cancelAnimationFrame( requestId ); + + isAnimating = false; + + }, + + setAnimationLoop: function ( callback ) { + + animationLoop = callback; + + }, + + setContext: function ( value ) { + + context = value; + + } + + }; + +} + +function WebGLAttributes( gl ) { + + const buffers = new WeakMap(); + + function createBuffer( attribute, bufferType ) { + + const array = attribute.array; + const usage = attribute.usage; + const size = array.byteLength; + + const buffer = gl.createBuffer(); + + gl.bindBuffer( bufferType, buffer ); + gl.bufferData( bufferType, array, usage ); + + attribute.onUploadCallback(); + + let type; + + if ( array instanceof Float32Array ) { + + type = gl.FLOAT; + + } else if ( typeof Float16Array !== 'undefined' && array instanceof Float16Array ) { + + type = gl.HALF_FLOAT; + + } else if ( array instanceof Uint16Array ) { + + if ( attribute.isFloat16BufferAttribute ) { + + type = gl.HALF_FLOAT; + + } else { + + type = gl.UNSIGNED_SHORT; + + } + + } else if ( array instanceof Int16Array ) { + + type = gl.SHORT; + + } else if ( array instanceof Uint32Array ) { + + type = gl.UNSIGNED_INT; + + } else if ( array instanceof Int32Array ) { + + type = gl.INT; + + } else if ( array instanceof Int8Array ) { + + type = gl.BYTE; + + } else if ( array instanceof Uint8Array ) { + + type = gl.UNSIGNED_BYTE; + + } else if ( array instanceof Uint8ClampedArray ) { + + type = gl.UNSIGNED_BYTE; + + } else { + + throw new Error( 'THREE.WebGLAttributes: Unsupported buffer data format: ' + array ); + + } + + return { + buffer: buffer, + type: type, + bytesPerElement: array.BYTES_PER_ELEMENT, + version: attribute.version, + size: size + }; + + } + + function updateBuffer( buffer, attribute, bufferType ) { + + const array = attribute.array; + const updateRanges = attribute.updateRanges; + + gl.bindBuffer( bufferType, buffer ); + + if ( updateRanges.length === 0 ) { + + // Not using update ranges + gl.bufferSubData( bufferType, 0, array ); + + } else { + + // Before applying update ranges, we merge any adjacent / overlapping + // ranges to reduce load on `gl.bufferSubData`. Empirically, this has led + // to performance improvements for applications which make heavy use of + // update ranges. Likely due to GPU command overhead. + // + // Note that to reduce garbage collection between frames, we merge the + // update ranges in-place. This is safe because this method will clear the + // update ranges once updated. + + updateRanges.sort( ( a, b ) => a.start - b.start ); + + // To merge the update ranges in-place, we work from left to right in the + // existing updateRanges array, merging ranges. This may result in a final + // array which is smaller than the original. This index tracks the last + // index representing a merged range, any data after this index can be + // trimmed once the merge algorithm is completed. + let mergeIndex = 0; + + for ( let i = 1; i < updateRanges.length; i ++ ) { + + const previousRange = updateRanges[ mergeIndex ]; + const range = updateRanges[ i ]; + + // We add one here to merge adjacent ranges. This is safe because ranges + // operate over positive integers. + if ( range.start <= previousRange.start + previousRange.count + 1 ) { + + previousRange.count = Math.max( + previousRange.count, + range.start + range.count - previousRange.start + ); + + } else { + + ++ mergeIndex; + updateRanges[ mergeIndex ] = range; + + } + + } + + // Trim the array to only contain the merged ranges. + updateRanges.length = mergeIndex + 1; + + for ( let i = 0, l = updateRanges.length; i < l; i ++ ) { + + const range = updateRanges[ i ]; + + gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT, + array, range.start, range.count ); + + } + + attribute.clearUpdateRanges(); + + } + + attribute.onUploadCallback(); + + } + + // + + function get( attribute ) { + + if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data; + + return buffers.get( attribute ); + + } + + function remove( attribute ) { + + if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data; + + const data = buffers.get( attribute ); + + if ( data ) { + + gl.deleteBuffer( data.buffer ); + + buffers.delete( attribute ); + + } + + } + + function update( attribute, bufferType ) { + + if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data; + + if ( attribute.isGLBufferAttribute ) { + + const cached = buffers.get( attribute ); + + if ( ! cached || cached.version < attribute.version ) { + + buffers.set( attribute, { + buffer: attribute.buffer, + type: attribute.type, + bytesPerElement: attribute.elementSize, + version: attribute.version + } ); + + } + + return; + + } + + const data = buffers.get( attribute ); + + if ( data === undefined ) { + + buffers.set( attribute, createBuffer( attribute, bufferType ) ); + + } else if ( data.version < attribute.version ) { + + if ( data.size !== attribute.array.byteLength ) { + + throw new Error( 'THREE.WebGLAttributes: The size of the buffer attribute\'s array buffer does not match the original size. Resizing buffer attributes is not supported.' ); + + } + + updateBuffer( data.buffer, attribute, bufferType ); + + data.version = attribute.version; + + } + + } + + return { + + get: get, + remove: remove, + update: update + + }; + +} + +var alphahash_fragment = "#ifdef USE_ALPHAHASH\n\tif ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;\n#endif"; + +var alphahash_pars_fragment = "#ifdef USE_ALPHAHASH\n\tconst float ALPHA_HASH_SCALE = 0.05;\n\tfloat hash2D( vec2 value ) {\n\t\treturn fract( 1.0e4 * sin( 17.0 * value.x + 0.1 * value.y ) * ( 0.1 + abs( sin( 13.0 * value.y + value.x ) ) ) );\n\t}\n\tfloat hash3D( vec3 value ) {\n\t\treturn hash2D( vec2( hash2D( value.xy ), value.z ) );\n\t}\n\tfloat getAlphaHashThreshold( vec3 position ) {\n\t\tfloat maxDeriv = max(\n\t\t\tlength( dFdx( position.xyz ) ),\n\t\t\tlength( dFdy( position.xyz ) )\n\t\t);\n\t\tfloat pixScale = 1.0 / ( ALPHA_HASH_SCALE * maxDeriv );\n\t\tvec2 pixScales = vec2(\n\t\t\texp2( floor( log2( pixScale ) ) ),\n\t\t\texp2( ceil( log2( pixScale ) ) )\n\t\t);\n\t\tvec2 alpha = vec2(\n\t\t\thash3D( floor( pixScales.x * position.xyz ) ),\n\t\t\thash3D( floor( pixScales.y * position.xyz ) )\n\t\t);\n\t\tfloat lerpFactor = fract( log2( pixScale ) );\n\t\tfloat x = ( 1.0 - lerpFactor ) * alpha.x + lerpFactor * alpha.y;\n\t\tfloat a = min( lerpFactor, 1.0 - lerpFactor );\n\t\tvec3 cases = vec3(\n\t\t\tx * x / ( 2.0 * a * ( 1.0 - a ) ),\n\t\t\t( x - 0.5 * a ) / ( 1.0 - a ),\n\t\t\t1.0 - ( ( 1.0 - x ) * ( 1.0 - x ) / ( 2.0 * a * ( 1.0 - a ) ) )\n\t\t);\n\t\tfloat threshold = ( x < ( 1.0 - a ) )\n\t\t\t? ( ( x < a ) ? cases.x : cases.y )\n\t\t\t: cases.z;\n\t\treturn clamp( threshold , 1.0e-6, 1.0 );\n\t}\n#endif"; + +var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;\n#endif"; + +var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif"; + +var alphatest_fragment = "#ifdef USE_ALPHATEST\n\t#ifdef ALPHA_TO_COVERAGE\n\tdiffuseColor.a = smoothstep( alphaTest, alphaTest + fwidth( diffuseColor.a ), diffuseColor.a );\n\tif ( diffuseColor.a == 0.0 ) discard;\n\t#else\n\tif ( diffuseColor.a < alphaTest ) discard;\n\t#endif\n#endif"; + +var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif"; + +var aomap_fragment = "#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vAoMapUv ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_CLEARCOAT ) \n\t\tclearcoatSpecularIndirect *= ambientOcclusion;\n\t#endif\n\t#if defined( USE_SHEEN ) \n\t\tsheenSpecularIndirect *= ambientOcclusion;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD )\n\t\tfloat dotNV = saturate( dot( geometryNormal, geometryViewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );\n\t#endif\n#endif"; + +var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif"; + +var batching_pars_vertex = "#ifdef USE_BATCHING\n\t#if ! defined( GL_ANGLE_multi_draw )\n\t#define gl_DrawID _gl_DrawID\n\tuniform int _gl_DrawID;\n\t#endif\n\tuniform highp sampler2D batchingTexture;\n\tuniform highp usampler2D batchingIdTexture;\n\tmat4 getBatchingMatrix( const in float i ) {\n\t\tint size = textureSize( batchingTexture, 0 ).x;\n\t\tint j = int( i ) * 4;\n\t\tint x = j % size;\n\t\tint y = j / size;\n\t\tvec4 v1 = texelFetch( batchingTexture, ivec2( x, y ), 0 );\n\t\tvec4 v2 = texelFetch( batchingTexture, ivec2( x + 1, y ), 0 );\n\t\tvec4 v3 = texelFetch( batchingTexture, ivec2( x + 2, y ), 0 );\n\t\tvec4 v4 = texelFetch( batchingTexture, ivec2( x + 3, y ), 0 );\n\t\treturn mat4( v1, v2, v3, v4 );\n\t}\n\tfloat getIndirectIndex( const in int i ) {\n\t\tint size = textureSize( batchingIdTexture, 0 ).x;\n\t\tint x = i % size;\n\t\tint y = i / size;\n\t\treturn float( texelFetch( batchingIdTexture, ivec2( x, y ), 0 ).r );\n\t}\n#endif\n#ifdef USE_BATCHING_COLOR\n\tuniform sampler2D batchingColorTexture;\n\tvec4 getBatchingColor( const in float i ) {\n\t\tint size = textureSize( batchingColorTexture, 0 ).x;\n\t\tint j = int( i );\n\t\tint x = j % size;\n\t\tint y = j / size;\n\t\treturn texelFetch( batchingColorTexture, ivec2( x, y ), 0 );\n\t}\n#endif"; + +var batching_vertex = "#ifdef USE_BATCHING\n\tmat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) );\n#endif"; + +var begin_vertex = "vec3 transformed = vec3( position );\n#ifdef USE_ALPHAHASH\n\tvPosition = vec3( position );\n#endif"; + +var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif"; + +var bsdfs = "float G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, 1.0, dotVH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n} // validated"; + +var iridescence_fragment = "#ifdef USE_IRIDESCENCE\n\tconst mat3 XYZ_TO_REC709 = mat3(\n\t\t 3.2404542, -0.9692660, 0.0556434,\n\t\t-1.5371385, 1.8760108, -0.2040259,\n\t\t-0.4985314, 0.0415560, 1.0572252\n\t);\n\tvec3 Fresnel0ToIor( vec3 fresnel0 ) {\n\t\tvec3 sqrtF0 = sqrt( fresnel0 );\n\t\treturn ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 );\n\t}\n\tvec3 IorToFresnel0( vec3 transmittedIor, float incidentIor ) {\n\t\treturn pow2( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) );\n\t}\n\tfloat IorToFresnel0( float transmittedIor, float incidentIor ) {\n\t\treturn pow2( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor ));\n\t}\n\tvec3 evalSensitivity( float OPD, vec3 shift ) {\n\t\tfloat phase = 2.0 * PI * OPD * 1.0e-9;\n\t\tvec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );\n\t\tvec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );\n\t\tvec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );\n\t\tvec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - pow2( phase ) * var );\n\t\txyz.x += 9.7470e-14 * sqrt( 2.0 * PI * 4.5282e+09 ) * cos( 2.2399e+06 * phase + shift[ 0 ] ) * exp( - 4.5282e+09 * pow2( phase ) );\n\t\txyz /= 1.0685e-7;\n\t\tvec3 rgb = XYZ_TO_REC709 * xyz;\n\t\treturn rgb;\n\t}\n\tvec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) {\n\t\tvec3 I;\n\t\tfloat iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );\n\t\tfloat sinTheta2Sq = pow2( outsideIOR / iridescenceIOR ) * ( 1.0 - pow2( cosTheta1 ) );\n\t\tfloat cosTheta2Sq = 1.0 - sinTheta2Sq;\n\t\tif ( cosTheta2Sq < 0.0 ) {\n\t\t\treturn vec3( 1.0 );\n\t\t}\n\t\tfloat cosTheta2 = sqrt( cosTheta2Sq );\n\t\tfloat R0 = IorToFresnel0( iridescenceIOR, outsideIOR );\n\t\tfloat R12 = F_Schlick( R0, 1.0, cosTheta1 );\n\t\tfloat T121 = 1.0 - R12;\n\t\tfloat phi12 = 0.0;\n\t\tif ( iridescenceIOR < outsideIOR ) phi12 = PI;\n\t\tfloat phi21 = PI - phi12;\n\t\tvec3 baseIOR = Fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) );\t\tvec3 R1 = IorToFresnel0( baseIOR, iridescenceIOR );\n\t\tvec3 R23 = F_Schlick( R1, 1.0, cosTheta2 );\n\t\tvec3 phi23 = vec3( 0.0 );\n\t\tif ( baseIOR[ 0 ] < iridescenceIOR ) phi23[ 0 ] = PI;\n\t\tif ( baseIOR[ 1 ] < iridescenceIOR ) phi23[ 1 ] = PI;\n\t\tif ( baseIOR[ 2 ] < iridescenceIOR ) phi23[ 2 ] = PI;\n\t\tfloat OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2;\n\t\tvec3 phi = vec3( phi21 ) + phi23;\n\t\tvec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 );\n\t\tvec3 r123 = sqrt( R123 );\n\t\tvec3 Rs = pow2( T121 ) * R23 / ( vec3( 1.0 ) - R123 );\n\t\tvec3 C0 = R12 + Rs;\n\t\tI = C0;\n\t\tvec3 Cm = Rs - T121;\n\t\tfor ( int m = 1; m <= 2; ++ m ) {\n\t\t\tCm *= r123;\n\t\t\tvec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi );\n\t\t\tI += Cm * Sm;\n\t\t}\n\t\treturn max( I, vec3( 0.0 ) );\n\t}\n#endif"; + +var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vBumpMapUv );\n\t\tvec2 dSTdy = dFdy( vBumpMapUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vBumpMapUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {\n\t\tvec3 vSigmaX = normalize( dFdx( surf_pos.xyz ) );\n\t\tvec3 vSigmaY = normalize( dFdy( surf_pos.xyz ) );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 ) * faceDirection;\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif"; + +var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#ifdef ALPHA_TO_COVERAGE\n\t\tfloat distanceToPlane, distanceGradient;\n\t\tfloat clipOpacity = 1.0;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tdistanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;\n\t\t\tdistanceGradient = fwidth( distanceToPlane ) / 2.0;\n\t\t\tclipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane );\n\t\t\tif ( clipOpacity == 0.0 ) discard;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\t\tfloat unionClipOpacity = 1.0;\n\t\t\t#pragma unroll_loop_start\n\t\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\t\tplane = clippingPlanes[ i ];\n\t\t\t\tdistanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;\n\t\t\t\tdistanceGradient = fwidth( distanceToPlane ) / 2.0;\n\t\t\t\tunionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane );\n\t\t\t}\n\t\t\t#pragma unroll_loop_end\n\t\t\tclipOpacity *= 1.0 - unionClipOpacity;\n\t\t#endif\n\t\tdiffuseColor.a *= clipOpacity;\n\t\tif ( diffuseColor.a == 0.0 ) discard;\n\t#else\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\t\tbool clipped = true;\n\t\t\t#pragma unroll_loop_start\n\t\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\t\tplane = clippingPlanes[ i ];\n\t\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t\t}\n\t\t\t#pragma unroll_loop_end\n\t\t\tif ( clipped ) discard;\n\t\t#endif\n\t#endif\n#endif"; + +var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif"; + +var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif"; + +var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif"; + +var color_fragment = "#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#endif"; + +var color_pars_fragment = "#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#endif"; + +var color_pars_vertex = "#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )\n\tvarying vec4 vColor;\n#endif"; + +var color_vertex = "#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )\n\tvColor = vec4( 1.0 );\n#endif\n#ifdef USE_COLOR_ALPHA\n\tvColor *= color;\n#elif defined( USE_COLOR )\n\tvColor.rgb *= color;\n#endif\n#ifdef USE_INSTANCING_COLOR\n\tvColor.rgb *= instanceColor.rgb;\n#endif\n#ifdef USE_BATCHING_COLOR\n\tvColor *= getBatchingColor( getIndirectIndex( gl_DrawID ) );\n#endif"; + +var common = "#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement( a ) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nvec3 pow2( const in vec3 x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }\nfloat average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract( sin( sn ) * c );\n}\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\n#ifdef USE_ALPHAHASH\n\tvarying vec3 vPosition;\n#endif\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\n#define inverseTransformDirection transformDirectionByInverseViewMatrix\nvec3 transformNormalByInverseViewMatrix( in vec3 normal, in mat4 viewMatrix ) {\n\treturn normalize( ( vec4( normal, 0.0 ) * viewMatrix ).xyz );\n}\nvec3 transformDirectionByInverseViewMatrix( in vec3 dir, in mat4 viewMatrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * viewMatrix ).xyz );\n}\nbool isPerspectiveMatrix( mat4 m ) {\n\treturn m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}\nvec3 BRDF_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nfloat F_Schlick( const in float f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n} // validated"; + +var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n\t#define cubeUV_minMipLevel 4.0\n\t#define cubeUV_minTileSize 16.0\n\tfloat getFace( vec3 direction ) {\n\t\tvec3 absDirection = abs( direction );\n\t\tfloat face = - 1.0;\n\t\tif ( absDirection.x > absDirection.z ) {\n\t\t\tif ( absDirection.x > absDirection.y )\n\t\t\t\tface = direction.x > 0.0 ? 0.0 : 3.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t} else {\n\t\t\tif ( absDirection.z > absDirection.y )\n\t\t\t\tface = direction.z > 0.0 ? 2.0 : 5.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t}\n\t\treturn face;\n\t}\n\tvec2 getUV( vec3 direction, float face ) {\n\t\tvec2 uv;\n\t\tif ( face == 0.0 ) {\n\t\t\tuv = vec2( direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 1.0 ) {\n\t\t\tuv = vec2( - direction.x, - direction.z ) / abs( direction.y );\n\t\t} else if ( face == 2.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.y ) / abs( direction.z );\n\t\t} else if ( face == 3.0 ) {\n\t\t\tuv = vec2( - direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 4.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.z ) / abs( direction.y );\n\t\t} else {\n\t\t\tuv = vec2( direction.x, direction.y ) / abs( direction.z );\n\t\t}\n\t\treturn 0.5 * ( uv + 1.0 );\n\t}\n\tvec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {\n\t\tfloat face = getFace( direction );\n\t\tfloat filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );\n\t\tmipInt = max( mipInt, cubeUV_minMipLevel );\n\t\tfloat faceSize = exp2( mipInt );\n\t\thighp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0;\n\t\tif ( face > 2.0 ) {\n\t\t\tuv.y += faceSize;\n\t\t\tface -= 3.0;\n\t\t}\n\t\tuv.x += face * faceSize;\n\t\tuv.x += filterInt * 3.0 * cubeUV_minTileSize;\n\t\tuv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize );\n\t\tuv.x *= CUBEUV_TEXEL_WIDTH;\n\t\tuv.y *= CUBEUV_TEXEL_HEIGHT;\n\t\t#ifdef texture2DGradEXT\n\t\t\treturn texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb;\n\t\t#else\n\t\t\treturn texture2D( envMap, uv ).rgb;\n\t\t#endif\n\t}\n\t#define cubeUV_r0 1.0\n\t#define cubeUV_m0 - 2.0\n\t#define cubeUV_r1 0.8\n\t#define cubeUV_m1 - 1.0\n\t#define cubeUV_r4 0.4\n\t#define cubeUV_m4 2.0\n\t#define cubeUV_r5 0.305\n\t#define cubeUV_m5 3.0\n\t#define cubeUV_r6 0.21\n\t#define cubeUV_m6 4.0\n\tfloat roughnessToMip( float roughness ) {\n\t\tfloat mip = 0.0;\n\t\tif ( roughness >= cubeUV_r1 ) {\n\t\t\tmip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0;\n\t\t} else if ( roughness >= cubeUV_r4 ) {\n\t\t\tmip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1;\n\t\t} else if ( roughness >= cubeUV_r5 ) {\n\t\t\tmip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4;\n\t\t} else if ( roughness >= cubeUV_r6 ) {\n\t\t\tmip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5;\n\t\t} else {\n\t\t\tmip = - 2.0 * log2( 1.16 * roughness );\t\t}\n\t\treturn mip;\n\t}\n\tvec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {\n\t\tfloat mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );\n\t\tfloat mipF = fract( mip );\n\t\tfloat mipInt = floor( mip );\n\t\tvec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );\n\t\tif ( mipF == 0.0 ) {\n\t\t\treturn vec4( color0, 1.0 );\n\t\t} else {\n\t\t\tvec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );\n\t\t\treturn vec4( mix( color0, color1, mipF ), 1.0 );\n\t\t}\n\t}\n#endif"; + +var defaultnormal_vertex = "vec3 transformedNormal = objectNormal;\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = objectTangent;\n#endif\n#ifdef USE_BATCHING\n\tmat3 bm = mat3( batchingMatrix );\n\ttransformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) );\n\ttransformedNormal = bm * transformedNormal;\n\t#ifdef USE_TANGENT\n\t\ttransformedTangent = bm * transformedTangent;\n\t#endif\n#endif\n#ifdef USE_INSTANCING\n\tmat3 im = mat3( instanceMatrix );\n\ttransformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) );\n\ttransformedNormal = im * transformedNormal;\n\t#ifdef USE_TANGENT\n\t\ttransformedTangent = im * transformedTangent;\n\t#endif\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\ttransformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz;\n#endif"; + +var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif"; + +var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );\n#endif"; + +var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );\n\t#ifdef DECODE_VIDEO_TEXTURE_EMISSIVE\n\t\temissiveColor = sRGBTransferEOTF( emissiveColor );\n\t#endif\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif"; + +var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif"; + +var colorspace_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );"; + +var colorspace_pars_fragment = "vec4 LinearTransferOETF( in vec4 value ) {\n\treturn value;\n}\nvec4 sRGBTransferEOTF( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );\n}\nvec4 sRGBTransferOETF( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\n}"; + +var envmap_fragment = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = transformNormalByInverseViewMatrix( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, envMapRotation * reflectVec );\n\t\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t\t#endif\n\t#endif\n#endif"; + +var envmap_common_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform mat3 envMapRotation;\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n#endif"; + +var envmap_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float reflectivity;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\tvarying vec3 vWorldPosition;\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif"; + +var envmap_pars_vertex = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\t\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif"; + +var envmap_vertex = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = transformNormalByInverseViewMatrix( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif"; + +var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif"; + +var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif"; + +var fog_fragment = "#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, vFogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif"; + +var fog_pars_fragment = "#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float vFogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif"; + +var gradientmap_pars_fragment = "#ifdef USE_GRADIENTMAP\n\tuniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\tfloat dotNL = dot( normal, lightDirection );\n\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t#ifdef USE_GRADIENTMAP\n\t\treturn vec3( texture2D( gradientMap, coord ).r );\n\t#else\n\t\tvec2 fw = fwidth( coord ) * 0.5;\n\t\treturn mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) );\n\t#endif\n}"; + +var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif"; + +var lights_lambert_fragment = "LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;"; + +var lights_lambert_pars_fragment = "varying vec3 vViewPosition;\nstruct LambertMaterial {\n\tvec3 diffuseColor;\n\tfloat specularStrength;\n};\nvoid RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Lambert\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Lambert"; + +var lights_pars_begin = "uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\n#if defined( USE_LIGHT_PROBES )\n\tuniform vec3 lightProbe[ 9 ];\n#endif\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {\n\tvec3 worldNormal = transformNormalByInverseViewMatrix( normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\treturn irradiance;\n}\nfloat getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\tif ( cutoffDistance > 0.0 ) {\n\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t}\n\treturn distanceFalloff;\n}\nfloat getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {\n\treturn smoothstep( coneCosine, penumbraCosine, angleCosine );\n}\n#if NUM_SUN_LIGHTS > 0\n\tstruct SunLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform SunLight sunLights[ NUM_SUN_LIGHTS ];\n\tvoid getSunLightInfo( const in SunLight sunLight, out IncidentLight light ) {\n\t\tlight.color = sunLight.color;\n\t\tlight.direction = sunLight.direction;\n\t\tlight.visible = true;\n\t}\n#endif\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) {\n\t\tlight.color = directionalLight.color;\n\t\tlight.direction = directionalLight.direction;\n\t\tlight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) {\n\t\tvec3 lVector = pointLight.position - geometryPosition;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tlight.color = pointLight.color;\n\t\tlight.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );\n\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) {\n\t\tvec3 lVector = spotLight.position - geometryPosition;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat angleCos = dot( light.direction, spotLight.direction );\n\t\tfloat spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\tif ( spotAttenuation > 0.0 ) {\n\t\t\tfloat lightDistance = length( lVector );\n\t\t\tlight.color = spotLight.color * spotAttenuation;\n\t\t\tlight.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t\t} else {\n\t\t\tlight.color = vec3( 0.0 );\n\t\t\tlight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {\n\t\tfloat dotNL = dot( normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\treturn irradiance;\n\t}\n#endif\n#include "; + +var envmap_physical_pars_fragment = "#ifdef USE_ENVMAP\n\tvec3 getIBLIrradiance( const in vec3 normal ) {\n\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\tvec3 worldNormal = transformNormalByInverseViewMatrix( normal, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 );\n\t\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\tvec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {\n\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\tvec3 reflectVec = reflect( - viewDir, normal );\n\t\t\treflectVec = normalize( mix( reflectVec, normal, pow4( roughness ) ) );\n\t\t\treflectVec = transformDirectionByInverseViewMatrix( reflectVec, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness );\n\t\t\treturn envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\t#ifdef USE_RETROREFLECTION\n\t\tvec3 getIBLRetroRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {\n\t\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\t\tvec3 retroVec = normalize( mix( viewDir, normal, pow4( roughness ) ) );\n\t\t\t\tretroVec = transformDirectionByInverseViewMatrix( retroVec, viewMatrix );\n\t\t\t\tvec4 envMapColor = textureCubeUV( envMap, envMapRotation * retroVec, roughness );\n\t\t\t\treturn envMapColor.rgb * envMapIntensity;\n\t\t\t#else\n\t\t\t\treturn vec3( 0.0 );\n\t\t\t#endif\n\t\t}\n\t#endif\n\t#ifdef USE_ANISOTROPY\n\t\tvec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) {\n\t\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\t\tvec3 bentNormal = cross( bitangent, viewDir );\n\t\t\t\tbentNormal = normalize( cross( bentNormal, bitangent ) );\n\t\t\t\tbentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) );\n\t\t\t\treturn getIBLRadiance( viewDir, bentNormal, roughness );\n\t\t\t#else\n\t\t\t\treturn vec3( 0.0 );\n\t\t\t#endif\n\t\t}\n\t\t#ifdef USE_RETROREFLECTION\n\t\t\tvec3 getIBLAnisotropyRetroRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) {\n\t\t\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\t\t\tvec3 bentNormal = cross( bitangent, viewDir );\n\t\t\t\t\tbentNormal = normalize( cross( bentNormal, bitangent ) );\n\t\t\t\t\tbentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) );\n\t\t\t\t\treturn getIBLRetroRadiance( viewDir, bentNormal, roughness );\n\t\t\t\t#else\n\t\t\t\t\treturn vec3( 0.0 );\n\t\t\t\t#endif\n\t\t\t}\n\t\t#endif\n\t#endif\n#endif"; + +var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;"; + +var lights_toon_pars_fragment = "varying vec3 vViewPosition;\nstruct ToonMaterial {\n\tvec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon"; + +var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;"; + +var lights_phong_pars_fragment = "varying vec3 vViewPosition;\nstruct BlinnPhongMaterial {\n\tvec3 diffuseColor;\n\tvec3 specularColor;\n\tfloat specularShininess;\n\tfloat specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong"; + +var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.diffuseContribution = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nmaterial.metalness = metalnessFactor;\nvec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;\nmaterial.roughness = min( material.roughness, 1.0 );\n#ifdef IOR\n\tmaterial.ior = ior;\n\t#ifdef USE_SPECULAR\n\t\tfloat specularIntensityFactor = specularIntensity;\n\t\tvec3 specularColorFactor = specularColor;\n\t\t#ifdef USE_SPECULAR_COLORMAP\n\t\t\tspecularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb;\n\t\t#endif\n\t\t#ifdef USE_SPECULAR_INTENSITYMAP\n\t\t\tspecularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a;\n\t\t#endif\n\t\tmaterial.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );\n\t#else\n\t\tfloat specularIntensityFactor = 1.0;\n\t\tvec3 specularColorFactor = vec3( 1.0 );\n\t\tmaterial.specularF90 = 1.0;\n\t#endif\n\tmaterial.specularColor = min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor;\n\tmaterial.specularColorBlended = mix( material.specularColor, diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = vec3( 0.04 );\n\tmaterial.specularColorBlended = mix( material.specularColor, diffuseColor.rgb, metalnessFactor );\n\tmaterial.specularF90 = 1.0;\n#endif\n#ifdef USE_CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\tmaterial.clearcoatF0 = vec3( 0.04 );\n\tmaterial.clearcoatF90 = 1.0;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_DISPERSION\n\tmaterial.dispersion = dispersion;\n#endif\n#ifdef USE_RETROREFLECTION\n\tmaterial.retroreflectivity = retroreflectivity;\n#endif\n#ifdef USE_IRIDESCENCE\n\tmaterial.iridescence = iridescence;\n\tmaterial.iridescenceIOR = iridescenceIOR;\n\t#ifdef USE_IRIDESCENCEMAP\n\t\tmaterial.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r;\n\t#endif\n\t#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\t\tmaterial.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum;\n\t#else\n\t\tmaterial.iridescenceThickness = iridescenceThicknessMaximum;\n\t#endif\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheenColor;\n\t#ifdef USE_SHEEN_COLORMAP\n\t\tmaterial.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb;\n\t#endif\n\tmaterial.sheenRoughness = clamp( sheenRoughness, 0.0001, 1.0 );\n\t#ifdef USE_SHEEN_ROUGHNESSMAP\n\t\tmaterial.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a;\n\t#endif\n#endif\n#ifdef USE_ANISOTROPY\n\t#ifdef USE_ANISOTROPYMAP\n\t\tmat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x );\n\t\tvec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb;\n\t\tvec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b;\n\t#else\n\t\tvec2 anisotropyV = anisotropyVector;\n\t#endif\n\tmaterial.anisotropy = length( anisotropyV );\n\tif( material.anisotropy == 0.0 ) {\n\t\tanisotropyV = vec2( 1.0, 0.0 );\n\t} else {\n\t\tanisotropyV /= material.anisotropy;\n\t\tmaterial.anisotropy = saturate( material.anisotropy );\n\t}\n\tmaterial.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) );\n\tmaterial.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y;\n\tmaterial.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y;\n#endif"; + +var lights_physical_pars_fragment = "uniform sampler2D dfgLUT;\nstruct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tvec3 diffuseContribution;\n\tvec3 specularColor;\n\tvec3 specularColorBlended;\n\tfloat roughness;\n\tfloat metalness;\n\tfloat specularF90;\n\tfloat dispersion;\n\tvec2 dfg;\n\tvec3 multiScatteringCompensation;\n\t#ifdef USE_RETROREFLECTION\n\t\tfloat retroreflectivity;\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tfloat clearcoat;\n\t\tfloat clearcoatRoughness;\n\t\tvec3 clearcoatF0;\n\t\tfloat clearcoatF90;\n\t#endif\n\t#ifdef USE_IRIDESCENCE\n\t\tfloat iridescence;\n\t\tfloat iridescenceIOR;\n\t\tfloat iridescenceThickness;\n\t\tvec3 iridescenceFresnel;\n\t\tvec3 iridescenceF0Dielectric;\n\t\tvec3 iridescenceF0Metallic;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tvec3 sheenColor;\n\t\tfloat sheenRoughness;\n\t#endif\n\t#ifdef IOR\n\t\tfloat ior;\n\t#endif\n\t#ifdef USE_TRANSMISSION\n\t\tfloat transmission;\n\t\tfloat transmissionAlpha;\n\t\tfloat thickness;\n\t\tfloat attenuationDistance;\n\t\tvec3 attenuationColor;\n\t#endif\n\t#ifdef USE_ANISOTROPY\n\t\tfloat anisotropy;\n\t\tfloat alphaT;\n\t\tvec3 anisotropyT;\n\t\tvec3 anisotropyB;\n\t#endif\n};\nvec3 clearcoatSpecularDirect = vec3( 0.0 );\nvec3 clearcoatSpecularIndirect = vec3( 0.0 );\nvec3 sheenSpecularDirect = vec3( 0.0 );\nvec3 sheenSpecularIndirect = vec3(0.0 );\nvec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) {\n float x = clamp( 1.0 - dotVH, 0.0, 1.0 );\n float x2 = x * x;\n float x5 = clamp( x * x2 * x2, 0.0, 0.9999 );\n return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 );\n}\nfloat V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\n#ifdef USE_ANISOTROPY\n\tfloat V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) {\n\t\tfloat gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) );\n\t\tfloat gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) );\n\t\treturn 0.5 / max( gv + gl, EPSILON );\n\t}\n\tfloat D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) {\n\t\tfloat a2 = alphaT * alphaB;\n\t\thighp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH );\n\t\thighp float v2 = dot( v, v );\n\t\tfloat w2 = a2 / v2;\n\t\treturn RECIPROCAL_PI * a2 * pow2 ( w2 );\n\t}\n#endif\n#ifdef USE_CLEARCOAT\n\tvec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) {\n\t\tvec3 f0 = material.clearcoatF0;\n\t\tfloat f90 = material.clearcoatF90;\n\t\tfloat roughness = material.clearcoatRoughness;\n\t\tfloat alpha = pow2( roughness );\n\t\tvec3 halfDir = normalize( lightDir + viewDir );\n\t\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\t\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\t\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\t\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\t\tvec3 F = F_Schlick( f0, f90, dotVH );\n\t\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\t\tfloat D = D_GGX( alpha, dotNH );\n\t\treturn F * ( V * D );\n\t}\n#endif\nvec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {\n\tvec3 f0 = material.specularColorBlended;\n\tfloat f90 = material.specularF90;\n\tfloat roughness = material.roughness;\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( f0, f90, dotVH );\n\t#ifdef USE_IRIDESCENCE\n\t\tF = mix( F, material.iridescenceFresnel, material.iridescence );\n\t#endif\n\t#ifdef USE_ANISOTROPY\n\t\tfloat dotTL = dot( material.anisotropyT, lightDir );\n\t\tfloat dotTV = dot( material.anisotropyT, viewDir );\n\t\tfloat dotTH = dot( material.anisotropyT, halfDir );\n\t\tfloat dotBL = dot( material.anisotropyB, lightDir );\n\t\tfloat dotBV = dot( material.anisotropyB, viewDir );\n\t\tfloat dotBH = dot( material.anisotropyB, halfDir );\n\t\tfloat V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL );\n\t\tfloat D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH );\n\t#else\n\t\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\t\tfloat D = D_GGX( alpha, dotNH );\n\t#endif\n\treturn F * ( V * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transpose( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie( float roughness, float dotNH ) {\n\tfloat alpha = pow2( roughness );\n\tfloat invAlpha = 1.0 / alpha;\n\tfloat cos2h = dotNH * dotNH;\n\tfloat sin2h = max( 1.0 - cos2h, 0.0078125 );\n\treturn ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );\n}\nfloat V_Neubelt( float dotNV, float dotNL ) {\n\treturn saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );\n}\nvec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat D = D_Charlie( sheenRoughness, dotNH );\n\tfloat V = V_Neubelt( dotNV, dotNL );\n\treturn sheenColor * ( D * V );\n}\n#endif\nfloat IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat r2 = roughness * roughness;\n\tfloat rInv = 1.0 / ( roughness + 0.1 );\n\tfloat a = -1.9362 + 1.0678 * roughness + 0.4573 * r2 - 0.8469 * rInv;\n\tfloat b = -0.6014 + 0.5538 * roughness - 0.4670 * r2 - 0.1255 * rInv;\n\tfloat DG = exp( a * dotNV + b );\n\treturn saturate( DG );\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tvec2 fab = texture2D( dfgLUT, vec2( roughness, dotNV ) ).rg;\n\treturn specularColor * fab.x + specularF90 * fab.y;\n}\n#ifdef USE_IRIDESCENCE\nvoid computeMultiscatteringIridescence( const in vec2 fab, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#else\nvoid computeMultiscattering( const in vec2 fab, const in vec3 specularColor, const in float specularF90, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#endif\n\t#ifdef USE_IRIDESCENCE\n\t\tvec3 Fr = mix( specularColor, iridescenceF0, iridescence );\n\t#else\n\t\tvec3 Fr = specularColor;\n\t#endif\n\tvec3 FssEss = Fr * fab.x + specularF90 * fab.y;\n\tfloat Ess = fab.x + fab.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometryNormal;\n\t\tvec3 viewDir = geometryViewDir;\n\t\tvec3 position = geometryPosition;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.roughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColorBlended * t2.x + ( material.specularF90 - material.specularColorBlended ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseContribution * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t\t#ifdef USE_CLEARCOAT\n\t\t\tvec3 Ncc = geometryClearcoatNormal;\n\t\t\tvec2 uvClearcoat = LTC_Uv( Ncc, viewDir, material.clearcoatRoughness );\n\t\t\tvec4 t1Clearcoat = texture2D( ltc_1, uvClearcoat );\n\t\t\tvec4 t2Clearcoat = texture2D( ltc_2, uvClearcoat );\n\t\t\tmat3 mInvClearcoat = mat3(\n\t\t\t\tvec3( t1Clearcoat.x, 0, t1Clearcoat.y ),\n\t\t\t\tvec3( 0, 1, 0 ),\n\t\t\t\tvec3( t1Clearcoat.z, 0, t1Clearcoat.w )\n\t\t\t);\n\t\t\tvec3 fresnelClearcoat = material.clearcoatF0 * t2Clearcoat.x + ( material.clearcoatF90 - material.clearcoatF0 ) * t2Clearcoat.y;\n\t\t\tclearcoatSpecularDirect += lightColor * fresnelClearcoat * LTC_Evaluate( Ncc, viewDir, position, mInvClearcoat, rectCoords );\n\t\t#endif\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = dotNLcc * directLight.color;\n\t\tclearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material );\n\t#endif\n\t#ifdef USE_SHEEN\n \n \t\tsheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness );\n \n \t\tfloat sheenAlbedoV = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );\n \t\tfloat sheenAlbedoL = IBLSheenBRDF( geometryNormal, directLight.direction, material.sheenRoughness );\n \n \t\tfloat sheenEnergyComp = 1.0 - max3( material.sheenColor ) * max( sheenAlbedoV, sheenAlbedoL );\n \n \t\tirradiance *= sheenEnergyComp;\n \n \t#endif\n\tvec3 specularBRDF = BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material );\n\t#ifdef USE_RETROREFLECTION\n\t\tvec3 retroViewDir = reflect( - geometryViewDir, geometryNormal );\n\t\tvec3 retroSpecularBRDF = BRDF_GGX( directLight.direction, retroViewDir, geometryNormal, material );\n\t\tspecularBRDF = mix( specularBRDF, retroSpecularBRDF, saturate( material.retroreflectivity ) );\n\t#endif\n\treflectedLight.directSpecular += irradiance * specularBRDF * material.multiScatteringCompensation;\n\tvec3 halfDir = normalize( directLight.direction + geometryViewDir );\n\tfloat dotVH = saturate( dot( geometryViewDir, halfDir ) );\n\tvec3 F = F_Schlick( material.specularColor, material.specularF90, dotVH );\n\t#ifdef USE_RETROREFLECTION\n\t\tvec3 retroHalfDir = normalize( directLight.direction + retroViewDir );\n\t\tfloat dotRetroVH = saturate( dot( retroViewDir, retroHalfDir ) );\n\t\tvec3 retroF = F_Schlick( material.specularColor, material.specularF90, dotRetroVH );\n\t\tF = mix( F, retroF, saturate( material.retroreflectivity ) );\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseContribution ) * ( 1.0 - F );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\t#ifdef USE_IRIDESCENCE\n\t\tcomputeMultiscatteringIridescence( material.dfg, material.specularColor, material.specularF90, material.iridescence, material.iridescenceF0Dielectric, singleScattering, multiScattering );\n\t#else\n\t\tcomputeMultiscattering( material.dfg, material.specularColor, material.specularF90, singleScattering, multiScattering );\n\t#endif\n\tvec3 diffuse = irradiance * BRDF_Lambert( material.diffuseContribution ) * ( 1.0 - singleScattering - multiScattering );\n\t#ifdef USE_SHEEN\n\t\tfloat sheenAlbedo = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );\n\t\tsheenSpecularIndirect += irradiance * material.sheenColor * sheenAlbedo * RECIPROCAL_PI;\n\t\tfloat sheenEnergyComp = 1.0 - max3( material.sheenColor ) * sheenAlbedo;\n\t\tdiffuse *= sheenEnergyComp;\n\t#endif\n\treflectedLight.indirectDiffuse += diffuse;\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ) * RECIPROCAL_PI;\n \t#endif\n\tvec3 singleScatteringDielectric = vec3( 0.0 );\n\tvec3 multiScatteringDielectric = vec3( 0.0 );\n\tvec3 singleScatteringMetallic = vec3( 0.0 );\n\tvec3 multiScatteringMetallic = vec3( 0.0 );\n\t#ifdef USE_IRIDESCENCE\n\t\tcomputeMultiscatteringIridescence( material.dfg, material.specularColor, material.specularF90, material.iridescence, material.iridescenceF0Dielectric, singleScatteringDielectric, multiScatteringDielectric );\n\t\tcomputeMultiscatteringIridescence( material.dfg, material.diffuseColor, material.specularF90, material.iridescence, material.iridescenceF0Metallic, singleScatteringMetallic, multiScatteringMetallic );\n\t#else\n\t\tcomputeMultiscattering( material.dfg, material.specularColor, material.specularF90, singleScatteringDielectric, multiScatteringDielectric );\n\t\tcomputeMultiscattering( material.dfg, material.diffuseColor, material.specularF90, singleScatteringMetallic, multiScatteringMetallic );\n\t#endif\n\tvec3 singleScattering = mix( singleScatteringDielectric, singleScatteringMetallic, material.metalness );\n\tvec3 multiScattering = mix( multiScatteringDielectric, multiScatteringMetallic, material.metalness );\n\tvec3 totalScatteringDielectric = singleScatteringDielectric + multiScatteringDielectric;\n\tvec3 diffuse = material.diffuseContribution * ( 1.0 - totalScatteringDielectric );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\tvec3 indirectSpecular = radiance * singleScattering;\n\tindirectSpecular += multiScattering * cosineWeightedIrradiance;\n\tvec3 indirectDiffuse = diffuse * cosineWeightedIrradiance;\n\t#ifdef USE_SHEEN\n\t\tfloat sheenAlbedo = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );\n\t\tfloat sheenEnergyComp = 1.0 - max3( material.sheenColor ) * sheenAlbedo;\n\t\tindirectSpecular *= sheenEnergyComp;\n\t\tindirectDiffuse *= sheenEnergyComp;\n\t#endif\n\treflectedLight.indirectSpecular += indirectSpecular;\n\treflectedLight.indirectDiffuse += indirectDiffuse;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}"; + +var lights_fragment_begin = "\nvec3 geometryPosition = - vViewPosition;\nvec3 geometryNormal = normal;\nvec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\nvec3 geometryClearcoatNormal = vec3( 0.0 );\n#ifdef USE_CLEARCOAT\n\tgeometryClearcoatNormal = clearcoatNormal;\n#endif\n#ifdef USE_IRIDESCENCE\n\tfloat dotNVi = saturate( dot( normal, geometryViewDir ) );\n\tif ( material.iridescenceThickness == 0.0 ) {\n\t\tmaterial.iridescence = 0.0;\n\t} else {\n\t\tmaterial.iridescence = saturate( material.iridescence );\n\t}\n\tif ( material.iridescence > 0.0 ) {\n\t\tvec3 iridescenceFresnelDielectric = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );\n\t\tvec3 iridescenceFresnelMetallic = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.diffuseColor );\n\t\tmaterial.iridescenceFresnel = mix( iridescenceFresnelDielectric, iridescenceFresnelMetallic, material.metalness );\n\t\tmaterial.iridescenceF0Dielectric = Schlick_to_F0( iridescenceFresnelDielectric, 1.0, dotNVi );\n\t\tmaterial.iridescenceF0Metallic = Schlick_to_F0( iridescenceFresnelMetallic, 1.0, dotNVi );\n\t}\n#endif\n#ifdef STANDARD\n\tfloat dotNVms = saturate( dot( geometryNormal, geometryViewDir ) );\n\tmaterial.dfg = texture2D( dfgLUT, vec2( material.roughness, dotNVms ) ).rg;\n\t#if ( NUM_SUN_LIGHTS > 0 || NUM_DIR_LIGHTS > 0 || NUM_POINT_LIGHTS > 0 || NUM_SPOT_LIGHTS > 0 )\n\t\tfloat EssMs = material.dfg.x + material.dfg.y;\n\t\tmaterial.multiScatteringCompensation = 1.0 + material.specularColorBlended * ( 1.0 / EssMs - 1.0 );\n\t#endif\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointLightInfo( pointLight, geometryPosition, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS ) && ( defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_BASIC ) )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\tvec4 spotColor;\n\tvec3 spotLightCoord;\n\tbool inSpotLightMap;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotLightInfo( spotLight, geometryPosition, directLight );\n\t\t#if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX\n\t\t#elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t#define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS\n\t\t#else\n\t\t#define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#endif\n\t\t#if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )\n\t\t\tspotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;\n\t\t\tinSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );\n\t\t\tspotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );\n\t\t\tdirectLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color;\n\t\t#endif\n\t\t#undef SPOT_LIGHT_MAP_INDEX\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SUN_LIGHTS > 0 ) && defined( RE_Direct )\n\tSunLight sunLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_SUN_LIGHT_SHADOWS > 0\n\tSunLightShadow sunLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SUN_LIGHTS; i ++ ) {\n\t\tsunLight = sunLights[ i ];\n\t\tgetSunLightInfo( sunLight, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SUN_LIGHT_SHADOWS )\n\t\tsunLightShadow = sunLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getSunShadow( sunShadowMap[ i ], sunLightShadow, UNROLLED_LOOP_INDEX ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalLightInfo( directionalLight, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\t#if defined( USE_LIGHT_PROBES )\n\t\tirradiance += getLightProbeIrradiance( lightProbe, geometryNormal );\n\t#endif\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n\t#ifdef USE_LIGHT_PROBES_GRID\n\t\tvec3 probeWorldPos = ( ( vec4( geometryPosition, 1.0 ) - viewMatrix[ 3 ] ) * viewMatrix ).xyz;\n\t\tvec3 probeWorldNormal = transformNormalByInverseViewMatrix( geometryNormal, viewMatrix );\n\t\tirradiance += getLightProbeGridIrradiance( probeWorldPos, probeWorldNormal );\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif"; + +var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n\t\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\t#if defined( STANDARD ) || defined( LAMBERT ) || defined( PHONG )\n\t\t\tiblIrradiance += getIBLIrradiance( geometryNormal );\n\t\t#endif\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\t#ifdef USE_ANISOTROPY\n\t\tvec3 iblRadiance = getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy );\n\t#else\n\t\tvec3 iblRadiance = getIBLRadiance( geometryViewDir, geometryNormal, material.roughness );\n\t#endif\n\t#ifdef USE_RETROREFLECTION\n\t\t#ifdef USE_ANISOTROPY\n\t\t\tvec3 retroIBLRadiance = getIBLAnisotropyRetroRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy );\n\t\t#else\n\t\t\tvec3 retroIBLRadiance = getIBLRetroRadiance( geometryViewDir, geometryNormal, material.roughness );\n\t\t#endif\n\t\tiblRadiance = mix( iblRadiance, retroIBLRadiance, saturate( material.retroreflectivity ) );\n\t#endif\n\tradiance += iblRadiance;\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness );\n\t#endif\n#endif"; + +var lights_fragment_end = "#if defined( RE_IndirectDiffuse )\n\t#if defined( LAMBERT ) || defined( PHONG )\n\t\tirradiance += iblIrradiance;\n\t#endif\n\tRE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n\tRE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n#endif"; + +var lightprobes_pars_fragment = "#ifdef USE_LIGHT_PROBES_GRID\nuniform highp sampler3D probesSH;\nuniform vec3 probesMin;\nuniform vec3 probesMax;\nuniform vec3 probesResolution;\nvec3 getLightProbeGridIrradiance( vec3 worldPos, vec3 worldNormal ) {\n\tvec3 res = probesResolution;\n\tvec3 gridRange = probesMax - probesMin;\n\tvec3 resMinusOne = res - 1.0;\n\tvec3 probeSpacing = gridRange / resMinusOne;\n\tvec3 samplePos = worldPos + worldNormal * probeSpacing * 0.5;\n\tvec3 uvw = clamp( ( samplePos - probesMin ) / gridRange, 0.0, 1.0 );\n\tuvw = uvw * resMinusOne / res + 0.5 / res;\n\tfloat nz = res.z;\n\tfloat paddedSlices = nz + 2.0;\n\tfloat atlasDepth = 7.0 * paddedSlices;\n\tfloat uvZBase = uvw.z * nz + 1.0;\n\tvec4 s0 = texture( probesSH, vec3( uvw.xy, ( uvZBase ) / atlasDepth ) );\n\tvec4 s1 = texture( probesSH, vec3( uvw.xy, ( uvZBase + paddedSlices ) / atlasDepth ) );\n\tvec4 s2 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 2.0 * paddedSlices ) / atlasDepth ) );\n\tvec4 s3 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 3.0 * paddedSlices ) / atlasDepth ) );\n\tvec4 s4 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 4.0 * paddedSlices ) / atlasDepth ) );\n\tvec4 s5 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 5.0 * paddedSlices ) / atlasDepth ) );\n\tvec4 s6 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 6.0 * paddedSlices ) / atlasDepth ) );\n\tvec3 c0 = s0.xyz;\n\tvec3 c1 = vec3( s0.w, s1.xy );\n\tvec3 c2 = vec3( s1.zw, s2.x );\n\tvec3 c3 = s2.yzw;\n\tvec3 c4 = s3.xyz;\n\tvec3 c5 = vec3( s3.w, s4.xy );\n\tvec3 c6 = vec3( s4.zw, s5.x );\n\tvec3 c7 = s5.yzw;\n\tvec3 c8 = s6.xyz;\n\tfloat x = worldNormal.x, y = worldNormal.y, z = worldNormal.z;\n\tvec3 result = c0 * 0.886227;\n\tresult += c1 * 2.0 * 0.511664 * y;\n\tresult += c2 * 2.0 * 0.511664 * z;\n\tresult += c3 * 2.0 * 0.511664 * x;\n\tresult += c4 * 2.0 * 0.429043 * x * y;\n\tresult += c5 * 2.0 * 0.429043 * y * z;\n\tresult += c6 * ( 0.743125 * z * z - 0.247708 );\n\tresult += c7 * 2.0 * 0.429043 * x * z;\n\tresult += c8 * 0.429043 * ( x * x - y * y );\n\treturn max( result, vec3( 0.0 ) );\n}\n#endif"; + +var logdepthbuf_fragment = "#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )\n\tgl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif"; + +var logdepthbuf_pars_fragment = "#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif"; + +var logdepthbuf_pars_vertex = "#ifdef USE_LOGARITHMIC_DEPTH_BUFFER\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif"; + +var logdepthbuf_vertex = "#ifdef USE_LOGARITHMIC_DEPTH_BUFFER\n\tvFragDepth = 1.0 + gl_Position.w;\n\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n#endif"; + +var map_fragment = "#ifdef USE_MAP\n\tvec4 sampledDiffuseColor = texture2D( map, vMapUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\tsampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor );\n\t#endif\n\tdiffuseColor *= sampledDiffuseColor;\n#endif"; + +var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif"; + +var map_particle_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\t#if defined( USE_POINTS_UV )\n\t\tvec2 uv = vUv;\n\t#else\n\t\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n\t#endif\n#endif\n#ifdef USE_MAP\n\tdiffuseColor *= texture2D( map, uv );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif"; + +var map_particle_pars_fragment = "#if defined( USE_POINTS_UV )\n\tvarying vec2 vUv;\n#else\n\t#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\t\tuniform mat3 uvTransform;\n\t#endif\n#endif\n#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif"; + +var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif"; + +var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif"; + +var morphinstance_vertex = "#ifdef USE_INSTANCING_MORPH\n\tfloat morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\tfloat morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tmorphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r;\n\t}\n#endif"; + +var morphcolor_vertex = "#if defined( USE_MORPHCOLORS )\n\tvColor *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t#if defined( USE_COLOR_ALPHA )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ];\n\t\t#elif defined( USE_COLOR )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];\n\t\t#endif\n\t}\n#endif"; + +var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tif ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];\n\t}\n#endif"; + +var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\t#ifndef USE_INSTANCING_MORPH\n\t\tuniform float morphTargetBaseInfluence;\n\t\tuniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\t#endif\n\tuniform sampler2DArray morphTargetsTexture;\n\tuniform ivec2 morphTargetsTextureSize;\n\tvec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {\n\t\tint texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;\n\t\tint y = texelIndex / morphTargetsTextureSize.x;\n\t\tint x = texelIndex - y * morphTargetsTextureSize.x;\n\t\tivec3 morphUV = ivec3( x, y, morphTargetIndex );\n\t\treturn texelFetch( morphTargetsTexture, morphUV, 0 );\n\t}\n#endif"; + +var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tif ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];\n\t}\n#endif"; + +var normal_fragment_begin = "float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;\n#ifdef FLAT_SHADED\n\tvec3 fdx = dFdx( vViewPosition );\n\tvec3 fdy = dFdy( vViewPosition );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal *= faceDirection;\n\t#endif\n#endif\n#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY )\n\t#ifdef USE_TANGENT\n\t\tmat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n\t#else\n\t\tmat3 tbn = getTangentFrame( - vViewPosition, normal,\n\t\t#if defined( USE_NORMALMAP )\n\t\t\tvNormalMapUv\n\t\t#elif defined( USE_CLEARCOAT_NORMALMAP )\n\t\t\tvClearcoatNormalMapUv\n\t\t#else\n\t\t\tvUv\n\t\t#endif\n\t\t);\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\ttbn[0] *= faceDirection;\n\t\ttbn[1] *= faceDirection;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\t#ifdef USE_TANGENT\n\t\tmat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n\t#else\n\t\tmat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv );\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\ttbn2[0] *= faceDirection;\n\t\ttbn2[1] *= faceDirection;\n\t#endif\n#endif\nvec3 nonPerturbedNormal = normal;"; + +var normal_fragment_maps = "#ifdef USE_NORMALMAP_OBJECTSPACE\n\tnormal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;\n\t#ifdef FLIP_SIDED\n\t\tnormal = - normal;\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\n\t#endif\n\tnormal = normalize( normalMatrix * normal );\n#elif defined( USE_NORMALMAP_TANGENTSPACE )\n\tvec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;\n\t#if defined( USE_PACKED_NORMALMAP )\n\t\tmapN = vec3( mapN.xy, sqrt( saturate( 1.0 - dot( mapN.xy, mapN.xy ) ) ) );\n\t#endif\n\tmapN.xy *= normalScale;\n\tnormal = normalize( tbn * mapN );\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );\n#endif"; + +var normal_pars_fragment = "#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif"; + +var normal_pars_vertex = "#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif"; + +var normal_vertex = "#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t\t#ifdef FLIP_SIDED\n\t\t\tvBitangent = - vBitangent;\n\t\t#endif\n\t#endif\n#endif"; + +var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef USE_NORMALMAP_OBJECTSPACE\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) )\n\tmat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {\n\t\tvec3 q0 = dFdx( eye_pos.xyz );\n\t\tvec3 q1 = dFdy( eye_pos.xyz );\n\t\tvec2 st0 = dFdx( uv.st );\n\t\tvec2 st1 = dFdy( uv.st );\n\t\tvec3 N = surf_norm;\n\t\tvec3 q1perp = cross( q1, N );\n\t\tvec3 q0perp = cross( N, q0 );\n\t\tvec3 T = q1perp * st0.x + q0perp * st1.x;\n\t\tvec3 B = q1perp * st0.y + q0perp * st1.y;\n\t\tfloat det = max( dot( T, T ), dot( B, B ) );\n\t\tfloat scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det );\n\t\treturn mat3( T * scale, B * scale, N );\n\t}\n#endif"; + +var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = nonPerturbedNormal;\n#endif"; + +var clearcoat_normal_fragment_maps = "#ifdef USE_CLEARCOAT_NORMALMAP\n\tvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0;\n\tclearcoatMapN.xy *= clearcoatNormalScale;\n\tclearcoatNormal = normalize( tbn2 * clearcoatMapN );\n#endif"; + +var clearcoat_pars_fragment = "#ifdef USE_CLEARCOATMAP\n\tuniform sampler2D clearcoatMap;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform sampler2D clearcoatRoughnessMap;\n#endif"; + +var iridescence_pars_fragment = "#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif"; + +var opaque_fragment = "#ifdef OPAQUE\ndiffuseColor.a = 1.0;\n#endif\n#ifdef USE_TRANSMISSION\ndiffuseColor.a *= material.transmissionAlpha;\n#endif\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );"; + +var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.;\nconst float Inv255 = 1. / 255.;\nconst vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 );\nconst vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g );\nconst vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b );\nconst vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a );\nvec4 packDepthToRGBA( const in float v ) {\n\tif( v <= 0.0 )\n\t\treturn vec4( 0., 0., 0., 0. );\n\tif( v >= 1.0 )\n\t\treturn vec4( 1., 1., 1., 1. );\n\tfloat vuf;\n\tfloat af = modf( v * PackFactors.a, vuf );\n\tfloat bf = modf( vuf * ShiftRight8, vuf );\n\tfloat gf = modf( vuf * ShiftRight8, vuf );\n\treturn vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af );\n}\nvec3 packDepthToRGB( const in float v ) {\n\tif( v <= 0.0 )\n\t\treturn vec3( 0., 0., 0. );\n\tif( v >= 1.0 )\n\t\treturn vec3( 1., 1., 1. );\n\tfloat vuf;\n\tfloat bf = modf( v * PackFactors.b, vuf );\n\tfloat gf = modf( vuf * ShiftRight8, vuf );\n\treturn vec3( vuf * Inv255, gf * PackUpscale, bf );\n}\nvec2 packDepthToRG( const in float v ) {\n\tif( v <= 0.0 )\n\t\treturn vec2( 0., 0. );\n\tif( v >= 1.0 )\n\t\treturn vec2( 1., 1. );\n\tfloat vuf;\n\tfloat gf = modf( v * 256., vuf );\n\treturn vec2( vuf * Inv255, gf );\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors4 );\n}\nfloat unpackRGBToDepth( const in vec3 v ) {\n\treturn dot( v, UnpackFactors3 );\n}\nfloat unpackRGToDepth( const in vec2 v ) {\n\treturn v.r * UnpackFactors2.r + v.g * UnpackFactors2.g;\n}\nvec4 pack2HalfToRGBA( const in vec2 v ) {\n\tvec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );\n\treturn vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );\n}\nvec2 unpackRGBATo2Half( const in vec4 v ) {\n\treturn vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) {\n\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\n\t\treturn depth * ( far - near ) - far;\n\t#else\n\t\treturn depth * ( near - far ) - near;\n\t#endif\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) {\n\t\n\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\treturn ( near * far ) / ( ( near - far ) * depth - near );\n\t#else\n\t\treturn ( near * far ) / ( ( far - near ) * depth - far );\n\t#endif\n}"; + +var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif"; + +var project_vertex = "vec4 mvPosition = vec4( transformed, 1.0 );\n#ifdef USE_BATCHING\n\tmvPosition = batchingMatrix * mvPosition;\n#endif\n#ifdef USE_INSTANCING\n\tmvPosition = instanceMatrix * mvPosition;\n#endif\nmvPosition = modelViewMatrix * mvPosition;\ngl_Position = projectionMatrix * mvPosition;"; + +var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif"; + +var dithering_pars_fragment = "#ifdef DITHERING\n\tvec3 dithering( vec3 color ) {\n\t\tfloat grid_position = rand( gl_FragCoord.xy );\n\t\tvec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n\t\tdither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n\t\treturn color + dither_shift_RGB;\n\t}\n#endif"; + +var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );\n\troughnessFactor *= texelRoughness.g;\n#endif"; + +var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif"; + +var shadowmap_pars_fragment = "#if NUM_SPOT_LIGHT_COORDS > 0\n\tvarying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#if NUM_SPOT_LIGHT_MAPS > 0\n\tuniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_SUN_LIGHT_SHADOWS > 0\n\t\t#define SUN_LIGHT_CASCADES 2\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tuniform sampler2DShadow sunShadowMap[ NUM_SUN_LIGHT_SHADOWS ];\n\t\t#else\n\t\t\tuniform sampler2D sunShadowMap[ NUM_SUN_LIGHT_SHADOWS ];\n\t\t#endif\n\t\tuniform mat4 sunShadowMatrix[ NUM_SUN_LIGHT_SHADOWS * SUN_LIGHT_CASCADES ];\n\t\tuniform vec4 sunShadowCascade[ NUM_SUN_LIGHT_SHADOWS * SUN_LIGHT_CASCADES ];\n\t\tvarying vec4 vSunShadowWorldPosition;\n\t\tvarying vec3 vSunShadowWorldNormal;\n\t\tstruct SunLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SunLightShadow sunLightShadows[ NUM_SUN_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tuniform sampler2DShadow directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\t#else\n\t\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\t#endif\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tuniform sampler2DShadow spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\t#else\n\t\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\t#endif\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tuniform samplerCubeShadow pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\t#elif defined( SHADOWMAP_TYPE_BASIC )\n\t\t\tuniform samplerCube pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\t#endif\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\tfloat interleavedGradientNoise( vec2 position ) {\n\t\t\treturn fract( 52.9829189 * fract( dot( position, vec2( 0.06711056, 0.00583715 ) ) ) );\n\t\t}\n\t\tvec2 vogelDiskSample( int sampleIndex, int samplesCount, float phi ) {\n\t\t\tconst float goldenAngle = 2.399963229728653;\n\t\t\tfloat r = sqrt( ( float( sampleIndex ) + 0.5 ) / float( samplesCount ) );\n\t\t\tfloat theta = float( sampleIndex ) * goldenAngle + phi;\n\t\t\treturn vec2( cos( theta ), sin( theta ) ) * r;\n\t\t}\n\t#endif\n\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\tfloat getShadow( sampler2DShadow shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\t\tfloat shadow = 1.0;\n\t\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\t\tshadowCoord.z += shadowBias;\n\t\t\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n\t\t\tif ( frustumTest ) {\n\t\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\t\tfloat radius = shadowRadius * texelSize.x;\n\t\t\t\tfloat phi = interleavedGradientNoise( gl_FragCoord.xy ) * PI2;\n\t\t\t\tshadow = (\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 0, 5, phi ) * radius, shadowCoord.z ) ) +\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 1, 5, phi ) * radius, shadowCoord.z ) ) +\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 2, 5, phi ) * radius, shadowCoord.z ) ) +\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 3, 5, phi ) * radius, shadowCoord.z ) ) +\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 4, 5, phi ) * radius, shadowCoord.z ) )\n\t\t\t\t) * 0.2;\n\t\t\t}\n\t\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t\t}\n\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\t\tfloat shadow = 1.0;\n\t\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\tshadowCoord.z -= shadowBias;\n\t\t\t#else\n\t\t\t\tshadowCoord.z += shadowBias;\n\t\t\t#endif\n\t\t\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n\t\t\tif ( frustumTest ) {\n\t\t\t\tvec2 distribution = texture2D( shadowMap, shadowCoord.xy ).rg;\n\t\t\t\tfloat mean = distribution.x;\n\t\t\t\tfloat variance = distribution.y * distribution.y;\n\t\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\t\tfloat hard_shadow = step( mean, shadowCoord.z );\n\t\t\t\t#else\n\t\t\t\t\tfloat hard_shadow = step( shadowCoord.z, mean );\n\t\t\t\t#endif\n\t\t\t\t\n\t\t\t\tif ( hard_shadow == 1.0 ) {\n\t\t\t\t\tshadow = 1.0;\n\t\t\t\t} else {\n\t\t\t\t\tvariance = max( variance, 0.0000001 );\n\t\t\t\t\tfloat d = shadowCoord.z - mean;\n\t\t\t\t\tfloat p_max = variance / ( variance + d * d );\n\t\t\t\t\tp_max = clamp( ( p_max - 0.3 ) / 0.65, 0.0, 1.0 );\n\t\t\t\t\tshadow = max( hard_shadow, p_max );\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t\t}\n\t#else\n\t\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\t\tfloat shadow = 1.0;\n\t\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\tshadowCoord.z -= shadowBias;\n\t\t\t#else\n\t\t\t\tshadowCoord.z += shadowBias;\n\t\t\t#endif\n\t\t\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n\t\t\tif ( frustumTest ) {\n\t\t\t\tfloat depth = texture2D( shadowMap, shadowCoord.xy ).r;\n\t\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\t\tshadow = step( depth, shadowCoord.z );\n\t\t\t\t#else\n\t\t\t\t\tshadow = step( shadowCoord.z, depth );\n\t\t\t\t#endif\n\t\t\t}\n\t\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t\t}\n\t#endif\n\t#if NUM_SUN_LIGHT_SHADOWS > 0\n\t\tfloat getSunShadow(\n\t\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\t\tsampler2DShadow shadowMap,\n\t\t\t#else\n\t\t\t\tsampler2D shadowMap,\n\t\t\t#endif\n\t\t\tSunLightShadow sunLightShadow,\n\t\t\tint shadowIndex\n\t\t) {\n\t\t\tvec4 shadowWorldPosition = vec4( vSunShadowWorldPosition.xyz + vSunShadowWorldNormal * sunLightShadow.shadowNormalBias, 1.0 );\n\t\t\tfloat viewDepth = vSunShadowWorldPosition.w;\n\t\t\tint cascadeOffset = shadowIndex * SUN_LIGHT_CASCADES;\n\t\t\tfloat shadow = 1.0;\n\t\t\tfor ( int i = SUN_LIGHT_CASCADES - 1; i >= 0; i -- ) {\n\t\t\t\tvec4 cascade = sunShadowCascade[ cascadeOffset + i ];\n\t\t\t\tif ( viewDepth >= cascade.x && viewDepth < cascade.y ) {\n\t\t\t\t\tfloat cascadeShadow = getShadow(\n\t\t\t\t\t\tshadowMap,\n\t\t\t\t\t\tsunLightShadow.shadowMapSize,\n\t\t\t\t\t\tsunLightShadow.shadowIntensity,\n\t\t\t\t\t\tsunLightShadow.shadowBias,\n\t\t\t\t\t\tsunLightShadow.shadowRadius,\n\t\t\t\t\t\tsunShadowMatrix[ cascadeOffset + i ] * shadowWorldPosition\n\t\t\t\t\t);\n\t\t\t\t\tshadow = mix( cascadeShadow, shadow, smoothstep( cascade.z, cascade.y, viewDepth ) );\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn shadow;\n\t\t}\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t#if defined( SHADOWMAP_TYPE_PCF )\n\tfloat getPointShadow( samplerCubeShadow shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tfloat shadow = 1.0;\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\tvec3 absVec = abs( lightToPosition );\n\t\tfloat viewSpaceZ = max( max( absVec.x, absVec.y ), absVec.z );\n\t\tif ( viewSpaceZ - shadowCameraFar <= 0.0 && viewSpaceZ - shadowCameraNear >= 0.0 ) {\n\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\tfloat dp = ( shadowCameraNear * ( shadowCameraFar - viewSpaceZ ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) );\n\t\t\t\tdp -= shadowBias;\n\t\t\t#else\n\t\t\t\tfloat dp = ( shadowCameraFar * ( viewSpaceZ - shadowCameraNear ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) );\n\t\t\t\tdp += shadowBias;\n\t\t\t#endif\n\t\t\tfloat texelSize = shadowRadius / shadowMapSize.x;\n\t\t\tvec3 absDir = abs( bd3D );\n\t\t\tvec3 tangent = absDir.x > absDir.z ? vec3( 0.0, 1.0, 0.0 ) : vec3( 1.0, 0.0, 0.0 );\n\t\t\ttangent = normalize( cross( bd3D, tangent ) );\n\t\t\tvec3 bitangent = cross( bd3D, tangent );\n\t\t\tfloat phi = interleavedGradientNoise( gl_FragCoord.xy ) * PI2;\n\t\t\tvec2 sample0 = vogelDiskSample( 0, 5, phi );\n\t\t\tvec2 sample1 = vogelDiskSample( 1, 5, phi );\n\t\t\tvec2 sample2 = vogelDiskSample( 2, 5, phi );\n\t\t\tvec2 sample3 = vogelDiskSample( 3, 5, phi );\n\t\t\tvec2 sample4 = vogelDiskSample( 4, 5, phi );\n\t\t\tshadow = (\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * sample0.x + bitangent * sample0.y ) * texelSize, dp ) ) +\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * sample1.x + bitangent * sample1.y ) * texelSize, dp ) ) +\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * sample2.x + bitangent * sample2.y ) * texelSize, dp ) ) +\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * sample3.x + bitangent * sample3.y ) * texelSize, dp ) ) +\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * sample4.x + bitangent * sample4.y ) * texelSize, dp ) )\n\t\t\t) * 0.2;\n\t\t}\n\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t}\n\t#elif defined( SHADOWMAP_TYPE_BASIC )\n\tfloat getPointShadow( samplerCube shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tfloat shadow = 1.0;\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tvec3 absVec = abs( lightToPosition );\n\t\tfloat viewSpaceZ = max( max( absVec.x, absVec.y ), absVec.z );\n\t\tif ( viewSpaceZ - shadowCameraFar <= 0.0 && viewSpaceZ - shadowCameraNear >= 0.0 ) {\n\t\t\tfloat dp = ( shadowCameraFar * ( viewSpaceZ - shadowCameraNear ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) );\n\t\t\tdp += shadowBias;\n\t\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t\tfloat depth = textureCube( shadowMap, bd3D ).r;\n\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\tdepth = 1.0 - depth;\n\t\t\t#endif\n\t\t\tshadow = step( dp, depth );\n\t\t}\n\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t}\n\t#endif\n\t#endif\n#endif"; + +var shadowmap_pars_vertex = "#if NUM_SPOT_LIGHT_COORDS > 0\n\tuniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];\n\tvarying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_SUN_LIGHT_SHADOWS > 0\n\t\tvarying vec4 vSunShadowWorldPosition;\n\t\tvarying vec3 vSunShadowWorldNormal;\n\t#endif\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n#endif"; + +var shadowmap_vertex = "#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_SUN_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )\n\t#ifdef HAS_NORMAL\n\t\tvec3 shadowWorldNormal = transformNormalByInverseViewMatrix( transformedNormal, viewMatrix );\n\t#else\n\t\tvec3 shadowWorldNormal = vec3( 0.0 );\n\t#endif\n\tvec4 shadowWorldPosition;\n#endif\n#if defined( USE_SHADOWMAP )\n\t#if NUM_SUN_LIGHT_SHADOWS > 0\n\t\tvSunShadowWorldPosition = vec4( worldPosition.xyz, - mvPosition.z );\n\t\tvSunShadowWorldNormal = shadowWorldNormal;\n\t#endif\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n\t\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n\t\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if NUM_SPOT_LIGHT_COORDS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition;\n\t\t#if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t\tshadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias;\n\t\t#endif\n\t\tvSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n#endif"; + +var shadowmask_pars_fragment = "float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_SUN_LIGHT_SHADOWS > 0\n\tSunLightShadow sunLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SUN_LIGHT_SHADOWS; i ++ ) {\n\t\tsunLight = sunLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getSunShadow( sunShadowMap[ i ], sunLight, UNROLLED_LOOP_INDEX ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0 && ( defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_BASIC ) )\n\tPointLightShadow pointLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#endif\n\treturn shadow;\n}"; + +var skinbase_vertex = "#ifdef USE_SKINNING\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif"; + +var skinning_pars_vertex = "#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\tuniform highp sampler2D boneTexture;\n\tmat4 getBoneMatrix( const in float i ) {\n\t\tint size = textureSize( boneTexture, 0 ).x;\n\t\tint j = int( i ) * 4;\n\t\tint x = j % size;\n\t\tint y = j / size;\n\t\tvec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 );\n\t\tvec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 );\n\t\tvec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 );\n\t\tvec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 );\n\t\treturn mat4( v1, v2, v3, v4 );\n\t}\n#endif"; + +var skinning_vertex = "#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n#endif"; + +var skinnormal_vertex = "#ifdef USE_SKINNING\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n\t#ifdef USE_TANGENT\n\t\tobjectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#endif\n#endif"; + +var specularmap_fragment = "float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vSpecularMapUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif"; + +var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif"; + +var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif"; + +var tonemapping_pars_fragment = "#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn saturate( toneMappingExposure * color );\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\nvec3 CineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\nvec3 RRTAndODTFit( vec3 v ) {\n\tvec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n\tvec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n\treturn a / b;\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n\tconst mat3 ACESInputMat = mat3(\n\t\tvec3( 0.59719, 0.07600, 0.02840 ),\t\tvec3( 0.35458, 0.90834, 0.13383 ),\n\t\tvec3( 0.04823, 0.01566, 0.83777 )\n\t);\n\tconst mat3 ACESOutputMat = mat3(\n\t\tvec3( 1.60475, -0.10208, -0.00327 ),\t\tvec3( -0.53108, 1.10813, -0.07276 ),\n\t\tvec3( -0.07367, -0.00605, 1.07602 )\n\t);\n\tcolor *= toneMappingExposure / 0.6;\n\tcolor = ACESInputMat * color;\n\tcolor = RRTAndODTFit( color );\n\tcolor = ACESOutputMat * color;\n\treturn saturate( color );\n}\nconst mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3(\n\tvec3( 1.6605, - 0.1246, - 0.0182 ),\n\tvec3( - 0.5876, 1.1329, - 0.1006 ),\n\tvec3( - 0.0728, - 0.0083, 1.1187 )\n);\nconst mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3(\n\tvec3( 0.6274, 0.0691, 0.0164 ),\n\tvec3( 0.3293, 0.9195, 0.0880 ),\n\tvec3( 0.0433, 0.0113, 0.8956 )\n);\nvec3 agxDefaultContrastApprox( vec3 x ) {\n\tvec3 x2 = x * x;\n\tvec3 x4 = x2 * x2;\n\treturn + 15.5 * x4 * x2\n\t\t- 40.14 * x4 * x\n\t\t+ 31.96 * x4\n\t\t- 6.868 * x2 * x\n\t\t+ 0.4298 * x2\n\t\t+ 0.1191 * x\n\t\t- 0.00232;\n}\nvec3 AgXToneMapping( vec3 color ) {\n\tconst mat3 AgXInsetMatrix = mat3(\n\t\tvec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ),\n\t\tvec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ),\n\t\tvec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 )\n\t);\n\tconst mat3 AgXOutsetMatrix = mat3(\n\t\tvec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ),\n\t\tvec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ),\n\t\tvec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 )\n\t);\n\tconst float AgxMinEv = - 12.47393;\tconst float AgxMaxEv = 4.026069;\n\tcolor *= toneMappingExposure;\n\tcolor = LINEAR_SRGB_TO_LINEAR_REC2020 * color;\n\tcolor = AgXInsetMatrix * color;\n\tcolor = max( color, 1e-10 );\tcolor = log2( color );\n\tcolor = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv );\n\tcolor = clamp( color, 0.0, 1.0 );\n\tcolor = agxDefaultContrastApprox( color );\n\tcolor = AgXOutsetMatrix * color;\n\tcolor = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) );\n\tcolor = LINEAR_REC2020_TO_LINEAR_SRGB * color;\n\tcolor = clamp( color, 0.0, 1.0 );\n\treturn color;\n}\nvec3 NeutralToneMapping( vec3 color ) {\n\tconst float StartCompression = 0.8 - 0.04;\n\tconst float Desaturation = 0.15;\n\tcolor *= toneMappingExposure;\n\tfloat x = min( color.r, min( color.g, color.b ) );\n\tfloat offset = x < 0.08 ? x - 6.25 * x * x : 0.04;\n\tcolor -= offset;\n\tfloat peak = max( color.r, max( color.g, color.b ) );\n\tif ( peak < StartCompression ) return color;\n\tfloat d = 1. - StartCompression;\n\tfloat newPeak = 1. - d * d / ( peak + d - StartCompression );\n\tcolor *= newPeak / peak;\n\tfloat g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. );\n\treturn mix( color, vec3( newPeak ), g );\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }"; + +var transmission_fragment = "#ifdef USE_TRANSMISSION\n\tmaterial.transmission = transmission;\n\tmaterial.transmissionAlpha = 1.0;\n\tmaterial.thickness = thickness;\n\tmaterial.attenuationDistance = attenuationDistance;\n\tmaterial.attenuationColor = attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tmaterial.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tmaterial.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g;\n\t#endif\n\tvec3 pos = vWorldPosition;\n\tvec3 v = normalize( cameraPosition - pos );\n\tvec3 n = transformNormalByInverseViewMatrix( normal, viewMatrix );\n\tvec4 transmitted = getIBLVolumeRefraction(\n\t\tn, v, material.roughness, material.diffuseContribution, material.specularColorBlended, material.specularF90,\n\t\tpos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness,\n\t\tmaterial.attenuationColor, material.attenuationDistance );\n\tmaterial.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission );\n\ttotalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission );\n#endif"; + +var transmission_pars_fragment = "#ifdef USE_TRANSMISSION\n\tuniform float transmission;\n\tuniform float thickness;\n\tuniform float attenuationDistance;\n\tuniform vec3 attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tuniform sampler2D transmissionMap;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tuniform sampler2D thicknessMap;\n\t#endif\n\tuniform vec2 transmissionSamplerSize;\n\tuniform sampler2D transmissionSamplerMap;\n\tuniform mat4 modelMatrix;\n\tuniform mat4 projectionMatrix;\n\tvarying vec3 vWorldPosition;\n\tfloat w0( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 );\n\t}\n\tfloat w1( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 );\n\t}\n\tfloat w2( float a ){\n\t\treturn ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 );\n\t}\n\tfloat w3( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * a * a );\n\t}\n\tfloat g0( float a ) {\n\t\treturn w0( a ) + w1( a );\n\t}\n\tfloat g1( float a ) {\n\t\treturn w2( a ) + w3( a );\n\t}\n\tfloat h0( float a ) {\n\t\treturn - 1.0 + w1( a ) / ( w0( a ) + w1( a ) );\n\t}\n\tfloat h1( float a ) {\n\t\treturn 1.0 + w3( a ) / ( w2( a ) + w3( a ) );\n\t}\n\tvec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) {\n\t\tuv = uv * texelSize.zw + 0.5;\n\t\tvec2 iuv = floor( uv );\n\t\tvec2 fuv = fract( uv );\n\t\tfloat g0x = g0( fuv.x );\n\t\tfloat g1x = g1( fuv.x );\n\t\tfloat h0x = h0( fuv.x );\n\t\tfloat h1x = h1( fuv.x );\n\t\tfloat h0y = h0( fuv.y );\n\t\tfloat h1y = h1( fuv.y );\n\t\tvec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n\t\treturn g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) +\n\t\t\tg1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) );\n\t}\n\tvec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) {\n\t\tvec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) );\n\t\tvec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) );\n\t\tvec2 fLodSizeInv = 1.0 / fLodSize;\n\t\tvec2 cLodSizeInv = 1.0 / cLodSize;\n\t\tvec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) );\n\t\tvec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) );\n\t\treturn mix( fSample, cSample, fract( lod ) );\n\t}\n\tvec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {\n\t\tvec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );\n\t\tvec3 modelScale;\n\t\tmodelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );\n\t\tmodelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );\n\t\tmodelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );\n\t\treturn normalize( refractionVector ) * thickness * modelScale;\n\t}\n\tfloat applyIorToRoughness( const in float roughness, const in float ior ) {\n\t\treturn roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n\t}\n\tvec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {\n\t\tfloat lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n\t\treturn textureBicubic( transmissionSamplerMap, fragCoord.xy, lod );\n\t}\n\tvec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tif ( isinf( attenuationDistance ) ) {\n\t\t\treturn vec3( 1.0 );\n\t\t} else {\n\t\t\tvec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n\t\t\tvec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );\t\t\treturn transmittance;\n\t\t}\n\t}\n\tvec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,\n\t\tconst in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,\n\t\tconst in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness,\n\t\tconst in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tvec4 transmittedLight;\n\t\tvec3 transmittance;\n\t\t#ifdef USE_DISPERSION\n\t\t\tfloat halfSpread = ( ior - 1.0 ) * 0.025 * dispersion;\n\t\t\tvec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread );\n\t\t\tfor ( int i = 0; i < 3; i ++ ) {\n\t\t\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix );\n\t\t\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\t\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\t\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\t\t\trefractionCoords += 1.0;\n\t\t\t\trefractionCoords /= 2.0;\n\t\t\t\tvec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] );\n\t\t\t\ttransmittedLight[ i ] = transmissionSample[ i ];\n\t\t\t\ttransmittedLight.a += transmissionSample.a;\n\t\t\t\ttransmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ];\n\t\t\t}\n\t\t\ttransmittedLight.a /= 3.0;\n\t\t#else\n\t\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n\t\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\t\trefractionCoords += 1.0;\n\t\t\trefractionCoords /= 2.0;\n\t\t\ttransmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n\t\t\ttransmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance );\n\t\t#endif\n\t\tvec3 attenuatedColor = transmittance * transmittedLight.rgb;\n\t\tvec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n\t\tfloat transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0;\n\t\treturn vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor );\n\t}\n#endif"; + +var uv_pars_fragment = "#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvarying vec2 vUv;\n#endif\n#ifdef USE_MAP\n\tvarying vec2 vMapUv;\n#endif\n#ifdef USE_ALPHAMAP\n\tvarying vec2 vAlphaMapUv;\n#endif\n#ifdef USE_LIGHTMAP\n\tvarying vec2 vLightMapUv;\n#endif\n#ifdef USE_AOMAP\n\tvarying vec2 vAoMapUv;\n#endif\n#ifdef USE_BUMPMAP\n\tvarying vec2 vBumpMapUv;\n#endif\n#ifdef USE_NORMALMAP\n\tvarying vec2 vNormalMapUv;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tvarying vec2 vEmissiveMapUv;\n#endif\n#ifdef USE_METALNESSMAP\n\tvarying vec2 vMetalnessMapUv;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tvarying vec2 vRoughnessMapUv;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tvarying vec2 vAnisotropyMapUv;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tvarying vec2 vClearcoatMapUv;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tvarying vec2 vClearcoatNormalMapUv;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tvarying vec2 vClearcoatRoughnessMapUv;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tvarying vec2 vIridescenceMapUv;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tvarying vec2 vIridescenceThicknessMapUv;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tvarying vec2 vSheenColorMapUv;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tvarying vec2 vSheenRoughnessMapUv;\n#endif\n#ifdef USE_SPECULARMAP\n\tvarying vec2 vSpecularMapUv;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tvarying vec2 vSpecularColorMapUv;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tvarying vec2 vSpecularIntensityMapUv;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tuniform mat3 transmissionMapTransform;\n\tvarying vec2 vTransmissionMapUv;\n#endif\n#ifdef USE_THICKNESSMAP\n\tuniform mat3 thicknessMapTransform;\n\tvarying vec2 vThicknessMapUv;\n#endif"; + +var uv_pars_vertex = "#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvarying vec2 vUv;\n#endif\n#ifdef USE_MAP\n\tuniform mat3 mapTransform;\n\tvarying vec2 vMapUv;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform mat3 alphaMapTransform;\n\tvarying vec2 vAlphaMapUv;\n#endif\n#ifdef USE_LIGHTMAP\n\tuniform mat3 lightMapTransform;\n\tvarying vec2 vLightMapUv;\n#endif\n#ifdef USE_AOMAP\n\tuniform mat3 aoMapTransform;\n\tvarying vec2 vAoMapUv;\n#endif\n#ifdef USE_BUMPMAP\n\tuniform mat3 bumpMapTransform;\n\tvarying vec2 vBumpMapUv;\n#endif\n#ifdef USE_NORMALMAP\n\tuniform mat3 normalMapTransform;\n\tvarying vec2 vNormalMapUv;\n#endif\n#ifdef USE_DISPLACEMENTMAP\n\tuniform mat3 displacementMapTransform;\n\tvarying vec2 vDisplacementMapUv;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tuniform mat3 emissiveMapTransform;\n\tvarying vec2 vEmissiveMapUv;\n#endif\n#ifdef USE_METALNESSMAP\n\tuniform mat3 metalnessMapTransform;\n\tvarying vec2 vMetalnessMapUv;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tuniform mat3 roughnessMapTransform;\n\tvarying vec2 vRoughnessMapUv;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tuniform mat3 anisotropyMapTransform;\n\tvarying vec2 vAnisotropyMapUv;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tuniform mat3 clearcoatMapTransform;\n\tvarying vec2 vClearcoatMapUv;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform mat3 clearcoatNormalMapTransform;\n\tvarying vec2 vClearcoatNormalMapUv;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform mat3 clearcoatRoughnessMapTransform;\n\tvarying vec2 vClearcoatRoughnessMapUv;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tuniform mat3 sheenColorMapTransform;\n\tvarying vec2 vSheenColorMapUv;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tuniform mat3 sheenRoughnessMapTransform;\n\tvarying vec2 vSheenRoughnessMapUv;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tuniform mat3 iridescenceMapTransform;\n\tvarying vec2 vIridescenceMapUv;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform mat3 iridescenceThicknessMapTransform;\n\tvarying vec2 vIridescenceThicknessMapUv;\n#endif\n#ifdef USE_SPECULARMAP\n\tuniform mat3 specularMapTransform;\n\tvarying vec2 vSpecularMapUv;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tuniform mat3 specularColorMapTransform;\n\tvarying vec2 vSpecularColorMapUv;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tuniform mat3 specularIntensityMapTransform;\n\tvarying vec2 vSpecularIntensityMapUv;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tuniform mat3 transmissionMapTransform;\n\tvarying vec2 vTransmissionMapUv;\n#endif\n#ifdef USE_THICKNESSMAP\n\tuniform mat3 thicknessMapTransform;\n\tvarying vec2 vThicknessMapUv;\n#endif"; + +var uv_vertex = "#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvUv = vec3( uv, 1 ).xy;\n#endif\n#ifdef USE_MAP\n\tvMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ALPHAMAP\n\tvAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_LIGHTMAP\n\tvLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_AOMAP\n\tvAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_BUMPMAP\n\tvBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_NORMALMAP\n\tvNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_DISPLACEMENTMAP\n\tvDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tvEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_METALNESSMAP\n\tvMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tvRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tvAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tvClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tvClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tvClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tvIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tvIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tvSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tvSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULARMAP\n\tvSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tvSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tvSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tvTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_THICKNESSMAP\n\tvThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy;\n#endif"; + +var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0\n\tvec4 worldPosition = vec4( transformed, 1.0 );\n\t#ifdef USE_BATCHING\n\t\tworldPosition = batchingMatrix * worldPosition;\n\t#endif\n\t#ifdef USE_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif"; + +const vertex$h = "varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\n}"; + +const fragment$h = "uniform sampler2D t2D;\nuniform float backgroundIntensity;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\ttexColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w );\n\t#endif\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include \n\t#include \n}"; + +const vertex$g = "varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n\tgl_Position.z = gl_Position.w;\n}"; + +const fragment$g = "#ifdef ENVMAP_TYPE_CUBE\n\tuniform samplerCube envMap;\n#elif defined( ENVMAP_TYPE_CUBE_UV )\n\tuniform sampler2D envMap;\n#endif\nuniform float backgroundBlurriness;\nuniform float backgroundIntensity;\nuniform mat3 backgroundRotation;\nvarying vec3 vWorldDirection;\n#include \nvoid main() {\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 texColor = textureCube( envMap, backgroundRotation * vWorldDirection );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness );\n\t#else\n\t\tvec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t#endif\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include \n\t#include \n}"; + +const vertex$f = "varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n\tgl_Position.z = gl_Position.w;\n}"; + +const fragment$f = "uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldDirection;\nvoid main() {\n\tvec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );\n\tgl_FragColor = texColor;\n\tgl_FragColor.a *= opacity;\n\t#include \n\t#include \n}"; + +const vertex$e = "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvHighPrecisionZW = gl_Position.zw;\n}"; + +const fragment$e = "#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include \n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\tfloat fragCoordZ = vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ];\n\t#else\n\t\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ] + 0.5;\n\t#endif\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#elif DEPTH_PACKING == 3202\n\t\tgl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 );\n\t#elif DEPTH_PACKING == 3203\n\t\tgl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 );\n\t#endif\n}"; + +const vertex$d = "#define DISTANCE\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvWorldPosition = worldPosition.xyz;\n}"; + +const fragment$d = "#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = vec4( dist, 0.0, 0.0, 1.0 );\n}"; + +const vertex$c = "varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n}"; + +const fragment$c = "uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\t#include \n\t#include \n}"; + +const vertex$b = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvLineDistance = scale * lineDistance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const fragment$b = "uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const vertex$a = "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )\n\t\t#include \n\t\t#include \n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const fragment$a = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n\t\treflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include \n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const vertex$9 = "#define LAMBERT\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const fragment$9 = "#define LAMBERT\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const vertex$8 = "#define MATCAP\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n}"; + +const fragment$8 = "#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t#else\n\t\tvec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const vertex$7 = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvarying vec3 vViewPosition;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}"; + +const fragment$7 = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvarying vec3 vViewPosition;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\tgl_FragColor = vec4( normalize( normal ) * 0.5 + 0.5, diffuseColor.a );\n\t#ifdef OPAQUE\n\t\tgl_FragColor.a = 1.0;\n\t#endif\n}"; + +const vertex$6 = "#define PHONG\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const fragment$6 = "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const vertex$5 = "#define STANDARD\nvarying vec3 vViewPosition;\n#ifdef USE_TRANSMISSION\n\tvarying vec3 vWorldPosition;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n#ifdef USE_TRANSMISSION\n\tvWorldPosition = worldPosition.xyz;\n#endif\n}"; + +const fragment$5 = "#define STANDARD\n#ifdef PHYSICAL\n\t#define IOR\n\t#define USE_SPECULAR\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef IOR\n\tuniform float ior;\n#endif\n#ifdef USE_SPECULAR\n\tuniform float specularIntensity;\n\tuniform vec3 specularColor;\n\t#ifdef USE_SPECULAR_COLORMAP\n\t\tuniform sampler2D specularColorMap;\n\t#endif\n\t#ifdef USE_SPECULAR_INTENSITYMAP\n\t\tuniform sampler2D specularIntensityMap;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_DISPERSION\n\tuniform float dispersion;\n#endif\n#ifdef USE_RETROREFLECTION\n\tuniform float retroreflectivity;\n#endif\n#ifdef USE_IRIDESCENCE\n\tuniform float iridescence;\n\tuniform float iridescenceIOR;\n\tuniform float iridescenceThicknessMinimum;\n\tuniform float iridescenceThicknessMaximum;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheenColor;\n\tuniform float sheenRoughness;\n\t#ifdef USE_SHEEN_COLORMAP\n\t\tuniform sampler2D sheenColorMap;\n\t#endif\n\t#ifdef USE_SHEEN_ROUGHNESSMAP\n\t\tuniform sampler2D sheenRoughnessMap;\n\t#endif\n#endif\n#ifdef USE_ANISOTROPY\n\tuniform vec2 anisotropyVector;\n\t#ifdef USE_ANISOTROPYMAP\n\t\tuniform sampler2D anisotropyMap;\n\t#endif\n#endif\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\tvec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n\t#include \n\tvec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;\n\t#ifdef USE_SHEEN\n \n\t\toutgoingLight = outgoingLight + sheenSpecularDirect + sheenSpecularIndirect;\n \n \t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) );\n\t\tvec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );\n\t\toutgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const vertex$4 = "#define TOON\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n}"; + +const fragment$4 = "#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const vertex$3 = "uniform float size;\nuniform float scale;\n#include \n#include \n#include \n#include \n#include \n#include \n#ifdef USE_POINTS_UV\n\tvarying vec2 vUv;\n\tuniform mat3 uvTransform;\n#endif\nvoid main() {\n\t#ifdef USE_POINTS_UV\n\t\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tgl_PointSize = size;\n\t#ifdef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const fragment$3 = "uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const vertex$2 = "#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const fragment$2 = "uniform vec3 color;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const vertex$1 = "uniform float rotation;\nuniform vec2 center;\n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 mvPosition = modelViewMatrix[ 3 ];\n\tvec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) );\n\t#ifndef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) scale *= - mvPosition.z;\n\t#endif\n\tvec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\n\tvec2 rotatedPosition;\n\trotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n\trotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n\tmvPosition.xy += rotatedPosition;\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include \n\t#include \n\t#include \n}"; + +const fragment$1 = "uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const ShaderChunk = { + alphahash_fragment: alphahash_fragment, + alphahash_pars_fragment: alphahash_pars_fragment, + alphamap_fragment: alphamap_fragment, + alphamap_pars_fragment: alphamap_pars_fragment, + alphatest_fragment: alphatest_fragment, + alphatest_pars_fragment: alphatest_pars_fragment, + aomap_fragment: aomap_fragment, + aomap_pars_fragment: aomap_pars_fragment, + batching_pars_vertex: batching_pars_vertex, + batching_vertex: batching_vertex, + begin_vertex: begin_vertex, + beginnormal_vertex: beginnormal_vertex, + bsdfs: bsdfs, + iridescence_fragment: iridescence_fragment, + bumpmap_pars_fragment: bumpmap_pars_fragment, + clipping_planes_fragment: clipping_planes_fragment, + clipping_planes_pars_fragment: clipping_planes_pars_fragment, + clipping_planes_pars_vertex: clipping_planes_pars_vertex, + clipping_planes_vertex: clipping_planes_vertex, + color_fragment: color_fragment, + color_pars_fragment: color_pars_fragment, + color_pars_vertex: color_pars_vertex, + color_vertex: color_vertex, + common: common, + cube_uv_reflection_fragment: cube_uv_reflection_fragment, + defaultnormal_vertex: defaultnormal_vertex, + displacementmap_pars_vertex: displacementmap_pars_vertex, + displacementmap_vertex: displacementmap_vertex, + emissivemap_fragment: emissivemap_fragment, + emissivemap_pars_fragment: emissivemap_pars_fragment, + colorspace_fragment: colorspace_fragment, + colorspace_pars_fragment: colorspace_pars_fragment, + envmap_fragment: envmap_fragment, + envmap_common_pars_fragment: envmap_common_pars_fragment, + envmap_pars_fragment: envmap_pars_fragment, + envmap_pars_vertex: envmap_pars_vertex, + envmap_physical_pars_fragment: envmap_physical_pars_fragment, + envmap_vertex: envmap_vertex, + fog_vertex: fog_vertex, + fog_pars_vertex: fog_pars_vertex, + fog_fragment: fog_fragment, + fog_pars_fragment: fog_pars_fragment, + gradientmap_pars_fragment: gradientmap_pars_fragment, + lightmap_pars_fragment: lightmap_pars_fragment, + lights_lambert_fragment: lights_lambert_fragment, + lights_lambert_pars_fragment: lights_lambert_pars_fragment, + lights_pars_begin: lights_pars_begin, + lights_toon_fragment: lights_toon_fragment, + lights_toon_pars_fragment: lights_toon_pars_fragment, + lights_phong_fragment: lights_phong_fragment, + lights_phong_pars_fragment: lights_phong_pars_fragment, + lights_physical_fragment: lights_physical_fragment, + lights_physical_pars_fragment: lights_physical_pars_fragment, + lights_fragment_begin: lights_fragment_begin, + lights_fragment_maps: lights_fragment_maps, + lights_fragment_end: lights_fragment_end, + lightprobes_pars_fragment: lightprobes_pars_fragment, + logdepthbuf_fragment: logdepthbuf_fragment, + logdepthbuf_pars_fragment: logdepthbuf_pars_fragment, + logdepthbuf_pars_vertex: logdepthbuf_pars_vertex, + logdepthbuf_vertex: logdepthbuf_vertex, + map_fragment: map_fragment, + map_pars_fragment: map_pars_fragment, + map_particle_fragment: map_particle_fragment, + map_particle_pars_fragment: map_particle_pars_fragment, + metalnessmap_fragment: metalnessmap_fragment, + metalnessmap_pars_fragment: metalnessmap_pars_fragment, + morphinstance_vertex: morphinstance_vertex, + morphcolor_vertex: morphcolor_vertex, + morphnormal_vertex: morphnormal_vertex, + morphtarget_pars_vertex: morphtarget_pars_vertex, + morphtarget_vertex: morphtarget_vertex, + normal_fragment_begin: normal_fragment_begin, + normal_fragment_maps: normal_fragment_maps, + normal_pars_fragment: normal_pars_fragment, + normal_pars_vertex: normal_pars_vertex, + normal_vertex: normal_vertex, + normalmap_pars_fragment: normalmap_pars_fragment, + clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin, + clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps, + clearcoat_pars_fragment: clearcoat_pars_fragment, + iridescence_pars_fragment: iridescence_pars_fragment, + opaque_fragment: opaque_fragment, + packing: packing, + premultiplied_alpha_fragment: premultiplied_alpha_fragment, + project_vertex: project_vertex, + dithering_fragment: dithering_fragment, + dithering_pars_fragment: dithering_pars_fragment, + roughnessmap_fragment: roughnessmap_fragment, + roughnessmap_pars_fragment: roughnessmap_pars_fragment, + shadowmap_pars_fragment: shadowmap_pars_fragment, + shadowmap_pars_vertex: shadowmap_pars_vertex, + shadowmap_vertex: shadowmap_vertex, + shadowmask_pars_fragment: shadowmask_pars_fragment, + skinbase_vertex: skinbase_vertex, + skinning_pars_vertex: skinning_pars_vertex, + skinning_vertex: skinning_vertex, + skinnormal_vertex: skinnormal_vertex, + specularmap_fragment: specularmap_fragment, + specularmap_pars_fragment: specularmap_pars_fragment, + tonemapping_fragment: tonemapping_fragment, + tonemapping_pars_fragment: tonemapping_pars_fragment, + transmission_fragment: transmission_fragment, + transmission_pars_fragment: transmission_pars_fragment, + uv_pars_fragment: uv_pars_fragment, + uv_pars_vertex: uv_pars_vertex, + uv_vertex: uv_vertex, + worldpos_vertex: worldpos_vertex, + + background_vert: vertex$h, + background_frag: fragment$h, + backgroundCube_vert: vertex$g, + backgroundCube_frag: fragment$g, + cube_vert: vertex$f, + cube_frag: fragment$f, + depth_vert: vertex$e, + depth_frag: fragment$e, + distance_vert: vertex$d, + distance_frag: fragment$d, + equirect_vert: vertex$c, + equirect_frag: fragment$c, + linedashed_vert: vertex$b, + linedashed_frag: fragment$b, + meshbasic_vert: vertex$a, + meshbasic_frag: fragment$a, + meshlambert_vert: vertex$9, + meshlambert_frag: fragment$9, + meshmatcap_vert: vertex$8, + meshmatcap_frag: fragment$8, + meshnormal_vert: vertex$7, + meshnormal_frag: fragment$7, + meshphong_vert: vertex$6, + meshphong_frag: fragment$6, + meshphysical_vert: vertex$5, + meshphysical_frag: fragment$5, + meshtoon_vert: vertex$4, + meshtoon_frag: fragment$4, + points_vert: vertex$3, + points_frag: fragment$3, + shadow_vert: vertex$2, + shadow_frag: fragment$2, + sprite_vert: vertex$1, + sprite_frag: fragment$1 +}; + +// Uniforms library for shared webgl shaders +const UniformsLib = { + + common: { + + diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) }, + opacity: { value: 1.0 }, + + map: { value: null }, + mapTransform: { value: /*@__PURE__*/ new Matrix3() }, + + alphaMap: { value: null }, + alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() }, + + alphaTest: { value: 0 } + + }, + + specularmap: { + + specularMap: { value: null }, + specularMapTransform: { value: /*@__PURE__*/ new Matrix3() } + + }, + + envmap: { + + envMap: { value: null }, + envMapRotation: { value: /*@__PURE__*/ new Matrix3() }, + reflectivity: { value: 1.0 }, // basic, lambert, phong + ior: { value: 1.5 }, // physical + refractionRatio: { value: 0.98 }, // basic, lambert, phong + dfgLUT: { value: null } // DFG LUT for physically-based rendering + + }, + + aomap: { + + aoMap: { value: null }, + aoMapIntensity: { value: 1 }, + aoMapTransform: { value: /*@__PURE__*/ new Matrix3() } + + }, + + lightmap: { + + lightMap: { value: null }, + lightMapIntensity: { value: 1 }, + lightMapTransform: { value: /*@__PURE__*/ new Matrix3() } + + }, + + bumpmap: { + + bumpMap: { value: null }, + bumpMapTransform: { value: /*@__PURE__*/ new Matrix3() }, + bumpScale: { value: 1 } + + }, + + normalmap: { + + normalMap: { value: null }, + normalMapTransform: { value: /*@__PURE__*/ new Matrix3() }, + normalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) } + + }, + + displacementmap: { + + displacementMap: { value: null }, + displacementMapTransform: { value: /*@__PURE__*/ new Matrix3() }, + displacementScale: { value: 1 }, + displacementBias: { value: 0 } + + }, + + emissivemap: { + + emissiveMap: { value: null }, + emissiveMapTransform: { value: /*@__PURE__*/ new Matrix3() } + + }, + + metalnessmap: { + + metalnessMap: { value: null }, + metalnessMapTransform: { value: /*@__PURE__*/ new Matrix3() } + + }, + + roughnessmap: { + + roughnessMap: { value: null }, + roughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() } + + }, + + gradientmap: { + + gradientMap: { value: null } + + }, + + fog: { + + fogDensity: { value: 0.00025 }, + fogNear: { value: 1 }, + fogFar: { value: 2000 }, + fogColor: { value: /*@__PURE__*/ new Color( 0xffffff ) } + + }, + + lights: { + + ambientLightColor: { value: [] }, + + lightProbe: { value: [] }, + + sunLights: { value: [], properties: { + direction: {}, + color: {} + } }, + + sunLightShadows: { value: [], properties: { + shadowIntensity: 1, + shadowBias: {}, + shadowNormalBias: {}, + shadowRadius: {}, + shadowMapSize: {} + } }, + + sunShadowMatrix: { value: [] }, + sunShadowCascade: { value: [] }, + + directionalLights: { value: [], properties: { + direction: {}, + color: {} + } }, + + directionalLightShadows: { value: [], properties: { + shadowIntensity: 1, + shadowBias: {}, + shadowNormalBias: {}, + shadowRadius: {}, + shadowMapSize: {} + } }, + + directionalShadowMatrix: { value: [] }, + + spotLights: { value: [], properties: { + color: {}, + position: {}, + direction: {}, + distance: {}, + coneCos: {}, + penumbraCos: {}, + decay: {} + } }, + + spotLightShadows: { value: [], properties: { + shadowIntensity: 1, + shadowBias: {}, + shadowNormalBias: {}, + shadowRadius: {}, + shadowMapSize: {} + } }, + + spotLightMap: { value: [] }, + spotLightMatrix: { value: [] }, + + pointLights: { value: [], properties: { + color: {}, + position: {}, + decay: {}, + distance: {} + } }, + + pointLightShadows: { value: [], properties: { + shadowIntensity: 1, + shadowBias: {}, + shadowNormalBias: {}, + shadowRadius: {}, + shadowMapSize: {}, + shadowCameraNear: {}, + shadowCameraFar: {} + } }, + + pointShadowMatrix: { value: [] }, + + hemisphereLights: { value: [], properties: { + direction: {}, + skyColor: {}, + groundColor: {} + } }, + + // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src + rectAreaLights: { value: [], properties: { + color: {}, + position: {}, + width: {}, + height: {} + } }, + + ltc_1: { value: null }, + ltc_2: { value: null }, + + probesSH: { value: null }, + probesMin: { value: /*@__PURE__*/ new Vector3() }, + probesMax: { value: /*@__PURE__*/ new Vector3() }, + probesResolution: { value: /*@__PURE__*/ new Vector3() } + + }, + + points: { + + diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) }, + opacity: { value: 1.0 }, + size: { value: 1.0 }, + scale: { value: 1.0 }, + map: { value: null }, + alphaMap: { value: null }, + alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() }, + alphaTest: { value: 0 }, + uvTransform: { value: /*@__PURE__*/ new Matrix3() } + + }, + + sprite: { + + diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) }, + opacity: { value: 1.0 }, + center: { value: /*@__PURE__*/ new Vector2( 0.5, 0.5 ) }, + rotation: { value: 0.0 }, + map: { value: null }, + mapTransform: { value: /*@__PURE__*/ new Matrix3() }, + alphaMap: { value: null }, + alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() }, + alphaTest: { value: 0 } + + } + +}; + +const ShaderLib = { + + basic: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.common, + UniformsLib.specularmap, + UniformsLib.envmap, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.fog + ] ), + + vertexShader: ShaderChunk.meshbasic_vert, + fragmentShader: ShaderChunk.meshbasic_frag + + }, + + lambert: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.common, + UniformsLib.specularmap, + UniformsLib.envmap, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.emissivemap, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + UniformsLib.fog, + UniformsLib.lights, + { + emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }, + envMapIntensity: { value: 1 } + } + ] ), + + vertexShader: ShaderChunk.meshlambert_vert, + fragmentShader: ShaderChunk.meshlambert_frag + + }, + + phong: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.common, + UniformsLib.specularmap, + UniformsLib.envmap, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.emissivemap, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + UniformsLib.fog, + UniformsLib.lights, + { + emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }, + specular: { value: /*@__PURE__*/ new Color( 0x111111 ) }, + shininess: { value: 30 }, + envMapIntensity: { value: 1 } + } + ] ), + + vertexShader: ShaderChunk.meshphong_vert, + fragmentShader: ShaderChunk.meshphong_frag + + }, + + standard: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.common, + UniformsLib.envmap, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.emissivemap, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + UniformsLib.roughnessmap, + UniformsLib.metalnessmap, + UniformsLib.fog, + UniformsLib.lights, + { + emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }, + roughness: { value: 1.0 }, + metalness: { value: 0.0 }, + envMapIntensity: { value: 1 } + } + ] ), + + vertexShader: ShaderChunk.meshphysical_vert, + fragmentShader: ShaderChunk.meshphysical_frag + + }, + + toon: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.common, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.emissivemap, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + UniformsLib.gradientmap, + UniformsLib.fog, + UniformsLib.lights, + { + emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) } + } + ] ), + + vertexShader: ShaderChunk.meshtoon_vert, + fragmentShader: ShaderChunk.meshtoon_frag + + }, + + matcap: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.common, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + UniformsLib.fog, + { + matcap: { value: null } + } + ] ), + + vertexShader: ShaderChunk.meshmatcap_vert, + fragmentShader: ShaderChunk.meshmatcap_frag + + }, + + points: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.points, + UniformsLib.fog + ] ), + + vertexShader: ShaderChunk.points_vert, + fragmentShader: ShaderChunk.points_frag + + }, + + dashed: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.common, + UniformsLib.fog, + { + scale: { value: 1 }, + dashSize: { value: 1 }, + totalSize: { value: 2 } + } + ] ), + + vertexShader: ShaderChunk.linedashed_vert, + fragmentShader: ShaderChunk.linedashed_frag + + }, + + depth: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.common, + UniformsLib.displacementmap + ] ), + + vertexShader: ShaderChunk.depth_vert, + fragmentShader: ShaderChunk.depth_frag + + }, + + normal: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.common, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + { + opacity: { value: 1.0 } + } + ] ), + + vertexShader: ShaderChunk.meshnormal_vert, + fragmentShader: ShaderChunk.meshnormal_frag + + }, + + sprite: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.sprite, + UniformsLib.fog + ] ), + + vertexShader: ShaderChunk.sprite_vert, + fragmentShader: ShaderChunk.sprite_frag + + }, + + background: { + + uniforms: { + uvTransform: { value: /*@__PURE__*/ new Matrix3() }, + t2D: { value: null }, + backgroundIntensity: { value: 1 } + }, + + vertexShader: ShaderChunk.background_vert, + fragmentShader: ShaderChunk.background_frag + + }, + + backgroundCube: { + + uniforms: { + envMap: { value: null }, + backgroundBlurriness: { value: 0 }, + backgroundIntensity: { value: 1 }, + backgroundRotation: { value: /*@__PURE__*/ new Matrix3() } + }, + + vertexShader: ShaderChunk.backgroundCube_vert, + fragmentShader: ShaderChunk.backgroundCube_frag + + }, + + cube: { + + uniforms: { + tCube: { value: null }, + tFlip: { value: -1 }, + opacity: { value: 1.0 } + }, + + vertexShader: ShaderChunk.cube_vert, + fragmentShader: ShaderChunk.cube_frag + + }, + + equirect: { + + uniforms: { + tEquirect: { value: null }, + }, + + vertexShader: ShaderChunk.equirect_vert, + fragmentShader: ShaderChunk.equirect_frag + + }, + + distance: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.common, + UniformsLib.displacementmap, + { + referencePosition: { value: /*@__PURE__*/ new Vector3() }, + nearDistance: { value: 1 }, + farDistance: { value: 1000 } + } + ] ), + + vertexShader: ShaderChunk.distance_vert, + fragmentShader: ShaderChunk.distance_frag + + }, + + shadow: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.lights, + UniformsLib.fog, + { + color: { value: /*@__PURE__*/ new Color( 0x00000 ) }, + opacity: { value: 1.0 } + }, + ] ), + + vertexShader: ShaderChunk.shadow_vert, + fragmentShader: ShaderChunk.shadow_frag + + } + +}; + +ShaderLib.physical = { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + ShaderLib.standard.uniforms, + { + clearcoat: { value: 0 }, + clearcoatMap: { value: null }, + clearcoatMapTransform: { value: /*@__PURE__*/ new Matrix3() }, + clearcoatNormalMap: { value: null }, + clearcoatNormalMapTransform: { value: /*@__PURE__*/ new Matrix3() }, + clearcoatNormalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) }, + clearcoatRoughness: { value: 0 }, + clearcoatRoughnessMap: { value: null }, + clearcoatRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }, + dispersion: { value: 0 }, + retroreflectivity: { value: 0 }, + iridescence: { value: 0 }, + iridescenceMap: { value: null }, + iridescenceMapTransform: { value: /*@__PURE__*/ new Matrix3() }, + iridescenceIOR: { value: 1.3 }, + iridescenceThicknessMinimum: { value: 100 }, + iridescenceThicknessMaximum: { value: 400 }, + iridescenceThicknessMap: { value: null }, + iridescenceThicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() }, + sheen: { value: 0 }, + sheenColor: { value: /*@__PURE__*/ new Color( 0x000000 ) }, + sheenColorMap: { value: null }, + sheenColorMapTransform: { value: /*@__PURE__*/ new Matrix3() }, + sheenRoughness: { value: 1 }, + sheenRoughnessMap: { value: null }, + sheenRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }, + transmission: { value: 0 }, + transmissionMap: { value: null }, + transmissionMapTransform: { value: /*@__PURE__*/ new Matrix3() }, + transmissionSamplerSize: { value: /*@__PURE__*/ new Vector2() }, + transmissionSamplerMap: { value: null }, + thickness: { value: 0 }, + thicknessMap: { value: null }, + thicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() }, + attenuationDistance: { value: 0 }, + attenuationColor: { value: /*@__PURE__*/ new Color( 0x000000 ) }, + specularColor: { value: /*@__PURE__*/ new Color( 1, 1, 1 ) }, + specularColorMap: { value: null }, + specularColorMapTransform: { value: /*@__PURE__*/ new Matrix3() }, + specularIntensity: { value: 1 }, + specularIntensityMap: { value: null }, + specularIntensityMapTransform: { value: /*@__PURE__*/ new Matrix3() }, + anisotropyVector: { value: /*@__PURE__*/ new Vector2() }, + anisotropyMap: { value: null }, + anisotropyMapTransform: { value: /*@__PURE__*/ new Matrix3() }, + } + ] ), + + vertexShader: ShaderChunk.meshphysical_vert, + fragmentShader: ShaderChunk.meshphysical_frag + +}; + +const _rgb = { r: 0, b: 0, g: 0 }; +const _m1$1 = /*@__PURE__*/ new Matrix4(); +const _m$1 = /*@__PURE__*/ new Matrix3(); + +_m$1.set( -1, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0 ); + +function WebGLBackground( renderer, environments, state, objects, alpha, premultipliedAlpha ) { + + const clearColor = new Color( 0x000000 ); + let clearAlpha = alpha === true ? 0 : 1; + + let planeMesh; + let boxMesh; + + let currentBackground = null; + let currentBackgroundVersion = 0; + let currentTonemapping = null; + + function getBackground( scene ) { + + let background = scene.isScene === true ? scene.background : null; + + if ( background && background.isTexture ) { + + const usePMREM = scene.backgroundBlurriness > 0; // use PMREM if the user wants to blur the background + background = environments.get( background, usePMREM ); + + } + + return background; + + } + + function render( scene ) { + + let forceClear = false; + const background = getBackground( scene ); + + if ( background === null ) { + + setClear( clearColor, clearAlpha ); + + } else if ( background && background.isColor ) { + + setClear( background, 1 ); + forceClear = true; + + } + + const environmentBlendMode = renderer.xr.getEnvironmentBlendMode(); + + if ( environmentBlendMode === 'additive' ) { + + state.buffers.color.setClear( 0, 0, 0, 1, premultipliedAlpha ); + + } else if ( environmentBlendMode === 'alpha-blend' ) { + + state.buffers.color.setClear( 0, 0, 0, 0, premultipliedAlpha ); + + } + + if ( renderer.autoClear || forceClear ) { + + // buffers might not be writable which is required to ensure a correct clear + + state.buffers.depth.setTest( true ); + state.buffers.depth.setMask( true ); + state.buffers.color.setMask( true ); + + renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil ); + + } + + } + + function addToRenderList( renderList, scene ) { + + const background = getBackground( scene ); + + if ( background && ( background.isCubeTexture || background.mapping === CubeUVReflectionMapping ) ) { + + if ( boxMesh === undefined ) { + + boxMesh = new Mesh( + new BoxGeometry( 1, 1, 1 ), + new ShaderMaterial( { + name: 'BackgroundCubeMaterial', + uniforms: cloneUniforms( ShaderLib.backgroundCube.uniforms ), + vertexShader: ShaderLib.backgroundCube.vertexShader, + fragmentShader: ShaderLib.backgroundCube.fragmentShader, + side: BackSide, + depthTest: false, + depthWrite: false, + fog: false, + allowOverride: false + } ) + ); + + boxMesh.geometry.deleteAttribute( 'normal' ); + boxMesh.geometry.deleteAttribute( 'uv' ); + + boxMesh.onBeforeRender = function ( renderer, scene, camera ) { + + this.matrixWorld.copyPosition( camera.matrixWorld ); + + }; + + // add "envMap" material property so the renderer can evaluate it like for built-in materials + Object.defineProperty( boxMesh.material, 'envMap', { + + get: function () { + + return this.uniforms.envMap.value; + + } + + } ); + + objects.update( boxMesh ); + + } + + + boxMesh.material.uniforms.envMap.value = background; + boxMesh.material.uniforms.backgroundBlurriness.value = scene.backgroundBlurriness; + boxMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity; + + + // note: since the matrix is orthonormal, we can use the more-efficient transpose() in lieu of invert() + boxMesh.material.uniforms.backgroundRotation.value.setFromMatrix4( _m1$1.makeRotationFromEuler( scene.backgroundRotation ) ).transpose(); + + if ( background.isCubeTexture && background.isRenderTargetTexture === false ) { + + boxMesh.material.uniforms.backgroundRotation.value.premultiply( _m$1 ); + + } + + + boxMesh.material.toneMapped = ColorManagement.getTransfer( background.colorSpace ) !== SRGBTransfer; + + if ( currentBackground !== background || + currentBackgroundVersion !== background.version || + currentTonemapping !== renderer.toneMapping ) { + + boxMesh.material.needsUpdate = true; + + currentBackground = background; + currentBackgroundVersion = background.version; + currentTonemapping = renderer.toneMapping; + + } + + boxMesh.layers.enableAll(); + + // push to the pre-sorted opaque render list + renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null ); + + } else if ( background && background.isTexture ) { + + if ( planeMesh === undefined ) { + + planeMesh = new Mesh( + new PlaneGeometry( 2, 2 ), + new ShaderMaterial( { + name: 'BackgroundMaterial', + uniforms: cloneUniforms( ShaderLib.background.uniforms ), + vertexShader: ShaderLib.background.vertexShader, + fragmentShader: ShaderLib.background.fragmentShader, + side: FrontSide, + depthTest: false, + depthWrite: false, + fog: false, + allowOverride: false + } ) + ); + + planeMesh.geometry.deleteAttribute( 'normal' ); + + // add "map" material property so the renderer can evaluate it like for built-in materials + Object.defineProperty( planeMesh.material, 'map', { + + get: function () { + + return this.uniforms.t2D.value; + + } + + } ); + + objects.update( planeMesh ); + + } + + planeMesh.material.uniforms.t2D.value = background; + planeMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity; + planeMesh.material.toneMapped = ColorManagement.getTransfer( background.colorSpace ) !== SRGBTransfer; + + if ( background.matrixAutoUpdate === true ) { + + background.updateMatrix(); + + } + + planeMesh.material.uniforms.uvTransform.value.copy( background.matrix ); + + if ( currentBackground !== background || + currentBackgroundVersion !== background.version || + currentTonemapping !== renderer.toneMapping ) { + + planeMesh.material.needsUpdate = true; + + currentBackground = background; + currentBackgroundVersion = background.version; + currentTonemapping = renderer.toneMapping; + + } + + planeMesh.layers.enableAll(); + + // push to the pre-sorted opaque render list + renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null ); + + } + + } + + function setClear( color, alpha ) { + + color.getRGB( _rgb, getUnlitUniformColorSpace( renderer ) ); + + state.buffers.color.setClear( _rgb.r, _rgb.g, _rgb.b, alpha, premultipliedAlpha ); + + } + + function dispose() { + + if ( boxMesh !== undefined ) { + + boxMesh.geometry.dispose(); + boxMesh.material.dispose(); + + boxMesh = undefined; + + } + + if ( planeMesh !== undefined ) { + + planeMesh.geometry.dispose(); + planeMesh.material.dispose(); + + planeMesh = undefined; + + } + + } + + return { + + getClearColor: function () { + + return clearColor; + + }, + setClearColor: function ( color, alpha = 1 ) { + + clearColor.set( color ); + clearAlpha = alpha; + setClear( clearColor, clearAlpha ); + + }, + getClearAlpha: function () { + + return clearAlpha; + + }, + setClearAlpha: function ( alpha ) { + + clearAlpha = alpha; + setClear( clearColor, clearAlpha ); + + }, + render: render, + addToRenderList: addToRenderList, + dispose: dispose + + }; + +} + +function WebGLBindingStates( gl, attributes ) { + + const maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS ); + + const bindingStates = {}; + + const defaultState = createBindingState( null ); + let currentState = defaultState; + let forceUpdate = false; + + function setup( object, material, program, geometry, index ) { + + let updateBuffers = false; + + const state = getBindingState( object, geometry, program, material ); + + if ( currentState !== state ) { + + currentState = state; + bindVertexArrayObject( currentState.object ); + + } + + updateBuffers = needsUpdate( object, geometry, program, index ); + + if ( updateBuffers ) saveCache( object, geometry, program, index ); + + if ( index !== null ) { + + attributes.update( index, gl.ELEMENT_ARRAY_BUFFER ); + + } + + if ( updateBuffers || forceUpdate ) { + + forceUpdate = false; + + setupVertexAttributes( object, material, program, geometry ); + + if ( index !== null ) { + + gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, attributes.get( index ).buffer ); + + } + + } + + } + + function createVertexArrayObject() { + + return gl.createVertexArray(); + + } + + function bindVertexArrayObject( vao ) { + + return gl.bindVertexArray( vao ); + + } + + function deleteVertexArrayObject( vao ) { + + return gl.deleteVertexArray( vao ); + + } + + function getBindingState( object, geometry, program, material ) { + + const wireframe = ( material.wireframe === true ); + + let objectMap = bindingStates[ geometry.id ]; + + if ( objectMap === undefined ) { + + objectMap = {}; + bindingStates[ geometry.id ] = objectMap; + + } + + // Each InstancedMesh requires unique binding states because it contains instanced attributes. + const objectId = ( object.isInstancedMesh === true ) ? object.id : 0; + + let programMap = objectMap[ objectId ]; + + if ( programMap === undefined ) { + + programMap = {}; + objectMap[ objectId ] = programMap; + + } + + let stateMap = programMap[ program.id ]; + + if ( stateMap === undefined ) { + + stateMap = {}; + programMap[ program.id ] = stateMap; + + } + + let state = stateMap[ wireframe ]; + + if ( state === undefined ) { + + state = createBindingState( createVertexArrayObject() ); + stateMap[ wireframe ] = state; + + } + + return state; + + } + + function createBindingState( vao ) { + + const newAttributes = []; + const enabledAttributes = []; + const attributeDivisors = []; + + for ( let i = 0; i < maxVertexAttributes; i ++ ) { + + newAttributes[ i ] = 0; + enabledAttributes[ i ] = 0; + attributeDivisors[ i ] = 0; + + } + + return { + + // for backward compatibility on non-VAO support browser + geometry: null, + program: null, + wireframe: false, + + newAttributes: newAttributes, + enabledAttributes: enabledAttributes, + attributeDivisors: attributeDivisors, + object: vao, + attributes: {}, + index: null + + }; + + } + + function needsUpdate( object, geometry, program, index ) { + + const cachedAttributes = currentState.attributes; + const geometryAttributes = geometry.attributes; + + let attributesNum = 0; + + const programAttributes = program.getAttributes(); + + for ( const name in programAttributes ) { + + const programAttribute = programAttributes[ name ]; + + if ( programAttribute.location >= 0 ) { + + const cachedAttribute = cachedAttributes[ name ]; + let geometryAttribute = geometryAttributes[ name ]; + + if ( geometryAttribute === undefined ) { + + if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix; + if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor; + + } + + if ( cachedAttribute === undefined ) return true; + + if ( cachedAttribute.attribute !== geometryAttribute ) return true; + + if ( geometryAttribute && cachedAttribute.data !== geometryAttribute.data ) return true; + + attributesNum ++; + + } + + } + + if ( currentState.attributesNum !== attributesNum ) return true; + + if ( currentState.index !== index ) return true; + + return false; + + } + + function saveCache( object, geometry, program, index ) { + + const cache = {}; + const attributes = geometry.attributes; + let attributesNum = 0; + + const programAttributes = program.getAttributes(); + + for ( const name in programAttributes ) { + + const programAttribute = programAttributes[ name ]; + + if ( programAttribute.location >= 0 ) { + + let attribute = attributes[ name ]; + + if ( attribute === undefined ) { + + if ( name === 'instanceMatrix' && object.instanceMatrix ) attribute = object.instanceMatrix; + if ( name === 'instanceColor' && object.instanceColor ) attribute = object.instanceColor; + + } + + const data = {}; + data.attribute = attribute; + + if ( attribute && attribute.data ) { + + data.data = attribute.data; + + } + + cache[ name ] = data; + + attributesNum ++; + + } + + } + + currentState.attributes = cache; + currentState.attributesNum = attributesNum; + + currentState.index = index; + + } + + function initAttributes() { + + const newAttributes = currentState.newAttributes; + + for ( let i = 0, il = newAttributes.length; i < il; i ++ ) { + + newAttributes[ i ] = 0; + + } + + } + + function enableAttribute( attribute ) { + + enableAttributeAndDivisor( attribute, 0 ); + + } + + function enableAttributeAndDivisor( attribute, meshPerAttribute ) { + + const newAttributes = currentState.newAttributes; + const enabledAttributes = currentState.enabledAttributes; + const attributeDivisors = currentState.attributeDivisors; + + newAttributes[ attribute ] = 1; + + if ( enabledAttributes[ attribute ] === 0 ) { + + gl.enableVertexAttribArray( attribute ); + enabledAttributes[ attribute ] = 1; + + } + + if ( attributeDivisors[ attribute ] !== meshPerAttribute ) { + + gl.vertexAttribDivisor( attribute, meshPerAttribute ); + attributeDivisors[ attribute ] = meshPerAttribute; + + } + + } + + function disableUnusedAttributes() { + + const newAttributes = currentState.newAttributes; + const enabledAttributes = currentState.enabledAttributes; + + for ( let i = 0, il = enabledAttributes.length; i < il; i ++ ) { + + if ( enabledAttributes[ i ] !== newAttributes[ i ] ) { + + gl.disableVertexAttribArray( i ); + enabledAttributes[ i ] = 0; + + } + + } + + } + + function vertexAttribPointer( index, size, type, normalized, stride, offset, integer ) { + + if ( integer === true ) { + + gl.vertexAttribIPointer( index, size, type, stride, offset ); + + } else { + + gl.vertexAttribPointer( index, size, type, normalized, stride, offset ); + + } + + } + + function setupVertexAttributes( object, material, program, geometry ) { + + initAttributes(); + + const geometryAttributes = geometry.attributes; + + const programAttributes = program.getAttributes(); + + const materialDefaultAttributeValues = material.defaultAttributeValues; + + for ( const name in programAttributes ) { + + const programAttribute = programAttributes[ name ]; + + if ( programAttribute.location >= 0 ) { + + let geometryAttribute = geometryAttributes[ name ]; + + if ( geometryAttribute === undefined ) { + + if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix; + if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor; + + } + + if ( geometryAttribute !== undefined ) { + + const normalized = geometryAttribute.normalized; + const size = geometryAttribute.itemSize; + + const attribute = attributes.get( geometryAttribute ); + + // TODO Attribute may not be available on context restore + + if ( attribute === undefined ) continue; + + const buffer = attribute.buffer; + const type = attribute.type; + const bytesPerElement = attribute.bytesPerElement; + + // check for integer attributes + + const integer = ( type === gl.INT || type === gl.UNSIGNED_INT || geometryAttribute.gpuType === IntType ); + + if ( geometryAttribute.isInterleavedBufferAttribute ) { + + const data = geometryAttribute.data; + const stride = data.stride; + const offset = geometryAttribute.offset; + + if ( data.isInstancedInterleavedBuffer ) { + + for ( let i = 0; i < programAttribute.locationSize; i ++ ) { + + enableAttributeAndDivisor( programAttribute.location + i, data.meshPerAttribute ); + + } + + if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) { + + geometry._maxInstanceCount = data.meshPerAttribute * data.count; + + } + + } else { + + for ( let i = 0; i < programAttribute.locationSize; i ++ ) { + + enableAttribute( programAttribute.location + i ); + + } + + } + + gl.bindBuffer( gl.ARRAY_BUFFER, buffer ); + + for ( let i = 0; i < programAttribute.locationSize; i ++ ) { + + vertexAttribPointer( + programAttribute.location + i, + size / programAttribute.locationSize, + type, + normalized, + stride * bytesPerElement, + ( offset + ( size / programAttribute.locationSize ) * i ) * bytesPerElement, + integer + ); + + } + + } else { + + if ( geometryAttribute.isInstancedBufferAttribute ) { + + for ( let i = 0; i < programAttribute.locationSize; i ++ ) { + + enableAttributeAndDivisor( programAttribute.location + i, geometryAttribute.meshPerAttribute ); + + } + + if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) { + + geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count; + + } + + } else { + + for ( let i = 0; i < programAttribute.locationSize; i ++ ) { + + enableAttribute( programAttribute.location + i ); + + } + + } + + gl.bindBuffer( gl.ARRAY_BUFFER, buffer ); + + for ( let i = 0; i < programAttribute.locationSize; i ++ ) { + + vertexAttribPointer( + programAttribute.location + i, + size / programAttribute.locationSize, + type, + normalized, + size * bytesPerElement, + ( size / programAttribute.locationSize ) * i * bytesPerElement, + integer + ); + + } + + } + + } else if ( materialDefaultAttributeValues !== undefined ) { + + const value = materialDefaultAttributeValues[ name ]; + + if ( value !== undefined ) { + + switch ( value.length ) { + + case 2: + gl.vertexAttrib2fv( programAttribute.location, value ); + break; + + case 3: + gl.vertexAttrib3fv( programAttribute.location, value ); + break; + + case 4: + gl.vertexAttrib4fv( programAttribute.location, value ); + break; + + default: + gl.vertexAttrib1fv( programAttribute.location, value ); + + } + + } + + } + + } + + } + + disableUnusedAttributes(); + + } + + function dispose() { + + reset(); + + for ( const geometryId in bindingStates ) { + + const objectMap = bindingStates[ geometryId ]; + + for ( const objectId in objectMap ) { + + const programMap = objectMap[ objectId ]; + + for ( const programId in programMap ) { + + const stateMap = programMap[ programId ]; + + for ( const wireframe in stateMap ) { + + deleteVertexArrayObject( stateMap[ wireframe ].object ); + + delete stateMap[ wireframe ]; + + } + + delete programMap[ programId ]; + + } + + } + + delete bindingStates[ geometryId ]; + + } + + } + + function releaseStatesOfGeometry( geometry ) { + + if ( bindingStates[ geometry.id ] === undefined ) return; + + const objectMap = bindingStates[ geometry.id ]; + + for ( const objectId in objectMap ) { + + const programMap = objectMap[ objectId ]; + + for ( const programId in programMap ) { + + const stateMap = programMap[ programId ]; + + for ( const wireframe in stateMap ) { + + deleteVertexArrayObject( stateMap[ wireframe ].object ); + + delete stateMap[ wireframe ]; + + } + + delete programMap[ programId ]; + + } + + } + + delete bindingStates[ geometry.id ]; + + } + + function releaseStatesOfProgram( program ) { + + for ( const geometryId in bindingStates ) { + + const objectMap = bindingStates[ geometryId ]; + + for ( const objectId in objectMap ) { + + const programMap = objectMap[ objectId ]; + + if ( programMap[ program.id ] === undefined ) continue; + + const stateMap = programMap[ program.id ]; + + for ( const wireframe in stateMap ) { + + deleteVertexArrayObject( stateMap[ wireframe ].object ); + + delete stateMap[ wireframe ]; + + } + + delete programMap[ program.id ]; + + } + + } + + } + + function releaseStatesOfObject( object ) { + + for ( const geometryId in bindingStates ) { + + const objectMap = bindingStates[ geometryId ]; + + const objectId = ( object.isInstancedMesh === true ) ? object.id : 0; + + const programMap = objectMap[ objectId ]; + + if ( programMap === undefined ) continue; + + for ( const programId in programMap ) { + + const stateMap = programMap[ programId ]; + + for ( const wireframe in stateMap ) { + + deleteVertexArrayObject( stateMap[ wireframe ].object ); + + delete stateMap[ wireframe ]; + + } + + delete programMap[ programId ]; + + } + + delete objectMap[ objectId ]; + + if ( Object.keys( objectMap ).length === 0 ) { + + delete bindingStates[ geometryId ]; + + } + + } + + } + + + function reset() { + + resetDefaultState(); + forceUpdate = true; + + if ( currentState === defaultState ) return; + + currentState = defaultState; + bindVertexArrayObject( currentState.object ); + + } + + // for backward-compatibility + + function resetDefaultState() { + + defaultState.geometry = null; + defaultState.program = null; + defaultState.wireframe = false; + + } + + return { + + setup: setup, + reset: reset, + resetDefaultState: resetDefaultState, + dispose: dispose, + releaseStatesOfGeometry: releaseStatesOfGeometry, + releaseStatesOfObject: releaseStatesOfObject, + releaseStatesOfProgram: releaseStatesOfProgram, + + initAttributes: initAttributes, + enableAttribute: enableAttribute, + disableUnusedAttributes: disableUnusedAttributes + + }; + +} + +function WebGLBufferRenderer( gl, extensions, info ) { + + let mode; + + function setMode( value ) { + + mode = value; + + } + + function render( start, count ) { + + gl.drawArrays( mode, start, count ); + + info.update( count, mode, 1 ); + + } + + function renderInstances( start, count, primcount ) { + + if ( primcount === 0 ) return; + + gl.drawArraysInstanced( mode, start, count, primcount ); + + info.update( count, mode, primcount ); + + } + + function renderMultiDraw( starts, counts, drawCount ) { + + if ( drawCount === 0 ) return; + + const extension = extensions.get( 'WEBGL_multi_draw' ); + extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount ); + + let elementCount = 0; + for ( let i = 0; i < drawCount; i ++ ) { + + elementCount += counts[ i ]; + + } + + info.update( elementCount, mode, 1 ); + + } + + // + + this.setMode = setMode; + this.render = render; + this.renderInstances = renderInstances; + this.renderMultiDraw = renderMultiDraw; + +} + +function WebGLCapabilities( gl, extensions, parameters, utils ) { + + let maxAnisotropy; + + function getMaxAnisotropy() { + + if ( maxAnisotropy !== undefined ) return maxAnisotropy; + + if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) { + + const extension = extensions.get( 'EXT_texture_filter_anisotropic' ); + + maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT ); + + } else { + + maxAnisotropy = 0; + + } + + return maxAnisotropy; + + } + + function textureFormatReadable( textureFormat ) { + + if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) { + + return false; + + } + + return true; + + } + + function textureTypeReadable( textureType ) { + + const halfFloatSupportedByExt = ( textureType === HalfFloatType ) && ( extensions.has( 'EXT_color_buffer_half_float' ) || extensions.has( 'EXT_color_buffer_float' ) ); + + if ( textureType !== UnsignedByteType && textureType !== FloatType && ! halfFloatSupportedByExt && + utils.convert( textureType ) !== gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE ) ) { // Edge and Chrome Mac < 52 (#9513) + + return false; + + } + + return true; + + } + + function getMaxPrecision( precision ) { + + if ( precision === 'highp' ) { + + if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 && + gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) { + + return 'highp'; + + } + + precision = 'mediump'; + + } + + if ( precision === 'mediump' ) { + + if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 && + gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) { + + return 'mediump'; + + } + + } + + return 'lowp'; + + } + + let precision = parameters.precision !== undefined ? parameters.precision : 'highp'; + const maxPrecision = getMaxPrecision( precision ); + + if ( maxPrecision !== precision ) { + + warn( 'WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' ); + precision = maxPrecision; + + } + + const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true; + const reversedDepthBuffer = parameters.reversedDepthBuffer === true && extensions.has( 'EXT_clip_control' ); + + if ( parameters.reversedDepthBuffer === true && reversedDepthBuffer === false ) { + + warn( 'WebGLRenderer: Unable to use reversed depth buffer due to missing EXT_clip_control extension. Fallback to default depth buffer.' ); + + } + + const maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS ); + const maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ); + const maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE ); + const maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE ); + + const maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS ); + const maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS ); + const maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS ); + const maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS ); + + const maxSamples = gl.getParameter( gl.MAX_SAMPLES ); + const samples = gl.getParameter( gl.SAMPLES ); + + return { + + isWebGL2: true, // keeping this for backwards compatibility + + getMaxAnisotropy: getMaxAnisotropy, + getMaxPrecision: getMaxPrecision, + + textureFormatReadable: textureFormatReadable, + textureTypeReadable: textureTypeReadable, + + precision: precision, + logarithmicDepthBuffer: logarithmicDepthBuffer, + reversedDepthBuffer: reversedDepthBuffer, + + maxTextures: maxTextures, + maxVertexTextures: maxVertexTextures, + maxTextureSize: maxTextureSize, + maxCubemapSize: maxCubemapSize, + + maxAttributes: maxAttributes, + maxVertexUniforms: maxVertexUniforms, + maxVaryings: maxVaryings, + maxFragmentUniforms: maxFragmentUniforms, + + maxSamples: maxSamples, + + samples: samples + + }; + +} + +function WebGLClipping( properties ) { + + const scope = this; + + let globalState = null, + numGlobalPlanes = 0, + localClippingEnabled = false, + renderingShadows = false; + + const plane = new Plane(), + viewNormalMatrix = new Matrix3(), + + uniform = { value: null, needsUpdate: false }; + + this.uniform = uniform; + this.numPlanes = 0; + this.numIntersection = 0; + + this.init = function ( planes, enableLocalClipping ) { + + const enabled = + planes.length !== 0 || + enableLocalClipping || + // enable state of previous frame - the clipping code has to + // run another frame in order to reset the state: + numGlobalPlanes !== 0 || + localClippingEnabled; + + localClippingEnabled = enableLocalClipping; + + numGlobalPlanes = planes.length; + + return enabled; + + }; + + this.beginShadows = function () { + + renderingShadows = true; + projectPlanes( null ); + + }; + + this.endShadows = function () { + + renderingShadows = false; + + }; + + this.setGlobalState = function ( planes, camera ) { + + globalState = projectPlanes( planes, camera, 0 ); + + }; + + this.setState = function ( material, camera, useCache ) { + + const planes = material.clippingPlanes, + clipIntersection = material.clipIntersection, + clipShadows = material.clipShadows; + + const materialProperties = properties.get( material ); + + if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) { + + // there's no local clipping + + if ( renderingShadows ) { + + // there's no global clipping + + projectPlanes( null ); + + } else { + + resetGlobalState(); + + } + + } else { + + const nGlobal = renderingShadows ? 0 : numGlobalPlanes, + lGlobal = nGlobal * 4; + + let dstArray = materialProperties.clippingState || null; + + uniform.value = dstArray; // ensure unique state + + dstArray = projectPlanes( planes, camera, lGlobal, useCache ); + + for ( let i = 0; i !== lGlobal; ++ i ) { + + dstArray[ i ] = globalState[ i ]; + + } + + materialProperties.clippingState = dstArray; + this.numIntersection = clipIntersection ? this.numPlanes : 0; + this.numPlanes += nGlobal; + + } + + + }; + + function resetGlobalState() { + + if ( uniform.value !== globalState ) { + + uniform.value = globalState; + uniform.needsUpdate = numGlobalPlanes > 0; + + } + + scope.numPlanes = numGlobalPlanes; + scope.numIntersection = 0; + + } + + function projectPlanes( planes, camera, dstOffset, skipTransform ) { + + const nPlanes = planes !== null ? planes.length : 0; + let dstArray = null; + + if ( nPlanes !== 0 ) { + + dstArray = uniform.value; + + if ( skipTransform !== true || dstArray === null ) { + + const flatSize = dstOffset + nPlanes * 4, + viewMatrix = camera.matrixWorldInverse; + + viewNormalMatrix.getNormalMatrix( viewMatrix ); + + if ( dstArray === null || dstArray.length < flatSize ) { + + dstArray = new Float32Array( flatSize ); + + } + + for ( let i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) { + + plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix ); + + plane.normal.toArray( dstArray, i4 ); + dstArray[ i4 + 3 ] = plane.constant; + + } + + } + + uniform.value = dstArray; + uniform.needsUpdate = true; + + } + + scope.numPlanes = nPlanes; + scope.numIntersection = 0; + + return dstArray; + + } + +} + +const LOD_MIN = 4; + +// The number of extra mips. +// Used for scene blur in fromScene() method. +const EXTRA_LODS = 6; + +// The number of spiral samples per blur pass. +// Used for scene blur in fromScene() method. +const BLUR_SAMPLES = 20; + +// GGX VNDF importance sampling configuration +const GGX_SAMPLES = 256; + +const _flatCamera = /*@__PURE__*/ new OrthographicCamera(); +const _clearColor = /*@__PURE__*/ new Color(); +let _oldTarget = null; +let _oldActiveCubeFace = 0; +let _oldActiveMipmapLevel = 0; +let _oldXrEnabled = false; + +const _origin = /*@__PURE__*/ new Vector3(); +const _direction = /*@__PURE__*/ new Vector3(); + +/** + * This class generates a Prefiltered, Mipmapped Radiance Environment Map + * (PMREM) from a cubeMap environment texture. This allows different levels of + * blur to be quickly accessed based on material roughness. It is packed into a + * special CubeUV format that allows us to perform custom interpolation so that + * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap + * chain, it only goes down to the LOD_MIN level (above), and then creates extra + * even more filtered 'mips' at the same LOD_MIN resolution, associated with + * higher roughness levels. In this way we maintain resolution to smoothly + * interpolate diffuse lighting while limiting sampling computation. + * + * The prefiltering uses GGX VNDF (Visible Normal Distribution Function) + * importance sampling based on "Sampling the GGX Distribution of Visible Normals" + * (Heitz, 2018) to generate environment maps that accurately match the GGX BRDF + * used in material rendering for physically-based image-based lighting. + */ +class PMREMGenerator { + + /** + * Constructs a new PMREM generator. + * + * @param {WebGLRenderer} renderer - The renderer. + */ + constructor( renderer ) { + + this._renderer = renderer; + this._pingPongRenderTarget = null; + + this._lodMax = 0; + this._cubeSize = 0; + this._sizeLods = []; + this._lodMeshes = []; + + this._backgroundBox = null; + + this._cubemapMaterial = null; + this._equirectMaterial = null; + + this._blurMaterial = null; + this._ggxMaterial = null; + + } + + /** + * Generates a PMREM from a supplied Scene, which can be faster than using an + * image if networking bandwidth is low. Optional sigma specifies a blur radius + * in radians to be applied to the scene before PMREM generation. Optional near + * and far planes ensure the scene is rendered in its entirety. + * + * @param {Scene} scene - The scene to be captured. + * @param {number} [sigma=0] - The blur radius in radians. + * @param {number} [near=0.1] - The near plane distance. + * @param {number} [far=100] - The far plane distance. + * @param {Object} [options={}] - The configuration options. + * @param {number} [options.size=256] - The texture size of the PMREM. + * @param {Vector3} [options.position=origin] - The position of the internal cube camera that renders the scene. + * @return {WebGLRenderTarget} The resulting PMREM. + */ + fromScene( scene, sigma = 0, near = 0.1, far = 100, options = {} ) { + + const { + size = 256, + position = _origin, + } = options; + + _oldTarget = this._renderer.getRenderTarget(); + _oldActiveCubeFace = this._renderer.getActiveCubeFace(); + _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel(); + _oldXrEnabled = this._renderer.xr.enabled; + + this._renderer.xr.enabled = false; + + this._setSize( size ); + + const cubeUVRenderTarget = this._allocateTargets(); + cubeUVRenderTarget.depthBuffer = true; + + this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position ); + + if ( sigma > 0 ) { + + this._blur( cubeUVRenderTarget, 0, 0, sigma ); + + } + + this._applyPMREM( cubeUVRenderTarget ); + this._cleanup( cubeUVRenderTarget ); + + return cubeUVRenderTarget; + + } + + /** + * Generates a PMREM from an equirectangular texture, which can be either LDR + * or HDR. The ideal input image size is 1k (1024 x 512), as this matches best + * with the 256 x 256 cubemap output. The minimum supported input image size + * is 64 x 32. + * + * @param {Texture} equirectangular - The equirectangular texture to be converted. + * @param {?WebGLRenderTarget} [renderTarget=null] - The render target to use. + * @return {WebGLRenderTarget} The resulting PMREM. + */ + fromEquirectangular( equirectangular, renderTarget = null ) { + + return this._fromTexture( equirectangular, renderTarget ); + + } + + /** + * Generates a PMREM from an cubemap texture, which can be either LDR + * or HDR. The ideal input cube size is 256 x 256, as this matches best + * with the 256 x 256 cubemap output. The minimum supported input cube + * size is 16 x 16 per face. + * + * @param {Texture} cubemap - The cubemap texture to be converted. + * @param {?WebGLRenderTarget} [renderTarget=null] - The render target to use. + * @return {WebGLRenderTarget} The resulting PMREM. + */ + fromCubemap( cubemap, renderTarget = null ) { + + return this._fromTexture( cubemap, renderTarget ); + + } + + /** + * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during + * your texture's network fetch for increased concurrency. + */ + compileCubemapShader() { + + if ( this._cubemapMaterial === null ) { + + this._cubemapMaterial = _getCubemapMaterial(); + this._compileMaterial( this._cubemapMaterial ); + + } + + } + + /** + * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during + * your texture's network fetch for increased concurrency. + */ + compileEquirectangularShader() { + + if ( this._equirectMaterial === null ) { + + this._equirectMaterial = _getEquirectMaterial(); + this._compileMaterial( this._equirectMaterial ); + + } + + } + + /** + * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class, + * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on + * one of them will cause any others to also become unusable. + */ + dispose() { + + this._dispose(); + + if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose(); + if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose(); + + if ( this._backgroundBox !== null ) { + + this._backgroundBox.geometry.dispose(); + this._backgroundBox.material.dispose(); + + } + + } + + // private interface + + _setSize( cubeSize ) { + + this._lodMax = Math.floor( Math.log2( cubeSize ) ); + this._cubeSize = Math.pow( 2, this._lodMax ); + + } + + _dispose() { + + if ( this._blurMaterial !== null ) this._blurMaterial.dispose(); + if ( this._ggxMaterial !== null ) this._ggxMaterial.dispose(); + + if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose(); + + for ( let i = 0; i < this._lodMeshes.length; i ++ ) { + + this._lodMeshes[ i ].geometry.dispose(); + + } + + } + + _cleanup( outputTarget ) { + + this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel ); + this._renderer.xr.enabled = _oldXrEnabled; + + outputTarget.scissorTest = false; + _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height ); + + } + + _fromTexture( texture, renderTarget ) { + + if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) { + + this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) ); + + } else { // Equirectangular + + this._setSize( texture.image.width / 4 ); + + } + + _oldTarget = this._renderer.getRenderTarget(); + _oldActiveCubeFace = this._renderer.getActiveCubeFace(); + _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel(); + _oldXrEnabled = this._renderer.xr.enabled; + + this._renderer.xr.enabled = false; + + const cubeUVRenderTarget = renderTarget || this._allocateTargets(); + this._textureToCubeUV( texture, cubeUVRenderTarget ); + this._applyPMREM( cubeUVRenderTarget ); + this._cleanup( cubeUVRenderTarget ); + + return cubeUVRenderTarget; + + } + + _allocateTargets() { + + const width = 3 * Math.max( this._cubeSize, 16 * 7 ); + const height = 4 * this._cubeSize; + + const params = { + magFilter: LinearFilter, + minFilter: LinearFilter, + generateMipmaps: false, + type: HalfFloatType, + format: RGBAFormat, + colorSpace: LinearSRGBColorSpace, + depthBuffer: false + }; + + const cubeUVRenderTarget = _createRenderTarget( width, height, params ); + + if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) { + + if ( this._pingPongRenderTarget !== null ) { + + this._dispose(); + + } + + this._pingPongRenderTarget = _createRenderTarget( width, height, params ); + + const { _lodMax } = this; + ( { lodMeshes: this._lodMeshes, sizeLods: this._sizeLods } = _createPlanes( _lodMax ) ); + + this._blurMaterial = _getBlurShader( _lodMax, width, height ); + this._ggxMaterial = _getGGXShader( _lodMax, width, height ); + + } + + return cubeUVRenderTarget; + + } + + _compileMaterial( material ) { + + const mesh = new Mesh( new BufferGeometry(), material ); + this._renderer.compile( mesh, _flatCamera ); + + } + + _sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position ) { + + const fov = 90; + const aspect = 1; + const cubeCamera = new PerspectiveCamera( fov, aspect, near, far ); + const upSign = [ 1, -1, 1, 1, 1, 1 ]; + const forwardSign = [ 1, 1, 1, -1, -1, -1 ]; + const renderer = this._renderer; + + const originalAutoClear = renderer.autoClear; + const toneMapping = renderer.toneMapping; + renderer.getClearColor( _clearColor ); + + renderer.toneMapping = NoToneMapping; + renderer.autoClear = false; + + // https://github.com/mrdoob/three.js/issues/31413#issuecomment-3095966812 + const reversedDepthBuffer = renderer.state.buffers.depth.getReversed(); + + if ( reversedDepthBuffer ) { + + renderer.setRenderTarget( cubeUVRenderTarget ); + renderer.clearDepth(); + renderer.setRenderTarget( null ); + + } + + if ( this._backgroundBox === null ) { + + this._backgroundBox = new Mesh( + new BoxGeometry(), + new MeshBasicMaterial( { + name: 'PMREM.Background', + side: BackSide, + depthWrite: false, + depthTest: false, + } ) + ); + + } + + const backgroundBox = this._backgroundBox; + const backgroundMaterial = backgroundBox.material; + + let useSolidColor = false; + + const background = scene.background; + + if ( background ) { + + if ( background.isColor ) { + + backgroundMaterial.color.copy( background ); + scene.background = null; + useSolidColor = true; + + } + + } else { + + backgroundMaterial.color.copy( _clearColor ); + useSolidColor = true; + + } + + for ( let i = 0; i < 6; i ++ ) { + + const col = i % 3; + + if ( col === 0 ) { + + cubeCamera.up.set( 0, upSign[ i ], 0 ); + cubeCamera.position.set( position.x, position.y, position.z ); + cubeCamera.lookAt( position.x + forwardSign[ i ], position.y, position.z ); + + } else if ( col === 1 ) { + + cubeCamera.up.set( 0, 0, upSign[ i ] ); + cubeCamera.position.set( position.x, position.y, position.z ); + cubeCamera.lookAt( position.x, position.y + forwardSign[ i ], position.z ); + + + } else { + + cubeCamera.up.set( 0, upSign[ i ], 0 ); + cubeCamera.position.set( position.x, position.y, position.z ); + cubeCamera.lookAt( position.x, position.y, position.z + forwardSign[ i ] ); + + } + + const size = this._cubeSize; + + _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size ); + + renderer.setRenderTarget( cubeUVRenderTarget ); + + if ( useSolidColor ) { + + renderer.render( backgroundBox, cubeCamera ); + + } + + renderer.render( scene, cubeCamera ); + + } + + renderer.toneMapping = toneMapping; + renderer.autoClear = originalAutoClear; + scene.background = background; + + } + + _textureToCubeUV( texture, cubeUVRenderTarget ) { + + const renderer = this._renderer; + + const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ); + + if ( isCubeTexture ) { + + if ( this._cubemapMaterial === null ) { + + this._cubemapMaterial = _getCubemapMaterial(); + + } + + this._cubemapMaterial.uniforms.flipEnvMap.value = ( texture.isRenderTargetTexture === false ) ? -1 : 1; + + } else { + + if ( this._equirectMaterial === null ) { + + this._equirectMaterial = _getEquirectMaterial(); + + } + + } + + const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial; + + const mesh = this._lodMeshes[ 0 ]; + mesh.material = material; + + const uniforms = material.uniforms; + + uniforms[ 'envMap' ].value = texture; + + const size = this._cubeSize; + + _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size ); + + renderer.setRenderTarget( cubeUVRenderTarget ); + renderer.render( mesh, _flatCamera ); + + } + + _applyPMREM( cubeUVRenderTarget ) { + + const renderer = this._renderer; + const autoClear = renderer.autoClear; + renderer.autoClear = false; + + const n = this._lodMeshes.length; + + // Use GGX VNDF importance sampling + for ( let i = 1; i < n; i ++ ) { + + this._applyGGXFilter( cubeUVRenderTarget, i - 1, i ); + + } + + renderer.autoClear = autoClear; + + } + + /** + * Applies GGX VNDF importance sampling filter to generate a prefiltered environment map. + * Uses Monte Carlo integration with VNDF importance sampling to accurately represent the + * GGX BRDF for physically-based rendering. Reads from the previous LOD level and + * applies incremental roughness filtering to avoid over-blurring. + * + * @private + * @param {WebGLRenderTarget} cubeUVRenderTarget + * @param {number} lodIn - Source LOD level to read from + * @param {number} lodOut - Target LOD level to write to + */ + _applyGGXFilter( cubeUVRenderTarget, lodIn, lodOut ) { + + const renderer = this._renderer; + const pingPongRenderTarget = this._pingPongRenderTarget; + + const ggxMaterial = this._ggxMaterial; + const ggxMesh = this._lodMeshes[ lodOut ]; + ggxMesh.material = ggxMaterial; + + const ggxUniforms = ggxMaterial.uniforms; + + // Calculate incremental roughness between LOD levels + const targetRoughness = lodOut / ( this._lodMeshes.length - 1 ); + const sourceRoughness = lodIn / ( this._lodMeshes.length - 1 ); + const incrementalRoughness = Math.sqrt( targetRoughness * targetRoughness - sourceRoughness * sourceRoughness ); + + // Apply blur strength mapping for better quality across the roughness range + const blurStrength = targetRoughness * 1.25; + const adjustedRoughness = incrementalRoughness * blurStrength; + + // Calculate viewport position based on output LOD level + const { _lodMax } = this; + const outputSize = this._sizeLods[ lodOut ]; + const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 ); + const y = 4 * ( this._cubeSize - outputSize ); + + // Read from previous LOD with incremental roughness + ggxUniforms[ 'envMap' ].value = cubeUVRenderTarget.texture; + ggxUniforms[ 'roughness' ].value = adjustedRoughness; + ggxUniforms[ 'mipInt' ].value = _lodMax - lodIn; // Sample from input LOD + + _setViewport( pingPongRenderTarget, x, y, 3 * outputSize, 2 * outputSize ); + renderer.setRenderTarget( pingPongRenderTarget ); + renderer.render( ggxMesh, _flatCamera ); + + // Copy from pingPong back to cubeUV (simple direct copy) + ggxUniforms[ 'envMap' ].value = pingPongRenderTarget.texture; + ggxUniforms[ 'roughness' ].value = 0.0; // Direct copy + ggxUniforms[ 'mipInt' ].value = _lodMax - lodOut; // Read from the level we just wrote + + _setViewport( cubeUVRenderTarget, x, y, 3 * outputSize, 2 * outputSize ); + renderer.setRenderTarget( cubeUVRenderTarget ); + renderer.render( ggxMesh, _flatCamera ); + + } + + /** + * This is a two-pass Gaussian blur for a cubemap. Each pass importance-samples + * the Gaussian along a spiral kernel (Golden Angle), which distributes samples + * isotropically on the sphere (no pole artifacts). + * + * Used for initial scene blur in fromScene() method when sigma > 0. + * + * @private + * @param {WebGLRenderTarget} cubeUVRenderTarget + * @param {number} lodIn + * @param {number} lodOut + * @param {number} sigma + */ + _blur( cubeUVRenderTarget, lodIn, lodOut, sigma ) { + + const pingPongRenderTarget = this._pingPongRenderTarget; + + // Two passes of sigma / sqrt( 2 ) compose to a blur of sigma while squaring + // the effective sample count. Sigmas beyond PI are visually indistinguishable + // from a uniform blur, so clamp to keep the shader math finite. + const blurSigma = Math.min( sigma, Math.PI ) / Math.SQRT2; + + this._blurPass( cubeUVRenderTarget, pingPongRenderTarget, lodIn, lodOut, blurSigma ); + this._blurPass( pingPongRenderTarget, cubeUVRenderTarget, lodOut, lodOut, blurSigma ); + + } + + _blurPass( targetIn, targetOut, lodIn, lodOut, sigmaRadians ) { + + const renderer = this._renderer; + const blurMaterial = this._blurMaterial; + + const blurMesh = this._lodMeshes[ lodOut ]; + blurMesh.material = blurMaterial; + + const blurUniforms = blurMaterial.uniforms; + + blurUniforms[ 'envMap' ].value = targetIn.texture; + blurUniforms[ 'sigma' ].value = sigmaRadians; + blurUniforms[ 'mipInt' ].value = this._lodMax - lodIn; + + const outputSize = this._sizeLods[ lodOut ]; + const x = 3 * outputSize * ( lodOut > this._lodMax - LOD_MIN ? lodOut - this._lodMax + LOD_MIN : 0 ); + const y = 4 * ( this._cubeSize - outputSize ); + + _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize ); + renderer.setRenderTarget( targetOut ); + renderer.render( blurMesh, _flatCamera ); + + } + +} + + + +function _createPlanes( lodMax ) { + + const sizeLods = []; + const lodMeshes = []; + + let lod = lodMax; + + const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LODS; + + for ( let i = 0; i < totalLods; i ++ ) { + + const sizeLod = Math.pow( 2, lod ); + sizeLods.push( sizeLod ); + + // UVs overshoot the face by one texel to bake the CubeUV border into the directions. + const texelSize = 1.0 / ( sizeLod - 2 ); + const min = - texelSize; + const max = 1 + texelSize; + const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ]; + + const cubeFaces = 6; + const vertices = 6; + const positionSize = 3; + + const position = new Float32Array( positionSize * vertices * cubeFaces ); + const outputDirection = new Float32Array( positionSize * vertices * cubeFaces ); + + for ( let face = 0; face < cubeFaces; face ++ ) { + + const x = ( face % 3 ) * 2 / 3 - 1; + const y = face > 2 ? 0 : -1; + const coordinates = [ + x, y, 0, + x + 2 / 3, y, 0, + x + 2 / 3, y + 1, 0, + x, y, 0, + x + 2 / 3, y + 1, 0, + x, y + 1, 0 + ]; + position.set( coordinates, positionSize * vertices * face ); + + for ( let vertex = 0; vertex < vertices; vertex ++ ) { + + const u = uv1[ vertex * 2 ] * 2 - 1; + const v = uv1[ vertex * 2 + 1 ] * 2 - 1; + + // RH coordinate system; PMREM face-indexing convention + if ( face === 0 ) { + + _direction.set( 1, v, u ); // pos x + + } else if ( face === 1 ) { + + _direction.set( - u, 1, - v ); // pos y + + } else if ( face === 2 ) { + + _direction.set( - u, v, 1 ); // pos z + + } else if ( face === 3 ) { + + _direction.set( -1, v, - u ); // neg x + + } else if ( face === 4 ) { + + _direction.set( - u, -1, v ); // neg y + + } else { + + _direction.set( u, v, -1 ); // neg z + + } + + _direction.toArray( outputDirection, ( face * vertices + vertex ) * positionSize ); + + } + + } + + const planes = new BufferGeometry(); + planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) ); + planes.setAttribute( 'outputDirection', new BufferAttribute( outputDirection, positionSize ) ); + lodMeshes.push( new Mesh( planes, null ) ); + + if ( lod > LOD_MIN ) { + + lod --; + + } + + } + + return { lodMeshes, sizeLods }; + +} + +function _createRenderTarget( width, height, params ) { + + const cubeUVRenderTarget = new WebGLRenderTarget( width, height, params ); + cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping; + cubeUVRenderTarget.texture.name = 'PMREM.cubeUv'; + cubeUVRenderTarget.scissorTest = true; + return cubeUVRenderTarget; + +} + +function _setViewport( target, x, y, width, height ) { + + target.viewport.set( x, y, width, height ); + target.scissor.set( x, y, width, height ); + +} + +function _getGGXShader( lodMax, width, height ) { + + const shaderMaterial = new ShaderMaterial( { + + name: 'PMREMGGXConvolution', + + defines: { + 'GGX_SAMPLES': GGX_SAMPLES, + 'CUBEUV_TEXEL_WIDTH': 1.0 / width, + 'CUBEUV_TEXEL_HEIGHT': 1.0 / height, + 'CUBEUV_MAX_MIP': `${lodMax}.0`, + }, + + uniforms: { + 'envMap': { value: null }, + 'roughness': { value: 0.0 }, + 'mipInt': { value: 0 } + }, + + vertexShader: _getCommonVertexShader(), + + fragmentShader: /* glsl */` + + precision highp float; + precision highp int; + + varying vec3 vOutputDirection; + + uniform sampler2D envMap; + uniform float roughness; + uniform float mipInt; + + #define ENVMAP_TYPE_CUBE_UV + #include + + #define PI 3.14159265359 + + // Van der Corput radical inverse + float radicalInverse_VdC(uint bits) { + bits = (bits << 16u) | (bits >> 16u); + bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u); + bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u); + bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u); + bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u); + return float(bits) * 2.3283064365386963e-10; // / 0x100000000 + } + + // Hammersley sequence + vec2 hammersley(uint i, uint N) { + return vec2(float(i) / float(N), radicalInverse_VdC(i)); + } + + // GGX VNDF importance sampling (Eric Heitz 2018) + // "Sampling the GGX Distribution of Visible Normals" + // https://jcgt.org/published/0007/04/01/ + vec3 importanceSampleGGX_VNDF(vec2 Xi, vec3 V, float roughness) { + float alpha = roughness * roughness; + + // Section 4.1: Orthonormal basis + vec3 T1 = vec3(1.0, 0.0, 0.0); + vec3 T2 = cross(V, T1); + + // Section 4.2: Parameterization of projected area + float r = sqrt(Xi.x); + float phi = 2.0 * PI * Xi.y; + float t1 = r * cos(phi); + float t2 = r * sin(phi); + float s = 0.5 * (1.0 + V.z); + t2 = (1.0 - s) * sqrt(1.0 - t1 * t1) + s * t2; + + // Section 4.3: Reprojection onto hemisphere + vec3 Nh = t1 * T1 + t2 * T2 + sqrt(max(0.0, 1.0 - t1 * t1 - t2 * t2)) * V; + + // Section 3.4: Transform back to ellipsoid configuration + return normalize(vec3(alpha * Nh.x, alpha * Nh.y, max(0.0, Nh.z))); + } + + void main() { + vec3 N = normalize(vOutputDirection); + vec3 V = N; // Assume view direction equals normal for pre-filtering + + vec3 prefilteredColor = vec3(0.0); + float totalWeight = 0.0; + + // For very low roughness, just sample the environment directly + if (roughness < 0.001) { + gl_FragColor = vec4(bilinearCubeUV(envMap, N, mipInt), 1.0); + return; + } + + // Tangent space basis for VNDF sampling + vec3 up = abs(N.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0); + vec3 tangent = normalize(cross(up, N)); + vec3 bitangent = cross(N, tangent); + + for(uint i = 0u; i < uint(GGX_SAMPLES); i++) { + vec2 Xi = hammersley(i, uint(GGX_SAMPLES)); + + // For PMREM, V = N, so in tangent space V is always (0, 0, 1) + vec3 H_tangent = importanceSampleGGX_VNDF(Xi, vec3(0.0, 0.0, 1.0), roughness); + + // Transform H back to world space + vec3 H = normalize(tangent * H_tangent.x + bitangent * H_tangent.y + N * H_tangent.z); + vec3 L = normalize(2.0 * dot(V, H) * H - V); + + float NdotL = max(dot(N, L), 0.0); + + if(NdotL > 0.0) { + // Sample environment at fixed mip level + // VNDF importance sampling handles the distribution filtering + vec3 sampleColor = bilinearCubeUV(envMap, L, mipInt); + + // Weight by NdotL for the split-sum approximation + // VNDF PDF naturally accounts for the visible microfacet distribution + prefilteredColor += sampleColor * NdotL; + totalWeight += NdotL; + } + } + + if (totalWeight > 0.0) { + prefilteredColor = prefilteredColor / totalWeight; + } + + gl_FragColor = vec4(prefilteredColor, 1.0); + } + `, + + blending: NoBlending, + depthTest: false, + depthWrite: false + + } ); + + return shaderMaterial; + +} + +function _getBlurShader( lodMax, width, height ) { + + const shaderMaterial = new ShaderMaterial( { + + name: 'SphericalGaussianBlur', + + defines: { + 'SAMPLES': BLUR_SAMPLES, + 'CUBEUV_TEXEL_WIDTH': 1.0 / width, + 'CUBEUV_TEXEL_HEIGHT': 1.0 / height, + 'CUBEUV_MAX_MIP': `${lodMax}.0`, + }, + + uniforms: { + 'envMap': { value: null }, + 'sigma': { value: 0 }, + 'mipInt': { value: 0 }, + }, + + vertexShader: _getCommonVertexShader(), + + fragmentShader: /* glsl */` + + precision highp float; + precision highp int; + + varying vec3 vOutputDirection; + + uniform sampler2D envMap; + uniform float sigma; + uniform float mipInt; + + #define ENVMAP_TYPE_CUBE_UV + #include + + #define PI 3.14159265359 + #define GOLDEN_ANGLE 2.39996322973 + + void main() { + + if ( sigma == 0.0 ) { + + gl_FragColor = vec4( bilinearCubeUV( envMap, vOutputDirection, mipInt ), 1.0 ); + return; + + } + + vec3 outputDirection = normalize( vOutputDirection ); + + vec3 up = abs( outputDirection.z ) < 0.999 ? vec3( 0.0, 0.0, 1.0 ) : vec3( 1.0, 0.0, 0.0 ); + vec3 tangent = normalize( cross( up, outputDirection ) ); + vec3 bitangent = cross( outputDirection, tangent ); + + // Truncate the kernel at three standard deviations or at the antipode. + float thetaMax = min( 3.0 * sigma, PI ); + float truncation = 1.0 - exp( - 0.5 * thetaMax * thetaMax / ( sigma * sigma ) ); + + vec3 accumColor = vec3( 0.0 ); + float accumWeight = 0.0; + + for ( int i = 0; i < SAMPLES; i ++ ) { + + // Stratified inverse-CDF sampling of the Gaussian, placed on a golden-angle spiral. + float stratum = ( float( i ) + 0.5 ) / float( SAMPLES ); + float theta = sigma * sqrt( - 2.0 * log( 1.0 - stratum * truncation ) ); + float phi = float( i ) * GOLDEN_ANGLE; + + vec3 offset = cos( phi ) * tangent + sin( phi ) * bitangent; + vec3 sampleDirection = cos( theta ) * outputDirection + sin( theta ) * offset; + + // Correct the planar sample density to solid angle. + float weight = sin( theta ) / theta; + + accumColor += weight * bilinearCubeUV( envMap, sampleDirection, mipInt ); + accumWeight += weight; + + } + + gl_FragColor = vec4( accumColor / accumWeight, 1.0 ); + + } + `, + + blending: NoBlending, + depthTest: false, + depthWrite: false + + } ); + + return shaderMaterial; + +} + +function _getEquirectMaterial() { + + return new ShaderMaterial( { + + name: 'EquirectangularToCubeUV', + + uniforms: { + 'envMap': { value: null } + }, + + vertexShader: _getCommonVertexShader(), + + fragmentShader: /* glsl */` + + precision mediump float; + precision mediump int; + + varying vec3 vOutputDirection; + + uniform sampler2D envMap; + + #include + + void main() { + + vec3 outputDirection = normalize( vOutputDirection ); + vec2 uv = equirectUv( outputDirection ); + + gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 ); + + } + `, + + blending: NoBlending, + depthTest: false, + depthWrite: false + + } ); + +} + +function _getCubemapMaterial() { + + return new ShaderMaterial( { + + name: 'CubemapToCubeUV', + + uniforms: { + 'envMap': { value: null }, + 'flipEnvMap': { value: -1 } + }, + + vertexShader: _getCommonVertexShader(), + + fragmentShader: /* glsl */` + + precision mediump float; + precision mediump int; + + uniform float flipEnvMap; + + varying vec3 vOutputDirection; + + uniform samplerCube envMap; + + void main() { + + gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) ); + + } + `, + + blending: NoBlending, + depthTest: false, + depthWrite: false + + } ); + +} + +function _getCommonVertexShader() { + + return /* glsl */` + + precision mediump float; + precision mediump int; + + attribute vec3 outputDirection; + + varying vec3 vOutputDirection; + + void main() { + + vOutputDirection = outputDirection; + gl_Position = vec4( position, 1.0 ); + + } + `; + +} + +/** + * A cube render target used in context of {@link WebGLRenderer}. + * + * @augments WebGLRenderTarget + */ +class WebGLCubeRenderTarget extends WebGLRenderTarget { + + /** + * Constructs a new cube render target. + * + * @param {number} [size=1] - The size of the render target. + * @param {RenderTarget~Options} [options] - The configuration object. + */ + constructor( size = 1, options = {} ) { + + super( size, size, options ); + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isWebGLCubeRenderTarget = true; + + const image = { width: size, height: size, depth: 1 }; + const images = [ image, image, image, image, image, image ]; + + /** + * Overwritten with a different texture type. + * + * @type {DataArrayTexture} + */ + this.texture = new CubeTexture( images ); + this._setTextureOptions( options ); + + // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js) + // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words, + // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly. + + // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped + // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture + // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures). + + this.texture.isRenderTargetTexture = true; + + } + + /** + * Converts the given equirectangular texture to a cube map. + * + * @param {WebGLRenderer} renderer - The renderer. + * @param {Texture} texture - The equirectangular texture. + * @return {WebGLCubeRenderTarget} A reference to this cube render target. + */ + fromEquirectangularTexture( renderer, texture ) { + + this.texture.type = texture.type; + this.texture.colorSpace = texture.colorSpace; + + this.texture.generateMipmaps = texture.generateMipmaps; + this.texture.minFilter = texture.minFilter; + this.texture.magFilter = texture.magFilter; + + const shader = { + + uniforms: { + tEquirect: { value: null }, + }, + + vertexShader: /* glsl */` + + varying vec3 vWorldDirection; + + vec3 transformDirection( in vec3 dir, in mat4 matrix ) { + + return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); + + } + + void main() { + + vWorldDirection = transformDirection( position, modelMatrix ); + + #include + #include + + } + `, + + fragmentShader: /* glsl */` + + uniform sampler2D tEquirect; + + varying vec3 vWorldDirection; + + #include + + void main() { + + vec3 direction = normalize( vWorldDirection ); + + vec2 sampleUV = equirectUv( direction ); + + gl_FragColor = texture2D( tEquirect, sampleUV ); + + } + ` + }; + + const geometry = new BoxGeometry( 5, 5, 5 ); + + const material = new ShaderMaterial( { + + name: 'CubemapFromEquirect', + + uniforms: cloneUniforms( shader.uniforms ), + vertexShader: shader.vertexShader, + fragmentShader: shader.fragmentShader, + side: BackSide, + blending: NoBlending + + } ); + + material.uniforms.tEquirect.value = texture; + + const mesh = new Mesh( geometry, material ); + + const currentMinFilter = texture.minFilter; + + // Avoid blurred poles + if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter; + + const camera = new CubeCamera( 1, 10, this ); + camera.update( renderer, mesh ); + + texture.minFilter = currentMinFilter; + + mesh.geometry.dispose(); + mesh.material.dispose(); + + return this; + + } + + /** + * Clears this cube render target. + * + * @param {WebGLRenderer} renderer - The renderer. + * @param {boolean} [color=true] - Whether the color buffer should be cleared or not. + * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not. + * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not. + */ + clear( renderer, color = true, depth = true, stencil = true ) { + + const currentRenderTarget = renderer.getRenderTarget(); + + for ( let i = 0; i < 6; i ++ ) { + + renderer.setRenderTarget( this, i ); + + renderer.clear( color, depth, stencil ); + + } + + renderer.setRenderTarget( currentRenderTarget ); + + } + +} + +function WebGLEnvironments( renderer ) { + + let cubeMaps = new WeakMap(); + let pmremMaps = new WeakMap(); + + let pmremGenerator = null; + + function get( texture, usePMREM = false ) { + + if ( texture === null || texture === undefined ) return null; + + if ( usePMREM ) { + + return getPMREM( texture ); + + } + + return getCube( texture ); + + } + + function getCube( texture ) { + + if ( texture && texture.isTexture ) { + + const mapping = texture.mapping; + + if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) { + + if ( cubeMaps.has( texture ) ) { + + const cubemap = cubeMaps.get( texture ).texture; + return mapTextureMapping( cubemap, texture.mapping ); + + } else { + + const image = texture.image; + + if ( image && image.height > 0 ) { + + const renderTarget = new WebGLCubeRenderTarget( image.height ); + renderTarget.fromEquirectangularTexture( renderer, texture ); + cubeMaps.set( texture, renderTarget ); + + texture.addEventListener( 'dispose', onCubemapDispose ); + + return mapTextureMapping( renderTarget.texture, texture.mapping ); + + } else { + + // image not yet ready. try the conversion next frame + + return null; + + } + + } + + } + + } + + return texture; + + } + + function getPMREM( texture ) { + + if ( texture && texture.isTexture ) { + + const mapping = texture.mapping; + + const isEquirectMap = ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ); + const isCubeMap = ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping ); + + // equirect/cube map to cubeUV conversion + + if ( isEquirectMap || isCubeMap ) { + + let renderTarget = pmremMaps.get( texture ); + + const currentPMREMVersion = renderTarget !== undefined ? renderTarget.texture.pmremVersion : 0; + + if ( texture.isRenderTargetTexture && texture.pmremVersion !== currentPMREMVersion ) { + + if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer ); + + renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture, renderTarget ) : pmremGenerator.fromCubemap( texture, renderTarget ); + renderTarget.texture.pmremVersion = texture.pmremVersion; + + pmremMaps.set( texture, renderTarget ); + + return renderTarget.texture; + + } else { + + if ( renderTarget !== undefined ) { + + return renderTarget.texture; + + } else { + + const image = texture.image; + + if ( ( isEquirectMap && image && image.height > 0 ) || ( isCubeMap && image && isCubeTextureComplete( image ) ) ) { + + if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer ); + + renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture ) : pmremGenerator.fromCubemap( texture ); + renderTarget.texture.pmremVersion = texture.pmremVersion; + + pmremMaps.set( texture, renderTarget ); + + texture.addEventListener( 'dispose', onPMREMDispose ); + + return renderTarget.texture; + + } else { + + // image not yet ready. try the conversion next frame + + return null; + + } + + } + + } + + } + + } + + return texture; + + } + + function mapTextureMapping( texture, mapping ) { + + if ( mapping === EquirectangularReflectionMapping ) { + + texture.mapping = CubeReflectionMapping; + + } else if ( mapping === EquirectangularRefractionMapping ) { + + texture.mapping = CubeRefractionMapping; + + } + + return texture; + + } + + function isCubeTextureComplete( image ) { + + let count = 0; + const length = 6; + + for ( let i = 0; i < length; i ++ ) { + + if ( image[ i ] !== undefined ) count ++; + + } + + return count === length; + + } + + function onCubemapDispose( event ) { + + const texture = event.target; + + texture.removeEventListener( 'dispose', onCubemapDispose ); + + const cubemap = cubeMaps.get( texture ); + + if ( cubemap !== undefined ) { + + cubeMaps.delete( texture ); + cubemap.dispose(); + + } + + } + + function onPMREMDispose( event ) { + + const texture = event.target; + + texture.removeEventListener( 'dispose', onPMREMDispose ); + + const pmrem = pmremMaps.get( texture ); + + if ( pmrem !== undefined ) { + + pmremMaps.delete( texture ); + pmrem.dispose(); + + } + + } + + function dispose() { + + cubeMaps = new WeakMap(); + pmremMaps = new WeakMap(); + + if ( pmremGenerator !== null ) { + + pmremGenerator.dispose(); + pmremGenerator = null; + + } + + } + + return { + get: get, + dispose: dispose + }; + +} + +function WebGLExtensions( gl ) { + + const extensions = {}; + + function getExtension( name ) { + + if ( extensions[ name ] !== undefined ) { + + return extensions[ name ]; + + } + + const extension = gl.getExtension( name ); + + extensions[ name ] = extension; + + return extension; + + } + + return { + + has: function ( name ) { + + return getExtension( name ) !== null; + + }, + + init: function () { + + getExtension( 'EXT_color_buffer_float' ); + getExtension( 'WEBGL_clip_cull_distance' ); + getExtension( 'OES_texture_float_linear' ); + getExtension( 'EXT_color_buffer_half_float' ); + getExtension( 'WEBGL_multisampled_render_to_texture' ); + getExtension( 'WEBGL_render_shared_exponent' ); + + }, + + get: function ( name ) { + + const extension = getExtension( name ); + + if ( extension === null ) { + + warnOnce( 'WebGLRenderer: ' + name + ' extension not supported.' ); + + } + + return extension; + + } + + }; + +} + +function WebGLGeometries( gl, attributes, info, bindingStates ) { + + const geometries = {}; + const wireframeAttributes = new WeakMap(); + + function onGeometryDispose( event ) { + + const geometry = event.target; + + if ( geometry.index !== null ) { + + attributes.remove( geometry.index ); + + } + + for ( const name in geometry.attributes ) { + + attributes.remove( geometry.attributes[ name ] ); + + } + + geometry.removeEventListener( 'dispose', onGeometryDispose ); + + delete geometries[ geometry.id ]; + + const attribute = wireframeAttributes.get( geometry ); + + if ( attribute ) { + + attributes.remove( attribute ); + wireframeAttributes.delete( geometry ); + + } + + bindingStates.releaseStatesOfGeometry( geometry ); + + if ( geometry.isInstancedBufferGeometry === true ) { + + delete geometry._maxInstanceCount; + + } + + // + + info.memory.geometries --; + + } + + function get( object, geometry ) { + + if ( geometries[ geometry.id ] === true ) return geometry; + + geometry.addEventListener( 'dispose', onGeometryDispose ); + + geometries[ geometry.id ] = true; + + info.memory.geometries ++; + + return geometry; + + } + + function update( geometry ) { + + const geometryAttributes = geometry.attributes; + + // Updating index buffer in VAO now. See WebGLBindingStates. + + for ( const name in geometryAttributes ) { + + attributes.update( geometryAttributes[ name ], gl.ARRAY_BUFFER ); + + } + + } + + function updateWireframeAttribute( geometry ) { + + const indices = []; + + const geometryIndex = geometry.index; + const geometryPosition = geometry.attributes.position; + let version = 0; + + if ( geometryPosition === undefined ) { + + return; + + } + + if ( geometryIndex !== null ) { + + const array = geometryIndex.array; + version = geometryIndex.version; + + for ( let i = 0, l = array.length; i < l; i += 3 ) { + + const a = array[ i + 0 ]; + const b = array[ i + 1 ]; + const c = array[ i + 2 ]; + + indices.push( a, b, b, c, c, a ); + + } + + } else { + + const array = geometryPosition.array; + version = geometryPosition.version; + + for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) { + + const a = i + 0; + const b = i + 1; + const c = i + 2; + + indices.push( a, b, b, c, c, a ); + + } + + } + + // check whether a 32 bit or 16 bit buffer is required to store the indices + // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565 + const attribute = new ( geometryPosition.count >= 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 ); + attribute.version = version; + + // Updating index buffer in VAO now. See WebGLBindingStates + + // + + const previousAttribute = wireframeAttributes.get( geometry ); + + if ( previousAttribute ) attributes.remove( previousAttribute ); + + // + + wireframeAttributes.set( geometry, attribute ); + + } + + function getWireframeAttribute( geometry ) { + + const currentAttribute = wireframeAttributes.get( geometry ); + + if ( currentAttribute ) { + + const geometryIndex = geometry.index; + + if ( geometryIndex !== null ) { + + // if the attribute is obsolete, create a new one + + if ( currentAttribute.version < geometryIndex.version ) { + + updateWireframeAttribute( geometry ); + + } + + } + + } else { + + updateWireframeAttribute( geometry ); + + } + + return wireframeAttributes.get( geometry ); + + } + + return { + + get: get, + update: update, + + getWireframeAttribute: getWireframeAttribute + + }; + +} + +function WebGLIndexedBufferRenderer( gl, extensions, info ) { + + let mode; + + function setMode( value ) { + + mode = value; + + } + + let type, bytesPerElement; + + function setIndex( value ) { + + type = value.type; + bytesPerElement = value.bytesPerElement; + + } + + function render( start, count ) { + + gl.drawElements( mode, count, type, start * bytesPerElement ); + + info.update( count, mode, 1 ); + + } + + function renderInstances( start, count, primcount ) { + + if ( primcount === 0 ) return; + + gl.drawElementsInstanced( mode, count, type, start * bytesPerElement, primcount ); + + info.update( count, mode, primcount ); + + } + + function renderMultiDraw( starts, counts, drawCount ) { + + if ( drawCount === 0 ) return; + + const extension = extensions.get( 'WEBGL_multi_draw' ); + extension.multiDrawElementsWEBGL( mode, counts, 0, type, starts, 0, drawCount ); + + let elementCount = 0; + for ( let i = 0; i < drawCount; i ++ ) { + + elementCount += counts[ i ]; + + } + + info.update( elementCount, mode, 1 ); + + + } + + // + + this.setMode = setMode; + this.setIndex = setIndex; + this.render = render; + this.renderInstances = renderInstances; + this.renderMultiDraw = renderMultiDraw; + +} + +function WebGLInfo( gl ) { + + const memory = { + geometries: 0, + textures: 0 + }; + + const render = { + frame: 0, + calls: 0, + triangles: 0, + points: 0, + lines: 0 + }; + + function update( count, mode, instanceCount ) { + + render.calls ++; + + switch ( mode ) { + + case gl.TRIANGLES: + render.triangles += instanceCount * ( count / 3 ); + break; + + case gl.LINES: + render.lines += instanceCount * ( count / 2 ); + break; + + case gl.LINE_STRIP: + render.lines += instanceCount * ( count - 1 ); + break; + + case gl.LINE_LOOP: + render.lines += instanceCount * count; + break; + + case gl.POINTS: + render.points += instanceCount * count; + break; + + default: + error( 'WebGLInfo: Unknown draw mode:', mode ); + break; + + } + + } + + function reset() { + + render.calls = 0; + render.triangles = 0; + render.points = 0; + render.lines = 0; + + } + + return { + memory: memory, + render: render, + programs: null, + autoReset: true, + reset: reset, + update: update + }; + +} + +function WebGLMorphtargets( gl, capabilities, textures ) { + + const morphTextures = new WeakMap(); + const morph = new Vector4(); + + function update( object, geometry, program ) { + + const objectInfluences = object.morphTargetInfluences; + + // the following encodes morph targets into an array of data textures. Each layer represents a single morph target. + + const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color; + const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0; + + let entry = morphTextures.get( geometry ); + + if ( entry === undefined || entry.count !== morphTargetsCount ) { + + if ( entry !== undefined ) entry.texture.dispose(); + + const hasMorphPosition = geometry.morphAttributes.position !== undefined; + const hasMorphNormals = geometry.morphAttributes.normal !== undefined; + const hasMorphColors = geometry.morphAttributes.color !== undefined; + + const morphTargets = geometry.morphAttributes.position || []; + const morphNormals = geometry.morphAttributes.normal || []; + const morphColors = geometry.morphAttributes.color || []; + + let vertexDataCount = 0; + + if ( hasMorphPosition === true ) vertexDataCount = 1; + if ( hasMorphNormals === true ) vertexDataCount = 2; + if ( hasMorphColors === true ) vertexDataCount = 3; + + let width = geometry.attributes.position.count * vertexDataCount; + let height = 1; + + if ( width > capabilities.maxTextureSize ) { + + height = Math.ceil( width / capabilities.maxTextureSize ); + width = capabilities.maxTextureSize; + + } + + const buffer = new Float32Array( width * height * 4 * morphTargetsCount ); + + const texture = new DataArrayTexture( buffer, width, height, morphTargetsCount ); + texture.type = FloatType; + texture.needsUpdate = true; + + // fill buffer + + const vertexDataStride = vertexDataCount * 4; + + for ( let i = 0; i < morphTargetsCount; i ++ ) { + + const morphTarget = morphTargets[ i ]; + const morphNormal = morphNormals[ i ]; + const morphColor = morphColors[ i ]; + + const offset = width * height * 4 * i; + + for ( let j = 0; j < morphTarget.count; j ++ ) { + + const stride = j * vertexDataStride; + + if ( hasMorphPosition === true ) { + + morph.fromBufferAttribute( morphTarget, j ); + + buffer[ offset + stride + 0 ] = morph.x; + buffer[ offset + stride + 1 ] = morph.y; + buffer[ offset + stride + 2 ] = morph.z; + buffer[ offset + stride + 3 ] = 0; + + } + + if ( hasMorphNormals === true ) { + + morph.fromBufferAttribute( morphNormal, j ); + + buffer[ offset + stride + 4 ] = morph.x; + buffer[ offset + stride + 5 ] = morph.y; + buffer[ offset + stride + 6 ] = morph.z; + buffer[ offset + stride + 7 ] = 0; + + } + + if ( hasMorphColors === true ) { + + morph.fromBufferAttribute( morphColor, j ); + + buffer[ offset + stride + 8 ] = morph.x; + buffer[ offset + stride + 9 ] = morph.y; + buffer[ offset + stride + 10 ] = morph.z; + buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? morph.w : 1; + + } + + } + + } + + entry = { + count: morphTargetsCount, + texture: texture, + size: new Vector2( width, height ) + }; + + morphTextures.set( geometry, entry ); + + function disposeTexture() { + + texture.dispose(); + + morphTextures.delete( geometry ); + + geometry.removeEventListener( 'dispose', disposeTexture ); + + } + + geometry.addEventListener( 'dispose', disposeTexture ); + + } + + // + if ( object.isInstancedMesh === true && object.morphTexture !== null ) { + + program.getUniforms().setValue( gl, 'morphTexture', object.morphTexture, textures ); + + } else { + + let morphInfluencesSum = 0; + + for ( let i = 0; i < objectInfluences.length; i ++ ) { + + morphInfluencesSum += objectInfluences[ i ]; + + } + + const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum; + + + program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence ); + program.getUniforms().setValue( gl, 'morphTargetInfluences', objectInfluences ); + + } + + program.getUniforms().setValue( gl, 'morphTargetsTexture', entry.texture, textures ); + program.getUniforms().setValue( gl, 'morphTargetsTextureSize', entry.size ); + + } + + return { + + update: update + + }; + +} + +function WebGLObjects( gl, geometries, attributes, bindingStates, info ) { + + let updateMap = new WeakMap(); + + function update( object ) { + + const frame = info.render.frame; + + const geometry = object.geometry; + const buffergeometry = geometries.get( object, geometry ); + + // Update once per frame + + if ( updateMap.get( buffergeometry ) !== frame ) { + + geometries.update( buffergeometry ); + + updateMap.set( buffergeometry, frame ); + + } + + if ( object.isInstancedMesh ) { + + if ( object.hasEventListener( 'dispose', onInstancedMeshDispose ) === false ) { + + object.addEventListener( 'dispose', onInstancedMeshDispose ); + + } + + if ( updateMap.get( object ) !== frame ) { + + attributes.update( object.instanceMatrix, gl.ARRAY_BUFFER ); + + if ( object.instanceColor !== null ) { + + attributes.update( object.instanceColor, gl.ARRAY_BUFFER ); + + } + + updateMap.set( object, frame ); + + } + + } + + if ( object.isSkinnedMesh ) { + + const skeleton = object.skeleton; + + if ( updateMap.get( skeleton ) !== frame ) { + + skeleton.update(); + + updateMap.set( skeleton, frame ); + + } + + } + + return buffergeometry; + + } + + function dispose() { + + updateMap = new WeakMap(); + + } + + function onInstancedMeshDispose( event ) { + + const instancedMesh = event.target; + + instancedMesh.removeEventListener( 'dispose', onInstancedMeshDispose ); + + bindingStates.releaseStatesOfObject( instancedMesh ); + + attributes.remove( instancedMesh.instanceMatrix ); + + if ( instancedMesh.instanceColor !== null ) attributes.remove( instancedMesh.instanceColor ); + + } + + return { + + update: update, + dispose: dispose + + }; + +} + +const toneMappingMap = { + [ LinearToneMapping ]: 'LINEAR_TONE_MAPPING', + [ ReinhardToneMapping ]: 'REINHARD_TONE_MAPPING', + [ CineonToneMapping ]: 'CINEON_TONE_MAPPING', + [ ACESFilmicToneMapping ]: 'ACES_FILMIC_TONE_MAPPING', + [ AgXToneMapping ]: 'AGX_TONE_MAPPING', + [ NeutralToneMapping ]: 'NEUTRAL_TONE_MAPPING', + [ CustomToneMapping ]: 'CUSTOM_TONE_MAPPING' +}; + +function WebGLOutput( type, width, height, antialias, depth, stencil ) { + + // render target for the scene pass (potentially multisampled) + const targetScene = new WebGLRenderTarget( width, height, { + type: type, + depthBuffer: depth, + stencilBuffer: stencil, + samples: antialias ? 4 : 0, + storeMultisampledDepthBuffer: false, + storeMultisampledStencilBuffer: false, + resolveDepthBuffer: false, + resolveStencilBuffer: false + } ); + + // single-sampled ping-pong buffers for post-processing effects, allocated on demand + let targetA = null; + let targetB = null; + + // create fullscreen triangle geometry + const geometry = new BufferGeometry(); + geometry.setAttribute( 'position', new Float32BufferAttribute( [ -1, 3, 0, -1, -1, 0, 3, -1, 0 ], 3 ) ); + geometry.setAttribute( 'uv', new Float32BufferAttribute( [ 0, 2, 0, 0, 2, 0 ], 2 ) ); + + // create output material with tone mapping support + const material = new RawShaderMaterial( { + uniforms: { + tDiffuse: { value: null } + }, + vertexShader: /* glsl */` + precision highp float; + + uniform mat4 modelViewMatrix; + uniform mat4 projectionMatrix; + + attribute vec3 position; + attribute vec2 uv; + + varying vec2 vUv; + + void main() { + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + }`, + fragmentShader: /* glsl */` + precision highp float; + + uniform sampler2D tDiffuse; + + varying vec2 vUv; + + #include + #include + + void main() { + gl_FragColor = texture2D( tDiffuse, vUv ); + + #ifdef LINEAR_TONE_MAPPING + gl_FragColor.rgb = LinearToneMapping( gl_FragColor.rgb ); + #elif defined( REINHARD_TONE_MAPPING ) + gl_FragColor.rgb = ReinhardToneMapping( gl_FragColor.rgb ); + #elif defined( CINEON_TONE_MAPPING ) + gl_FragColor.rgb = CineonToneMapping( gl_FragColor.rgb ); + #elif defined( ACES_FILMIC_TONE_MAPPING ) + gl_FragColor.rgb = ACESFilmicToneMapping( gl_FragColor.rgb ); + #elif defined( AGX_TONE_MAPPING ) + gl_FragColor.rgb = AgXToneMapping( gl_FragColor.rgb ); + #elif defined( NEUTRAL_TONE_MAPPING ) + gl_FragColor.rgb = NeutralToneMapping( gl_FragColor.rgb ); + #elif defined( CUSTOM_TONE_MAPPING ) + gl_FragColor.rgb = CustomToneMapping( gl_FragColor.rgb ); + #endif + + #ifdef SRGB_TRANSFER + gl_FragColor = sRGBTransferOETF( gl_FragColor ); + #endif + }`, + depthTest: false, + depthWrite: false + } ); + + const mesh = new Mesh( geometry, material ); + const camera = new OrthographicCamera( -1, 1, 1, -1, 0, 1 ); + + let _outputColorSpace = null; + let _outputToneMapping = null; + let _isCompositing = false; + let _savedToneMapping; + let _savedRenderTarget = null; + let _effects = []; + let _hasRenderPass = false; + + this.setSize = function ( width, height ) { + + targetScene.setSize( width, height ); + + if ( targetA !== null ) targetA.setSize( width, height ); + if ( targetB !== null ) targetB.setSize( width, height ); + + for ( let i = 0; i < _effects.length; i ++ ) { + + const effect = _effects[ i ]; + if ( effect.setSize ) effect.setSize( width, height ); + + } + + }; + + this.setEffects = function ( effects ) { + + _effects = effects; + _hasRenderPass = _effects.length > 0 && _effects[ 0 ].isRenderPass === true; + + const width = targetScene.width; + const height = targetScene.height; + + if ( _effects.length > 0 && targetA === null ) { + + targetA = new WebGLRenderTarget( width, height, { type: HalfFloatType, depthBuffer: false, stencilBuffer: false } ); + targetB = new WebGLRenderTarget( width, height, { type: HalfFloatType, depthBuffer: false, stencilBuffer: false } ); + + } + + for ( let i = 0; i < _effects.length; i ++ ) { + + const effect = _effects[ i ]; + if ( effect.setSize ) effect.setSize( width, height ); + + } + + }; + + this.begin = function ( renderer, renderTarget ) { + + // Don't begin during compositing phase (post-processing effects call render()) + if ( _isCompositing ) return false; + + if ( renderer.toneMapping === NoToneMapping && _effects.length === 0 ) return false; + + _savedRenderTarget = renderTarget; + + // resize internal buffers to match render target (e.g. XR resolution) + if ( renderTarget !== null ) { + + const width = renderTarget.width; + const height = renderTarget.height; + + if ( targetScene.width !== width || targetScene.height !== height ) { + + this.setSize( width, height ); + + } + + } + + // if the first effect is a RenderPass, it renders the scene itself (see end()) + if ( _hasRenderPass === false ) { + + renderer.setRenderTarget( targetScene ); + + } + + // disable tone mapping during render - it will be applied in end() + _savedToneMapping = renderer.toneMapping; + renderer.toneMapping = NoToneMapping; + + return true; + + }; + + this.hasRenderPass = function () { + + return _hasRenderPass; + + }; + + this.end = function ( renderer, deltaTime ) { + + // restore tone mapping + renderer.toneMapping = _savedToneMapping; + + _isCompositing = true; + + // run post-processing effects - the scene lives in the multisampled targetScene, + // effects ping-pong between the single-sampled targetA and targetB + let readBuffer = targetScene; + let writeBuffer = targetA; + + for ( let i = 0; i < _effects.length; i ++ ) { + + const effect = _effects[ i ]; + + if ( effect.enabled === false ) continue; + + effect.render( renderer, writeBuffer, readBuffer, deltaTime ); + + if ( effect.needsSwap !== false ) { + + // keep targetScene out of the rotation so only the scene pass is multisampled + readBuffer = writeBuffer; + writeBuffer = ( writeBuffer === targetA ) ? targetB : targetA; + + } + + } + + // update output material defines if settings changed + if ( _outputColorSpace !== renderer.outputColorSpace || _outputToneMapping !== renderer.toneMapping ) { + + _outputColorSpace = renderer.outputColorSpace; + _outputToneMapping = renderer.toneMapping; + + material.defines = {}; + + if ( ColorManagement.getTransfer( _outputColorSpace ) === SRGBTransfer ) material.defines.SRGB_TRANSFER = ''; + + const toneMapping = toneMappingMap[ _outputToneMapping ]; + if ( toneMapping ) material.defines[ toneMapping ] = ''; + + material.needsUpdate = true; + + } + + // final output to canvas (or XR render target) + material.uniforms.tDiffuse.value = readBuffer.texture; + renderer.setRenderTarget( _savedRenderTarget ); + renderer.render( mesh, camera ); + + _savedRenderTarget = null; + _isCompositing = false; + + }; + + this.isCompositing = function () { + + return _isCompositing; + + }; + + this.dispose = function () { + + targetScene.dispose(); + + if ( targetA !== null ) targetA.dispose(); + if ( targetB !== null ) targetB.dispose(); + + geometry.dispose(); + material.dispose(); + + }; + +} + +/** + * Uniforms of a program. + * Those form a tree structure with a special top-level container for the root, + * which you get by calling 'new WebGLUniforms( gl, program )'. + * + * + * Properties of inner nodes including the top-level container: + * + * .seq - array of nested uniforms + * .map - nested uniforms by name + * + * + * Methods of all nodes except the top-level container: + * + * .setValue( gl, value, [textures] ) + * + * uploads a uniform value(s) + * the 'textures' parameter is needed for sampler uniforms + * + * + * Static methods of the top-level container (textures factorizations): + * + * .upload( gl, seq, values, textures ) + * + * sets uniforms in 'seq' to 'values[id].value' + * + * .seqWithValue( seq, values ) : filteredSeq + * + * filters 'seq' entries with corresponding entry in values + * + * + * Methods of the top-level container (textures factorizations): + * + * .setValue( gl, name, value, textures ) + * + * sets uniform with name 'name' to 'value' + * + * .setOptional( gl, obj, prop ) + * + * like .set for an optional property of the object + * + */ + + +const emptyTexture = /*@__PURE__*/ new Texture(); + +const emptyShadowTexture = /*@__PURE__*/ new DepthTexture( 1, 1 ); + +const emptyArrayTexture = /*@__PURE__*/ new DataArrayTexture(); +const empty3dTexture = /*@__PURE__*/ new Data3DTexture(); +const emptyCubeTexture = /*@__PURE__*/ new CubeTexture(); + +// --- Utilities --- + +// Array Caches (provide typed arrays for temporary by size) + +const arrayCacheF32 = []; +const arrayCacheI32 = []; + +// Float32Array caches used for uploading Matrix uniforms + +const mat4array = new Float32Array( 16 ); +const mat3array = new Float32Array( 9 ); +const mat2array = new Float32Array( 4 ); + +// Flattening for arrays of vectors and matrices + +function flatten( array, nBlocks, blockSize ) { + + const firstElem = array[ 0 ]; + + if ( firstElem <= 0 || firstElem > 0 ) return array; + // unoptimized: ! isNaN( firstElem ) + // see http://jacksondunstan.com/articles/983 + + const n = nBlocks * blockSize; + let r = arrayCacheF32[ n ]; + + if ( r === undefined ) { + + r = new Float32Array( n ); + arrayCacheF32[ n ] = r; + + } + + if ( nBlocks !== 0 ) { + + firstElem.toArray( r, 0 ); + + for ( let i = 1, offset = 0; i !== nBlocks; ++ i ) { + + offset += blockSize; + array[ i ].toArray( r, offset ); + + } + + } + + return r; + +} + +function arraysEqual( a, b ) { + + if ( a.length !== b.length ) return false; + + for ( let i = 0, l = a.length; i < l; i ++ ) { + + if ( a[ i ] !== b[ i ] ) return false; + + } + + return true; + +} + +function copyArray( a, b ) { + + for ( let i = 0, l = b.length; i < l; i ++ ) { + + a[ i ] = b[ i ]; + + } + +} + +// Texture unit allocation + +function allocTexUnits( textures, n ) { + + let r = arrayCacheI32[ n ]; + + if ( r === undefined ) { + + r = new Int32Array( n ); + arrayCacheI32[ n ] = r; + + } + + for ( let i = 0; i !== n; ++ i ) { + + r[ i ] = textures.allocateTextureUnit(); + + } + + return r; + +} + +// --- Setters --- + +// Note: Defining these methods externally, because they come in a bunch +// and this way their names minify. + +// Single scalar + +function setValueV1f( gl, v ) { + + const cache = this.cache; + + if ( cache[ 0 ] === v ) return; + + gl.uniform1f( this.addr, v ); + + cache[ 0 ] = v; + +} + +// Single float vector (from flat array or THREE.VectorN) + +function setValueV2f( gl, v ) { + + const cache = this.cache; + + if ( v.x !== undefined ) { + + if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) { + + gl.uniform2f( this.addr, v.x, v.y ); + + cache[ 0 ] = v.x; + cache[ 1 ] = v.y; + + } + + } else { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniform2fv( this.addr, v ); + + copyArray( cache, v ); + + } + +} + +function setValueV3f( gl, v ) { + + const cache = this.cache; + + if ( v.x !== undefined ) { + + if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) { + + gl.uniform3f( this.addr, v.x, v.y, v.z ); + + cache[ 0 ] = v.x; + cache[ 1 ] = v.y; + cache[ 2 ] = v.z; + + } + + } else if ( v.r !== undefined ) { + + if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) { + + gl.uniform3f( this.addr, v.r, v.g, v.b ); + + cache[ 0 ] = v.r; + cache[ 1 ] = v.g; + cache[ 2 ] = v.b; + + } + + } else { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniform3fv( this.addr, v ); + + copyArray( cache, v ); + + } + +} + +function setValueV4f( gl, v ) { + + const cache = this.cache; + + if ( v.x !== undefined ) { + + if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) { + + gl.uniform4f( this.addr, v.x, v.y, v.z, v.w ); + + cache[ 0 ] = v.x; + cache[ 1 ] = v.y; + cache[ 2 ] = v.z; + cache[ 3 ] = v.w; + + } + + } else { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniform4fv( this.addr, v ); + + copyArray( cache, v ); + + } + +} + +// Single matrix (from flat array or THREE.MatrixN) + +function setValueM2( gl, v ) { + + const cache = this.cache; + const elements = v.elements; + + if ( elements === undefined ) { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniformMatrix2fv( this.addr, false, v ); + + copyArray( cache, v ); + + } else { + + if ( arraysEqual( cache, elements ) ) return; + + mat2array.set( elements ); + + gl.uniformMatrix2fv( this.addr, false, mat2array ); + + copyArray( cache, elements ); + + } + +} + +function setValueM3( gl, v ) { + + const cache = this.cache; + const elements = v.elements; + + if ( elements === undefined ) { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniformMatrix3fv( this.addr, false, v ); + + copyArray( cache, v ); + + } else { + + if ( arraysEqual( cache, elements ) ) return; + + mat3array.set( elements ); + + gl.uniformMatrix3fv( this.addr, false, mat3array ); + + copyArray( cache, elements ); + + } + +} + +function setValueM4( gl, v ) { + + const cache = this.cache; + const elements = v.elements; + + if ( elements === undefined ) { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniformMatrix4fv( this.addr, false, v ); + + copyArray( cache, v ); + + } else { + + if ( arraysEqual( cache, elements ) ) return; + + mat4array.set( elements ); + + gl.uniformMatrix4fv( this.addr, false, mat4array ); + + copyArray( cache, elements ); + + } + +} + +// Single integer / boolean + +function setValueV1i( gl, v ) { + + const cache = this.cache; + + if ( cache[ 0 ] === v ) return; + + gl.uniform1i( this.addr, v ); + + cache[ 0 ] = v; + +} + +// Single integer / boolean vector (from flat array or THREE.VectorN) + +function setValueV2i( gl, v ) { + + const cache = this.cache; + + if ( v.x !== undefined ) { + + if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) { + + gl.uniform2i( this.addr, v.x, v.y ); + + cache[ 0 ] = v.x; + cache[ 1 ] = v.y; + + } + + } else { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniform2iv( this.addr, v ); + + copyArray( cache, v ); + + } + +} + +function setValueV3i( gl, v ) { + + const cache = this.cache; + + if ( v.x !== undefined ) { + + if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) { + + gl.uniform3i( this.addr, v.x, v.y, v.z ); + + cache[ 0 ] = v.x; + cache[ 1 ] = v.y; + cache[ 2 ] = v.z; + + } + + } else { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniform3iv( this.addr, v ); + + copyArray( cache, v ); + + } + +} + +function setValueV4i( gl, v ) { + + const cache = this.cache; + + if ( v.x !== undefined ) { + + if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) { + + gl.uniform4i( this.addr, v.x, v.y, v.z, v.w ); + + cache[ 0 ] = v.x; + cache[ 1 ] = v.y; + cache[ 2 ] = v.z; + cache[ 3 ] = v.w; + + } + + } else { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniform4iv( this.addr, v ); + + copyArray( cache, v ); + + } + +} + +// Single unsigned integer + +function setValueV1ui( gl, v ) { + + const cache = this.cache; + + if ( cache[ 0 ] === v ) return; + + gl.uniform1ui( this.addr, v ); + + cache[ 0 ] = v; + +} + +// Single unsigned integer vector (from flat array or THREE.VectorN) + +function setValueV2ui( gl, v ) { + + const cache = this.cache; + + if ( v.x !== undefined ) { + + if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) { + + gl.uniform2ui( this.addr, v.x, v.y ); + + cache[ 0 ] = v.x; + cache[ 1 ] = v.y; + + } + + } else { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniform2uiv( this.addr, v ); + + copyArray( cache, v ); + + } + +} + +function setValueV3ui( gl, v ) { + + const cache = this.cache; + + if ( v.x !== undefined ) { + + if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) { + + gl.uniform3ui( this.addr, v.x, v.y, v.z ); + + cache[ 0 ] = v.x; + cache[ 1 ] = v.y; + cache[ 2 ] = v.z; + + } + + } else { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniform3uiv( this.addr, v ); + + copyArray( cache, v ); + + } + +} + +function setValueV4ui( gl, v ) { + + const cache = this.cache; + + if ( v.x !== undefined ) { + + if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) { + + gl.uniform4ui( this.addr, v.x, v.y, v.z, v.w ); + + cache[ 0 ] = v.x; + cache[ 1 ] = v.y; + cache[ 2 ] = v.z; + cache[ 3 ] = v.w; + + } + + } else { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniform4uiv( this.addr, v ); + + copyArray( cache, v ); + + } + +} + + +// Single texture (2D / Cube) + +function setValueT1( gl, v, textures ) { + + const cache = this.cache; + const unit = textures.allocateTextureUnit(); + + if ( cache[ 0 ] !== unit ) { + + gl.uniform1i( this.addr, unit ); + cache[ 0 ] = unit; + + } + + let emptyTexture2D; + + if ( this.type === gl.SAMPLER_2D_SHADOW ) { + + emptyShadowTexture.compareFunction = textures.isReversedDepthBuffer() ? GreaterEqualCompare : LessEqualCompare; + emptyTexture2D = emptyShadowTexture; + + } else { + + emptyTexture2D = emptyTexture; + + } + + textures.setTexture2D( v || emptyTexture2D, unit ); + +} + +function setValueT3D1( gl, v, textures ) { + + const cache = this.cache; + const unit = textures.allocateTextureUnit(); + + if ( cache[ 0 ] !== unit ) { + + gl.uniform1i( this.addr, unit ); + cache[ 0 ] = unit; + + } + + textures.setTexture3D( v || empty3dTexture, unit ); + +} + +function setValueT6( gl, v, textures ) { + + const cache = this.cache; + const unit = textures.allocateTextureUnit(); + + if ( cache[ 0 ] !== unit ) { + + gl.uniform1i( this.addr, unit ); + cache[ 0 ] = unit; + + } + + textures.setTextureCube( v || emptyCubeTexture, unit ); + +} + +function setValueT2DArray1( gl, v, textures ) { + + const cache = this.cache; + const unit = textures.allocateTextureUnit(); + + if ( cache[ 0 ] !== unit ) { + + gl.uniform1i( this.addr, unit ); + cache[ 0 ] = unit; + + } + + textures.setTexture2DArray( v || emptyArrayTexture, unit ); + +} + +// Helper to pick the right setter for the singular case + +function getSingularSetter( type ) { + + switch ( type ) { + + case 0x1406: return setValueV1f; // FLOAT + case 0x8b50: return setValueV2f; // _VEC2 + case 0x8b51: return setValueV3f; // _VEC3 + case 0x8b52: return setValueV4f; // _VEC4 + + case 0x8b5a: return setValueM2; // _MAT2 + case 0x8b5b: return setValueM3; // _MAT3 + case 0x8b5c: return setValueM4; // _MAT4 + + case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL + case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2 + case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3 + case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4 + + case 0x1405: return setValueV1ui; // UINT + case 0x8dc6: return setValueV2ui; // _VEC2 + case 0x8dc7: return setValueV3ui; // _VEC3 + case 0x8dc8: return setValueV4ui; // _VEC4 + + case 0x8b5e: // SAMPLER_2D + case 0x8d66: // SAMPLER_EXTERNAL_OES + case 0x8dca: // INT_SAMPLER_2D + case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D + case 0x8b62: // SAMPLER_2D_SHADOW + return setValueT1; + + case 0x8b5f: // SAMPLER_3D + case 0x8dcb: // INT_SAMPLER_3D + case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D + return setValueT3D1; + + case 0x8b60: // SAMPLER_CUBE + case 0x8dcc: // INT_SAMPLER_CUBE + case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE + case 0x8dc5: // SAMPLER_CUBE_SHADOW + return setValueT6; + + case 0x8dc1: // SAMPLER_2D_ARRAY + case 0x8dcf: // INT_SAMPLER_2D_ARRAY + case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY + case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW + return setValueT2DArray1; + + } + +} + + +// Array of scalars + +function setValueV1fArray( gl, v ) { + + gl.uniform1fv( this.addr, v ); + +} + +// Array of vectors (from flat array or array of THREE.VectorN) + +function setValueV2fArray( gl, v ) { + + const data = flatten( v, this.size, 2 ); + + gl.uniform2fv( this.addr, data ); + +} + +function setValueV3fArray( gl, v ) { + + const data = flatten( v, this.size, 3 ); + + gl.uniform3fv( this.addr, data ); + +} + +function setValueV4fArray( gl, v ) { + + const data = flatten( v, this.size, 4 ); + + gl.uniform4fv( this.addr, data ); + +} + +// Array of matrices (from flat array or array of THREE.MatrixN) + +function setValueM2Array( gl, v ) { + + const data = flatten( v, this.size, 4 ); + + gl.uniformMatrix2fv( this.addr, false, data ); + +} + +function setValueM3Array( gl, v ) { + + const data = flatten( v, this.size, 9 ); + + gl.uniformMatrix3fv( this.addr, false, data ); + +} + +function setValueM4Array( gl, v ) { + + const data = flatten( v, this.size, 16 ); + + gl.uniformMatrix4fv( this.addr, false, data ); + +} + +// Array of integer / boolean + +function setValueV1iArray( gl, v ) { + + gl.uniform1iv( this.addr, v ); + +} + +// Array of integer / boolean vectors (from flat array) + +function setValueV2iArray( gl, v ) { + + gl.uniform2iv( this.addr, v ); + +} + +function setValueV3iArray( gl, v ) { + + gl.uniform3iv( this.addr, v ); + +} + +function setValueV4iArray( gl, v ) { + + gl.uniform4iv( this.addr, v ); + +} + +// Array of unsigned integer + +function setValueV1uiArray( gl, v ) { + + gl.uniform1uiv( this.addr, v ); + +} + +// Array of unsigned integer vectors (from flat array) + +function setValueV2uiArray( gl, v ) { + + gl.uniform2uiv( this.addr, v ); + +} + +function setValueV3uiArray( gl, v ) { + + gl.uniform3uiv( this.addr, v ); + +} + +function setValueV4uiArray( gl, v ) { + + gl.uniform4uiv( this.addr, v ); + +} + + +// Array of textures (2D / 3D / Cube / 2DArray) + +function setValueT1Array( gl, v, textures ) { + + const cache = this.cache; + + const n = v.length; + + const units = allocTexUnits( textures, n ); + + if ( ! arraysEqual( cache, units ) ) { + + gl.uniform1iv( this.addr, units ); + + copyArray( cache, units ); + + } + + let emptyTexture2D; + + if ( this.type === gl.SAMPLER_2D_SHADOW ) { + + emptyTexture2D = emptyShadowTexture; + + } else { + + emptyTexture2D = emptyTexture; + + } + + for ( let i = 0; i !== n; ++ i ) { + + textures.setTexture2D( v[ i ] || emptyTexture2D, units[ i ] ); + + } + +} + +function setValueT3DArray( gl, v, textures ) { + + const cache = this.cache; + + const n = v.length; + + const units = allocTexUnits( textures, n ); + + if ( ! arraysEqual( cache, units ) ) { + + gl.uniform1iv( this.addr, units ); + + copyArray( cache, units ); + + } + + for ( let i = 0; i !== n; ++ i ) { + + textures.setTexture3D( v[ i ] || empty3dTexture, units[ i ] ); + + } + +} + +function setValueT6Array( gl, v, textures ) { + + const cache = this.cache; + + const n = v.length; + + const units = allocTexUnits( textures, n ); + + if ( ! arraysEqual( cache, units ) ) { + + gl.uniform1iv( this.addr, units ); + + copyArray( cache, units ); + + } + + for ( let i = 0; i !== n; ++ i ) { + + textures.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] ); + + } + +} + +function setValueT2DArrayArray( gl, v, textures ) { + + const cache = this.cache; + + const n = v.length; + + const units = allocTexUnits( textures, n ); + + if ( ! arraysEqual( cache, units ) ) { + + gl.uniform1iv( this.addr, units ); + + copyArray( cache, units ); + + } + + for ( let i = 0; i !== n; ++ i ) { + + textures.setTexture2DArray( v[ i ] || emptyArrayTexture, units[ i ] ); + + } + +} + + +// Helper to pick the right setter for a pure (bottom-level) array + +function getPureArraySetter( type ) { + + switch ( type ) { + + case 0x1406: return setValueV1fArray; // FLOAT + case 0x8b50: return setValueV2fArray; // _VEC2 + case 0x8b51: return setValueV3fArray; // _VEC3 + case 0x8b52: return setValueV4fArray; // _VEC4 + + case 0x8b5a: return setValueM2Array; // _MAT2 + case 0x8b5b: return setValueM3Array; // _MAT3 + case 0x8b5c: return setValueM4Array; // _MAT4 + + case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL + case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2 + case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3 + case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4 + + case 0x1405: return setValueV1uiArray; // UINT + case 0x8dc6: return setValueV2uiArray; // _VEC2 + case 0x8dc7: return setValueV3uiArray; // _VEC3 + case 0x8dc8: return setValueV4uiArray; // _VEC4 + + case 0x8b5e: // SAMPLER_2D + case 0x8d66: // SAMPLER_EXTERNAL_OES + case 0x8dca: // INT_SAMPLER_2D + case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D + case 0x8b62: // SAMPLER_2D_SHADOW + return setValueT1Array; + + case 0x8b5f: // SAMPLER_3D + case 0x8dcb: // INT_SAMPLER_3D + case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D + return setValueT3DArray; + + case 0x8b60: // SAMPLER_CUBE + case 0x8dcc: // INT_SAMPLER_CUBE + case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE + case 0x8dc5: // SAMPLER_CUBE_SHADOW + return setValueT6Array; + + case 0x8dc1: // SAMPLER_2D_ARRAY + case 0x8dcf: // INT_SAMPLER_2D_ARRAY + case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY + case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW + return setValueT2DArrayArray; + + } + +} + +// --- Uniform Classes --- + +class SingleUniform { + + constructor( id, activeInfo, addr ) { + + this.id = id; + this.addr = addr; + this.cache = []; + this.type = activeInfo.type; + this.setValue = getSingularSetter( activeInfo.type ); + + // this.path = activeInfo.name; // DEBUG + + } + +} + +class PureArrayUniform { + + constructor( id, activeInfo, addr ) { + + this.id = id; + this.addr = addr; + this.cache = []; + this.type = activeInfo.type; + this.size = activeInfo.size; + this.setValue = getPureArraySetter( activeInfo.type ); + + // this.path = activeInfo.name; // DEBUG + + } + +} + +class StructuredUniform { + + constructor( id ) { + + this.id = id; + + this.seq = []; + this.map = {}; + + } + + setValue( gl, value, textures ) { + + const seq = this.seq; + + for ( let i = 0, n = seq.length; i !== n; ++ i ) { + + const u = seq[ i ]; + u.setValue( gl, value[ u.id ], textures ); + + } + + } + +} + +// --- Top-level --- + +// Parser - builds up the property tree from the path strings + +const RePathPart = /(\w+)(\])?(\[|\.)?/g; + +// extracts +// - the identifier (member name or array index) +// - followed by an optional right bracket (found when array index) +// - followed by an optional left bracket or dot (type of subscript) +// +// Note: These portions can be read in a non-overlapping fashion and +// allow straightforward parsing of the hierarchy that WebGL encodes +// in the uniform names. + +function addUniform( container, uniformObject ) { + + container.seq.push( uniformObject ); + container.map[ uniformObject.id ] = uniformObject; + +} + +function parseUniform( activeInfo, addr, container ) { + + const path = activeInfo.name, + pathLength = path.length; + + // reset RegExp object, because of the early exit of a previous run + RePathPart.lastIndex = 0; + + while ( true ) { + + const match = RePathPart.exec( path ), + matchEnd = RePathPart.lastIndex; + + let id = match[ 1 ]; + const idIsIndex = match[ 2 ] === ']', + subscript = match[ 3 ]; + + if ( idIsIndex ) id = id | 0; // convert to integer + + if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) { + + // bare name or "pure" bottom-level array "[0]" suffix + + addUniform( container, subscript === undefined ? + new SingleUniform( id, activeInfo, addr ) : + new PureArrayUniform( id, activeInfo, addr ) ); + + break; + + } else { + + // step into inner node / create it in case it doesn't exist + + const map = container.map; + let next = map[ id ]; + + if ( next === undefined ) { + + next = new StructuredUniform( id ); + addUniform( container, next ); + + } + + container = next; + + } + + } + +} + +// Root Container + +class WebGLUniforms { + + constructor( gl, program ) { + + this.seq = []; + this.map = {}; + + const n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS ); + + for ( let i = 0; i < n; ++ i ) { + + const info = gl.getActiveUniform( program, i ), + addr = gl.getUniformLocation( program, info.name ); + + parseUniform( info, addr, this ); + + } + + // Sort uniforms to prioritize shadow samplers first (for optimal texture unit allocation) + + const shadowSamplers = []; + const otherUniforms = []; + + for ( const u of this.seq ) { + + if ( u.type === gl.SAMPLER_2D_SHADOW || u.type === gl.SAMPLER_CUBE_SHADOW || u.type === gl.SAMPLER_2D_ARRAY_SHADOW ) { + + shadowSamplers.push( u ); + + } else { + + otherUniforms.push( u ); + + } + + } + + if ( shadowSamplers.length > 0 ) { + + this.seq = shadowSamplers.concat( otherUniforms ); + + } + + } + + setValue( gl, name, value, textures ) { + + const u = this.map[ name ]; + + if ( u !== undefined ) u.setValue( gl, value, textures ); + + } + + setOptional( gl, object, name ) { + + const v = object[ name ]; + + if ( v !== undefined ) this.setValue( gl, name, v ); + + } + + static upload( gl, seq, values, textures ) { + + for ( let i = 0, n = seq.length; i !== n; ++ i ) { + + const u = seq[ i ], + v = values[ u.id ]; + + if ( v.needsUpdate !== false ) { + + // note: always updating when .needsUpdate is undefined + u.setValue( gl, v.value, textures ); + + } + + } + + } + + static seqWithValue( seq, values ) { + + const r = []; + + for ( let i = 0, n = seq.length; i !== n; ++ i ) { + + const u = seq[ i ]; + if ( u.id in values ) r.push( u ); + + } + + return r; + + } + +} + +function WebGLShader( gl, type, string ) { + + const shader = gl.createShader( type ); + + gl.shaderSource( shader, string ); + gl.compileShader( shader ); + + return shader; + +} + +// From https://www.khronos.org/registry/webgl/extensions/KHR_parallel_shader_compile/ +const COMPLETION_STATUS_KHR = 0x91B1; + +let programIdCount = 0; + +function handleSource( string, errorLine ) { + + const lines = string.split( '\n' ); + const lines2 = []; + + const from = Math.max( errorLine - 6, 0 ); + const to = Math.min( errorLine + 6, lines.length ); + + for ( let i = from; i < to; i ++ ) { + + const line = i + 1; + lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` ); + + } + + return lines2.join( '\n' ); + +} + +const _m0 = /*@__PURE__*/ new Matrix3(); + +function getEncodingComponents( colorSpace ) { + + ColorManagement._getMatrix( _m0, ColorManagement.workingColorSpace, colorSpace ); + + const encodingMatrix = `mat3( ${ _m0.elements.map( ( v ) => v.toFixed( 4 ) ) } )`; + + switch ( ColorManagement.getTransfer( colorSpace ) ) { + + case LinearTransfer: + return [ encodingMatrix, 'LinearTransferOETF' ]; + + case SRGBTransfer: + return [ encodingMatrix, 'sRGBTransferOETF' ]; + + default: + warn( 'WebGLProgram: Unsupported color space: ', colorSpace ); + return [ encodingMatrix, 'LinearTransferOETF' ]; + + } + +} + +function getShaderErrors( gl, shader, type ) { + + const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS ); + + const shaderInfoLog = gl.getShaderInfoLog( shader ) || ''; + const errors = shaderInfoLog.trim(); + + if ( status && errors === '' ) return ''; + + const errorMatches = /ERROR: 0:(\d+)/.exec( errors ); + if ( errorMatches ) { + + // --enable-privileged-webgl-extension + // log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) ); + + const errorLine = parseInt( errorMatches[ 1 ] ); + return type.toUpperCase() + '\n\n' + errors + '\n\n' + handleSource( gl.getShaderSource( shader ), errorLine ); + + } else { + + return errors; + + } + +} + +function getTexelEncodingFunction( functionName, colorSpace ) { + + const components = getEncodingComponents( colorSpace ); + + return [ + + `vec4 ${functionName}( vec4 value ) {`, + + ` return ${components[ 1 ]}( vec4( value.rgb * ${components[ 0 ]}, value.a ) );`, + + '}', + + ].join( '\n' ); + +} + +const toneMappingFunctions = { + [ LinearToneMapping ]: 'Linear', + [ ReinhardToneMapping ]: 'Reinhard', + [ CineonToneMapping ]: 'Cineon', + [ ACESFilmicToneMapping ]: 'ACESFilmic', + [ AgXToneMapping ]: 'AgX', + [ NeutralToneMapping ]: 'Neutral', + [ CustomToneMapping ]: 'Custom' +}; + +function getToneMappingFunction( functionName, toneMapping ) { + + const toneMappingName = toneMappingFunctions[ toneMapping ]; + + if ( toneMappingName === undefined ) { + + warn( 'WebGLProgram: Unsupported toneMapping:', toneMapping ); + return 'vec3 ' + functionName + '( vec3 color ) { return LinearToneMapping( color ); }'; + + } + + return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }'; + +} + +const _v0 = /*@__PURE__*/ new Vector3(); + +function getLuminanceFunction() { + + ColorManagement.getLuminanceCoefficients( _v0 ); + + const r = _v0.x.toFixed( 4 ); + const g = _v0.y.toFixed( 4 ); + const b = _v0.z.toFixed( 4 ); + + return [ + + 'float luminance( const in vec3 rgb ) {', + + ` const vec3 weights = vec3( ${ r }, ${ g }, ${ b } );`, + + ' return dot( weights, rgb );', + + '}' + + ].join( '\n' ); + +} + +function generateVertexExtensions( parameters ) { + + const chunks = [ + parameters.extensionClipCullDistance ? '#extension GL_ANGLE_clip_cull_distance : require' : '', + parameters.extensionMultiDraw ? '#extension GL_ANGLE_multi_draw : require' : '', + ]; + + return chunks.filter( filterEmptyLine ).join( '\n' ); + +} + +function generateDefines( defines ) { + + const chunks = []; + + for ( const name in defines ) { + + const value = defines[ name ]; + + if ( value === false ) continue; + + chunks.push( '#define ' + name + ' ' + value ); + + } + + return chunks.join( '\n' ); + +} + +function fetchAttributeLocations( gl, program ) { + + const attributes = {}; + + const n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES ); + + for ( let i = 0; i < n; i ++ ) { + + const info = gl.getActiveAttrib( program, i ); + const name = info.name; + + let locationSize = 1; + if ( info.type === gl.FLOAT_MAT2 ) locationSize = 2; + if ( info.type === gl.FLOAT_MAT3 ) locationSize = 3; + if ( info.type === gl.FLOAT_MAT4 ) locationSize = 4; + + // log( 'WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i ); + + attributes[ name ] = { + type: info.type, + location: gl.getAttribLocation( program, name ), + locationSize: locationSize + }; + + } + + return attributes; + +} + +function filterEmptyLine( string ) { + + return string !== ''; + +} + +function replaceLightNums( string, parameters ) { + + const numSpotLightCoords = parameters.numSpotLightShadows + parameters.numSpotLightMaps - parameters.numSpotLightShadowsWithMaps; + + return string + .replace( /NUM_SUN_LIGHTS/g, parameters.numSunLights ) + .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights ) + .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights ) + .replace( /NUM_SPOT_LIGHT_MAPS/g, parameters.numSpotLightMaps ) + .replace( /NUM_SPOT_LIGHT_COORDS/g, numSpotLightCoords ) + .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights ) + .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights ) + .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights ) + .replace( /NUM_SUN_LIGHT_SHADOWS/g, parameters.numSunLightShadows ) + .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows ) + .replace( /NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, parameters.numSpotLightShadowsWithMaps ) + .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows ) + .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows ); + +} + +function replaceClippingPlaneNums( string, parameters ) { + + return string + .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes ) + .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) ); + +} + +// Resolve Includes + +const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm; + +function resolveIncludes( string ) { + + return string.replace( includePattern, includeReplacer ); + +} + +const shaderChunkMap = new Map(); + +function includeReplacer( match, include ) { + + let string = ShaderChunk[ include ]; + + if ( string === undefined ) { + + const newInclude = shaderChunkMap.get( include ); + + if ( newInclude !== undefined ) { + + string = ShaderChunk[ newInclude ]; + warn( 'WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.', include, newInclude ); + + } else { + + throw new Error( 'THREE.WebGLProgram: Can not resolve #include <' + include + '>' ); + + } + + } + + return resolveIncludes( string ); + +} + +// Unroll Loops + +const unrollLoopPattern = /#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g; + +function unrollLoops( string ) { + + return string.replace( unrollLoopPattern, loopReplacer ); + +} + +function loopReplacer( match, start, end, snippet ) { + + let string = ''; + + for ( let i = parseInt( start ); i < parseInt( end ); i ++ ) { + + string += snippet + .replace( /\[\s*i\s*\]/g, '[ ' + i + ' ]' ) + .replace( /UNROLLED_LOOP_INDEX/g, i ); + + } + + return string; + +} + +// + +function generatePrecision( parameters ) { + + let precisionstring = `precision ${parameters.precision} float; + precision ${parameters.precision} int; + precision ${parameters.precision} sampler2D; + precision ${parameters.precision} samplerCube; + precision ${parameters.precision} sampler3D; + precision ${parameters.precision} sampler2DArray; + precision ${parameters.precision} sampler2DShadow; + precision ${parameters.precision} samplerCubeShadow; + precision ${parameters.precision} sampler2DArrayShadow; + precision ${parameters.precision} isampler2D; + precision ${parameters.precision} isampler3D; + precision ${parameters.precision} isamplerCube; + precision ${parameters.precision} isampler2DArray; + precision ${parameters.precision} usampler2D; + precision ${parameters.precision} usampler3D; + precision ${parameters.precision} usamplerCube; + precision ${parameters.precision} usampler2DArray; + `; + + if ( parameters.precision === 'highp' ) { + + precisionstring += '\n#define HIGH_PRECISION'; + + } else if ( parameters.precision === 'mediump' ) { + + precisionstring += '\n#define MEDIUM_PRECISION'; + + } else if ( parameters.precision === 'lowp' ) { + + precisionstring += '\n#define LOW_PRECISION'; + + } + + return precisionstring; + +} + +const shadowMapTypeDefines = { + [ PCFShadowMap ]: 'SHADOWMAP_TYPE_PCF', + [ VSMShadowMap ]: 'SHADOWMAP_TYPE_VSM' +}; + +function generateShadowMapTypeDefine( parameters ) { + + return shadowMapTypeDefines[ parameters.shadowMapType ] || 'SHADOWMAP_TYPE_BASIC'; + +} + +const envMapTypeDefines = { + [ CubeReflectionMapping ]: 'ENVMAP_TYPE_CUBE', + [ CubeRefractionMapping ]: 'ENVMAP_TYPE_CUBE', + [ CubeUVReflectionMapping ]: 'ENVMAP_TYPE_CUBE_UV' +}; + +function generateEnvMapTypeDefine( parameters ) { + + if ( parameters.envMap === false ) return 'ENVMAP_TYPE_CUBE'; + + return envMapTypeDefines[ parameters.envMapMode ] || 'ENVMAP_TYPE_CUBE'; + +} + +const envMapModeDefines = { + [ CubeRefractionMapping ]: 'ENVMAP_MODE_REFRACTION' +}; + +function generateEnvMapModeDefine( parameters ) { + + if ( parameters.envMap === false ) return 'ENVMAP_MODE_REFLECTION'; + + return envMapModeDefines[ parameters.envMapMode ] || 'ENVMAP_MODE_REFLECTION'; + +} + +const envMapBlendingDefines = { + [ MultiplyOperation ]: 'ENVMAP_BLENDING_MULTIPLY', + [ MixOperation ]: 'ENVMAP_BLENDING_MIX', + [ AddOperation ]: 'ENVMAP_BLENDING_ADD' +}; + +function generateEnvMapBlendingDefine( parameters ) { + + if ( parameters.envMap === false ) return 'ENVMAP_BLENDING_NONE'; + + return envMapBlendingDefines[ parameters.combine ] || 'ENVMAP_BLENDING_NONE'; + +} + +function generateCubeUVSize( parameters ) { + + const imageHeight = parameters.envMapCubeUVHeight; + + if ( imageHeight === null ) return null; + + const maxMip = Math.log2( imageHeight ) - 2; + + const texelHeight = 1.0 / imageHeight; + + const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) ); + + return { texelWidth, texelHeight, maxMip }; + +} + +function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) { + + // TODO Send this event to Three.js DevTools + // log( 'WebGLProgram', cacheKey ); + + const gl = renderer.getContext(); + + const defines = parameters.defines; + + let vertexShader = parameters.vertexShader; + let fragmentShader = parameters.fragmentShader; + + const shadowMapTypeDefine = generateShadowMapTypeDefine( parameters ); + const envMapTypeDefine = generateEnvMapTypeDefine( parameters ); + const envMapModeDefine = generateEnvMapModeDefine( parameters ); + const envMapBlendingDefine = generateEnvMapBlendingDefine( parameters ); + const envMapCubeUVSize = generateCubeUVSize( parameters ); + + const customVertexExtensions = generateVertexExtensions( parameters ); + + const customDefines = generateDefines( defines ); + + const program = gl.createProgram(); + + let prefixVertex, prefixFragment; + let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : ''; + + if ( parameters.isRawShaderMaterial ) { + + prefixVertex = [ + + '#define SHADER_TYPE ' + parameters.shaderType, + '#define SHADER_NAME ' + parameters.shaderName, + + customDefines + + ].filter( filterEmptyLine ).join( '\n' ); + + if ( prefixVertex.length > 0 ) { + + prefixVertex += '\n'; + + } + + prefixFragment = [ + + '#define SHADER_TYPE ' + parameters.shaderType, + '#define SHADER_NAME ' + parameters.shaderName, + + customDefines + + ].filter( filterEmptyLine ).join( '\n' ); + + if ( prefixFragment.length > 0 ) { + + prefixFragment += '\n'; + + } + + } else { + + prefixVertex = [ + + generatePrecision( parameters ), + + '#define SHADER_TYPE ' + parameters.shaderType, + '#define SHADER_NAME ' + parameters.shaderName, + + customDefines, + + parameters.extensionClipCullDistance ? '#define USE_CLIP_DISTANCE' : '', + parameters.batching ? '#define USE_BATCHING' : '', + parameters.batchingColor ? '#define USE_BATCHING_COLOR' : '', + parameters.instancing ? '#define USE_INSTANCING' : '', + parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '', + parameters.instancingMorph ? '#define USE_INSTANCING_MORPH' : '', + + parameters.useFog && parameters.fog ? '#define USE_FOG' : '', + parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '', + + parameters.map ? '#define USE_MAP' : '', + parameters.envMap ? '#define USE_ENVMAP' : '', + parameters.envMap ? '#define ' + envMapModeDefine : '', + parameters.lightMap ? '#define USE_LIGHTMAP' : '', + parameters.aoMap ? '#define USE_AOMAP' : '', + parameters.bumpMap ? '#define USE_BUMPMAP' : '', + parameters.normalMap ? '#define USE_NORMALMAP' : '', + parameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '', + parameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '', + parameters.displacementMap ? '#define USE_DISPLACEMENTMAP' : '', + parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', + + parameters.anisotropy ? '#define USE_ANISOTROPY' : '', + parameters.anisotropyMap ? '#define USE_ANISOTROPYMAP' : '', + + parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', + parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', + parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', + + parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '', + parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '', + + parameters.specularMap ? '#define USE_SPECULARMAP' : '', + parameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '', + parameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '', + + parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', + parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', + parameters.alphaMap ? '#define USE_ALPHAMAP' : '', + parameters.alphaHash ? '#define USE_ALPHAHASH' : '', + + parameters.transmission ? '#define USE_TRANSMISSION' : '', + parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '', + parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '', + + parameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '', + parameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '', + + // + + parameters.mapUv ? '#define MAP_UV ' + parameters.mapUv : '', + parameters.alphaMapUv ? '#define ALPHAMAP_UV ' + parameters.alphaMapUv : '', + parameters.lightMapUv ? '#define LIGHTMAP_UV ' + parameters.lightMapUv : '', + parameters.aoMapUv ? '#define AOMAP_UV ' + parameters.aoMapUv : '', + parameters.emissiveMapUv ? '#define EMISSIVEMAP_UV ' + parameters.emissiveMapUv : '', + parameters.bumpMapUv ? '#define BUMPMAP_UV ' + parameters.bumpMapUv : '', + parameters.normalMapUv ? '#define NORMALMAP_UV ' + parameters.normalMapUv : '', + parameters.displacementMapUv ? '#define DISPLACEMENTMAP_UV ' + parameters.displacementMapUv : '', + + parameters.metalnessMapUv ? '#define METALNESSMAP_UV ' + parameters.metalnessMapUv : '', + parameters.roughnessMapUv ? '#define ROUGHNESSMAP_UV ' + parameters.roughnessMapUv : '', + + parameters.anisotropyMapUv ? '#define ANISOTROPYMAP_UV ' + parameters.anisotropyMapUv : '', + + parameters.clearcoatMapUv ? '#define CLEARCOATMAP_UV ' + parameters.clearcoatMapUv : '', + parameters.clearcoatNormalMapUv ? '#define CLEARCOAT_NORMALMAP_UV ' + parameters.clearcoatNormalMapUv : '', + parameters.clearcoatRoughnessMapUv ? '#define CLEARCOAT_ROUGHNESSMAP_UV ' + parameters.clearcoatRoughnessMapUv : '', + + parameters.iridescenceMapUv ? '#define IRIDESCENCEMAP_UV ' + parameters.iridescenceMapUv : '', + parameters.iridescenceThicknessMapUv ? '#define IRIDESCENCE_THICKNESSMAP_UV ' + parameters.iridescenceThicknessMapUv : '', + + parameters.sheenColorMapUv ? '#define SHEEN_COLORMAP_UV ' + parameters.sheenColorMapUv : '', + parameters.sheenRoughnessMapUv ? '#define SHEEN_ROUGHNESSMAP_UV ' + parameters.sheenRoughnessMapUv : '', + + parameters.specularMapUv ? '#define SPECULARMAP_UV ' + parameters.specularMapUv : '', + parameters.specularColorMapUv ? '#define SPECULAR_COLORMAP_UV ' + parameters.specularColorMapUv : '', + parameters.specularIntensityMapUv ? '#define SPECULAR_INTENSITYMAP_UV ' + parameters.specularIntensityMapUv : '', + + parameters.transmissionMapUv ? '#define TRANSMISSIONMAP_UV ' + parameters.transmissionMapUv : '', + parameters.thicknessMapUv ? '#define THICKNESSMAP_UV ' + parameters.thicknessMapUv : '', + + // + + parameters.vertexTangents && parameters.flatShading === false ? '#define USE_TANGENT' : '', + parameters.vertexNormals ? '#define HAS_NORMAL' : '', + parameters.vertexColors ? '#define USE_COLOR' : '', + parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '', + parameters.vertexUv1s ? '#define USE_UV1' : '', + parameters.vertexUv2s ? '#define USE_UV2' : '', + parameters.vertexUv3s ? '#define USE_UV3' : '', + + parameters.pointsUvs ? '#define USE_POINTS_UV' : '', + + parameters.flatShading ? '#define FLAT_SHADED' : '', + + parameters.skinning ? '#define USE_SKINNING' : '', + + parameters.morphTargets ? '#define USE_MORPHTARGETS' : '', + parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '', + ( parameters.morphColors ) ? '#define USE_MORPHCOLORS' : '', + ( parameters.morphTargetsCount > 0 ) ? '#define MORPHTARGETS_TEXTURE_STRIDE ' + parameters.morphTextureStride : '', + ( parameters.morphTargetsCount > 0 ) ? '#define MORPHTARGETS_COUNT ' + parameters.morphTargetsCount : '', + parameters.doubleSided ? '#define DOUBLE_SIDED' : '', + parameters.flipSided ? '#define FLIP_SIDED' : '', + + parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', + parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', + + parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '', + + parameters.numLightProbes > 0 ? '#define USE_LIGHT_PROBES' : '', + + parameters.logarithmicDepthBuffer ? '#define USE_LOGARITHMIC_DEPTH_BUFFER' : '', + parameters.reversedDepthBuffer ? '#define USE_REVERSED_DEPTH_BUFFER' : '', + + 'uniform mat4 modelMatrix;', + 'uniform mat4 modelViewMatrix;', + 'uniform mat4 projectionMatrix;', + 'uniform mat4 viewMatrix;', + 'uniform mat3 normalMatrix;', + 'uniform vec3 cameraPosition;', + 'uniform bool isOrthographic;', + + '#ifdef USE_INSTANCING', + + ' attribute mat4 instanceMatrix;', + + '#endif', + + '#ifdef USE_INSTANCING_COLOR', + + ' attribute vec3 instanceColor;', + + '#endif', + + '#ifdef USE_INSTANCING_MORPH', + + ' uniform sampler2D morphTexture;', + + '#endif', + + 'attribute vec3 position;', + 'attribute vec3 normal;', + 'attribute vec2 uv;', + + '#ifdef USE_UV1', + + ' attribute vec2 uv1;', + + '#endif', + + '#ifdef USE_UV2', + + ' attribute vec2 uv2;', + + '#endif', + + '#ifdef USE_UV3', + + ' attribute vec2 uv3;', + + '#endif', + + '#ifdef USE_TANGENT', + + ' attribute vec4 tangent;', + + '#endif', + + '#if defined( USE_COLOR_ALPHA )', + + ' attribute vec4 color;', + + '#elif defined( USE_COLOR )', + + ' attribute vec3 color;', + + '#endif', + + '#ifdef USE_SKINNING', + + ' attribute vec4 skinIndex;', + ' attribute vec4 skinWeight;', + + '#endif', + + '\n' + + ].filter( filterEmptyLine ).join( '\n' ); + + prefixFragment = [ + + generatePrecision( parameters ), + + '#define SHADER_TYPE ' + parameters.shaderType, + '#define SHADER_NAME ' + parameters.shaderName, + + customDefines, + + parameters.useFog && parameters.fog ? '#define USE_FOG' : '', + parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '', + + parameters.alphaToCoverage ? '#define ALPHA_TO_COVERAGE' : '', + parameters.map ? '#define USE_MAP' : '', + parameters.matcap ? '#define USE_MATCAP' : '', + parameters.envMap ? '#define USE_ENVMAP' : '', + parameters.envMap ? '#define ' + envMapTypeDefine : '', + parameters.envMap ? '#define ' + envMapModeDefine : '', + parameters.envMap ? '#define ' + envMapBlendingDefine : '', + envMapCubeUVSize ? '#define CUBEUV_TEXEL_WIDTH ' + envMapCubeUVSize.texelWidth : '', + envMapCubeUVSize ? '#define CUBEUV_TEXEL_HEIGHT ' + envMapCubeUVSize.texelHeight : '', + envMapCubeUVSize ? '#define CUBEUV_MAX_MIP ' + envMapCubeUVSize.maxMip + '.0' : '', + parameters.lightMap ? '#define USE_LIGHTMAP' : '', + parameters.aoMap ? '#define USE_AOMAP' : '', + parameters.bumpMap ? '#define USE_BUMPMAP' : '', + parameters.normalMap ? '#define USE_NORMALMAP' : '', + parameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '', + parameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '', + parameters.packedNormalMap ? '#define USE_PACKED_NORMALMAP' : '', + parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', + + parameters.anisotropy ? '#define USE_ANISOTROPY' : '', + parameters.anisotropyMap ? '#define USE_ANISOTROPYMAP' : '', + + parameters.clearcoat ? '#define USE_CLEARCOAT' : '', + parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', + parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', + parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', + + parameters.dispersion ? '#define USE_DISPERSION' : '', + parameters.retroreflection ? '#define USE_RETROREFLECTION' : '', + + parameters.iridescence ? '#define USE_IRIDESCENCE' : '', + parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '', + parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '', + + parameters.specularMap ? '#define USE_SPECULARMAP' : '', + parameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '', + parameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '', + + parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', + parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', + + parameters.alphaMap ? '#define USE_ALPHAMAP' : '', + parameters.alphaTest ? '#define USE_ALPHATEST' : '', + parameters.alphaHash ? '#define USE_ALPHAHASH' : '', + + parameters.sheen ? '#define USE_SHEEN' : '', + parameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '', + parameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '', + + parameters.transmission ? '#define USE_TRANSMISSION' : '', + parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '', + parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '', + + parameters.vertexTangents && parameters.flatShading === false ? '#define USE_TANGENT' : '', + parameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '', + parameters.vertexAlphas || parameters.batchingColor ? '#define USE_COLOR_ALPHA' : '', + parameters.vertexUv1s ? '#define USE_UV1' : '', + parameters.vertexUv2s ? '#define USE_UV2' : '', + parameters.vertexUv3s ? '#define USE_UV3' : '', + + parameters.pointsUvs ? '#define USE_POINTS_UV' : '', + + parameters.gradientMap ? '#define USE_GRADIENTMAP' : '', + + parameters.flatShading ? '#define FLAT_SHADED' : '', + + parameters.doubleSided ? '#define DOUBLE_SIDED' : '', + parameters.flipSided ? '#define FLIP_SIDED' : '', + + parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', + parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', + + parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '', + + parameters.numLightProbes > 0 ? '#define USE_LIGHT_PROBES' : '', + + parameters.numLightProbeGrids > 0 ? '#define USE_LIGHT_PROBES_GRID' : '', + + parameters.decodeVideoTexture ? '#define DECODE_VIDEO_TEXTURE' : '', + parameters.decodeVideoTextureEmissive ? '#define DECODE_VIDEO_TEXTURE_EMISSIVE' : '', + + parameters.logarithmicDepthBuffer ? '#define USE_LOGARITHMIC_DEPTH_BUFFER' : '', + parameters.reversedDepthBuffer ? '#define USE_REVERSED_DEPTH_BUFFER' : '', + + 'uniform mat4 viewMatrix;', + 'uniform vec3 cameraPosition;', + 'uniform bool isOrthographic;', + + ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '', + ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below + ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '', + + parameters.dithering ? '#define DITHERING' : '', + parameters.opaque ? '#define OPAQUE' : '', + + ShaderChunk[ 'colorspace_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below + getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputColorSpace ), + getLuminanceFunction(), + + parameters.useDepthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '', + + '\n' + + ].filter( filterEmptyLine ).join( '\n' ); + + } + + vertexShader = resolveIncludes( vertexShader ); + vertexShader = replaceLightNums( vertexShader, parameters ); + vertexShader = replaceClippingPlaneNums( vertexShader, parameters ); + + fragmentShader = resolveIncludes( fragmentShader ); + fragmentShader = replaceLightNums( fragmentShader, parameters ); + fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters ); + + vertexShader = unrollLoops( vertexShader ); + fragmentShader = unrollLoops( fragmentShader ); + + if ( parameters.isRawShaderMaterial !== true ) { + + // GLSL 3.0 conversion for built-in materials and ShaderMaterial + + versionString = '#version 300 es\n'; + + prefixVertex = [ + customVertexExtensions, + '#define attribute in', + '#define varying out', + '#define texture2D texture' + ].join( '\n' ) + '\n' + prefixVertex; + + prefixFragment = [ + '#define varying in', + ( parameters.glslVersion === GLSL3 ) ? '' : 'layout(location = 0) out highp vec4 pc_fragColor;', + ( parameters.glslVersion === GLSL3 ) ? '' : '#define gl_FragColor pc_fragColor', + '#define gl_FragDepthEXT gl_FragDepth', + '#define texture2D texture', + '#define textureCube texture', + '#define texture2DProj textureProj', + '#define texture2DLodEXT textureLod', + '#define texture2DProjLodEXT textureProjLod', + '#define textureCubeLodEXT textureLod', + '#define texture2DGradEXT textureGrad', + '#define texture2DProjGradEXT textureProjGrad', + '#define textureCubeGradEXT textureGrad' + ].join( '\n' ) + '\n' + prefixFragment; + + } + + const vertexGlsl = versionString + prefixVertex + vertexShader; + const fragmentGlsl = versionString + prefixFragment + fragmentShader; + + // log( '*VERTEX*', vertexGlsl ); + // log( '*FRAGMENT*', fragmentGlsl ); + + const glVertexShader = WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl ); + const glFragmentShader = WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl ); + + gl.attachShader( program, glVertexShader ); + gl.attachShader( program, glFragmentShader ); + + // Force a particular attribute to index 0. + + if ( parameters.index0AttributeName !== undefined ) { + + gl.bindAttribLocation( program, 0, parameters.index0AttributeName ); + + } else if ( parameters.hasPositionAttribute === true ) { + + // below avoids the "Attribute 0 is disabled" performance penalty + + gl.bindAttribLocation( program, 0, 'position' ); + + } + + gl.linkProgram( program ); + + function onFirstUse( self ) { + + // check for link errors + if ( renderer.debug.checkShaderErrors ) { + + const programInfoLog = gl.getProgramInfoLog( program ) || ''; + const vertexShaderInfoLog = gl.getShaderInfoLog( glVertexShader ) || ''; + const fragmentShaderInfoLog = gl.getShaderInfoLog( glFragmentShader ) || ''; + + const programLog = programInfoLog.trim(); + const vertexLog = vertexShaderInfoLog.trim(); + const fragmentLog = fragmentShaderInfoLog.trim(); + + let runnable = true; + let haveDiagnostics = true; + + if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) { + + runnable = false; + + if ( typeof renderer.debug.onShaderError === 'function' ) { + + renderer.debug.onShaderError( gl, program, glVertexShader, glFragmentShader ); + + } else { + + // default error reporting + + const vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' ); + const fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' ); + + error( + 'WebGLProgram: Shader Error ' + gl.getError() + ' - ' + + 'VALIDATE_STATUS ' + gl.getProgramParameter( program, gl.VALIDATE_STATUS ) + '\n\n' + + 'Material Name: ' + self.name + '\n' + + 'Material Type: ' + self.type + '\n\n' + + 'Program Info Log: ' + programLog + '\n' + + vertexErrors + '\n' + + fragmentErrors + ); + + } + + } else if ( programLog !== '' ) { + + warn( 'WebGLProgram: Program Info Log:', programLog ); + + } else if ( vertexLog === '' || fragmentLog === '' ) { + + haveDiagnostics = false; + + } + + if ( haveDiagnostics ) { + + self.diagnostics = { + + runnable: runnable, + + programLog: programLog, + + vertexShader: { + + log: vertexLog, + prefix: prefixVertex + + }, + + fragmentShader: { + + log: fragmentLog, + prefix: prefixFragment + + } + + }; + + } + + } + + // Clean up + + // Crashes in iOS9 and iOS10. #18402 + // gl.detachShader( program, glVertexShader ); + // gl.detachShader( program, glFragmentShader ); + + gl.deleteShader( glVertexShader ); + gl.deleteShader( glFragmentShader ); + + cachedUniforms = new WebGLUniforms( gl, program ); + cachedAttributes = fetchAttributeLocations( gl, program ); + + } + + // set up caching for uniform locations + + let cachedUniforms; + + this.getUniforms = function () { + + if ( cachedUniforms === undefined ) { + + // Populates cachedUniforms and cachedAttributes + onFirstUse( this ); + + } + + return cachedUniforms; + + }; + + // set up caching for attribute locations + + let cachedAttributes; + + this.getAttributes = function () { + + if ( cachedAttributes === undefined ) { + + // Populates cachedAttributes and cachedUniforms + onFirstUse( this ); + + } + + return cachedAttributes; + + }; + + // indicate when the program is ready to be used. if the KHR_parallel_shader_compile extension isn't supported, + // flag the program as ready immediately. It may cause a stall when it's first used. + + let programReady = ( parameters.rendererExtensionParallelShaderCompile === false ); + + this.isReady = function () { + + if ( programReady === false ) { + + programReady = gl.getProgramParameter( program, COMPLETION_STATUS_KHR ); + + } + + return programReady; + + }; + + // free resource + + this.destroy = function () { + + bindingStates.releaseStatesOfProgram( this ); + + gl.deleteProgram( program ); + this.program = undefined; + + }; + + // + + this.type = parameters.shaderType; + this.name = parameters.shaderName; + this.id = programIdCount ++; + this.cacheKey = cacheKey; + this.usedTimes = 1; + this.program = program; + this.vertexShader = glVertexShader; + this.fragmentShader = glFragmentShader; + + return this; + +} + +let _id = 0; + +class WebGLShaderCache { + + constructor() { + + this.shaderCache = new Map(); + this.materialCache = new Map(); + + } + + update( material, vertexShaderStage, fragmentShaderStage ) { + + const materialShaders = this._getShaderCacheForMaterial( material ); + + if ( materialShaders.has( vertexShaderStage ) === false ) { + + materialShaders.add( vertexShaderStage ); + vertexShaderStage.usedTimes ++; + + } + + if ( materialShaders.has( fragmentShaderStage ) === false ) { + + materialShaders.add( fragmentShaderStage ); + fragmentShaderStage.usedTimes ++; + + } + + return this; + + } + + remove( material ) { + + const materialShaders = this.materialCache.get( material ); + + for ( const shaderStage of materialShaders ) { + + shaderStage.usedTimes --; + + if ( shaderStage.usedTimes === 0 ) this.shaderCache.delete( shaderStage.code ); + + } + + this.materialCache.delete( material ); + + return this; + + } + + getVertexShaderStage( material ) { + + return this._getShaderStage( material.vertexShader ); + + } + + getFragmentShaderStage( material ) { + + return this._getShaderStage( material.fragmentShader ); + + } + + dispose() { + + this.shaderCache.clear(); + this.materialCache.clear(); + + } + + _getShaderCacheForMaterial( material ) { + + const cache = this.materialCache; + let set = cache.get( material ); + + if ( set === undefined ) { + + set = new Set(); + cache.set( material, set ); + + } + + return set; + + } + + _getShaderStage( code ) { + + const cache = this.shaderCache; + let stage = cache.get( code ); + + if ( stage === undefined ) { + + stage = new WebGLShaderStage( code ); + cache.set( code, stage ); + + } + + return stage; + + } + +} + +class WebGLShaderStage { + + constructor( code ) { + + this.id = _id ++; + + this.code = code; + this.usedTimes = 0; + + } + +} + +function isPackedRGFormat( format ) { + + return format === RGFormat || format === RG11_EAC_Format || format === RED_GREEN_RGTC2_Format; + +} + +function WebGLPrograms( renderer, environments, extensions, capabilities, bindingStates, clipping ) { + + const _programLayers = new Layers(); + const _customShaders = new WebGLShaderCache(); + const _activeChannels = new Set(); + const programs = []; + const programsMap = new Map(); + + const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer; + + let precision = capabilities.precision; + + const shaderIDs = { + MeshDepthMaterial: 'depth', + MeshDistanceMaterial: 'distance', + MeshNormalMaterial: 'normal', + MeshBasicMaterial: 'basic', + MeshLambertMaterial: 'lambert', + MeshPhongMaterial: 'phong', + MeshToonMaterial: 'toon', + MeshStandardMaterial: 'physical', + MeshPhysicalMaterial: 'physical', + MeshMatcapMaterial: 'matcap', + LineBasicMaterial: 'basic', + LineDashedMaterial: 'dashed', + PointsMaterial: 'points', + ShadowMaterial: 'shadow', + SpriteMaterial: 'sprite' + }; + + function getChannel( value ) { + + _activeChannels.add( value ); + + if ( value === 0 ) return 'uv'; + + return `uv${ value }`; + + } + + function getParameters( material, lights, shadows, scene, object, lightProbeGrids ) { + + const fog = scene.fog; + const geometry = object.geometry; + const environment = ( material.isMeshStandardMaterial || material.isMeshLambertMaterial || material.isMeshPhongMaterial ) ? scene.environment : null; + + const usePMREM = material.isMeshStandardMaterial || ( material.isMeshLambertMaterial && ! material.envMap ) || ( material.isMeshPhongMaterial && ! material.envMap ); + const envMap = environments.get( material.envMap || environment, usePMREM ); + const envMapCubeUVHeight = ( !! envMap ) && ( envMap.mapping === CubeUVReflectionMapping ) ? envMap.image.height : null; + + const shaderID = shaderIDs[ material.type ]; + + // heuristics to create shader parameters according to lights in the scene + // (not to blow over maxLights budget) + + if ( material.precision !== null ) { + + precision = capabilities.getMaxPrecision( material.precision ); + + if ( precision !== material.precision ) { + + warn( 'WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' ); + + } + + } + + // + + const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color; + const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0; + + let morphTextureStride = 0; + + if ( geometry.morphAttributes.position !== undefined ) morphTextureStride = 1; + if ( geometry.morphAttributes.normal !== undefined ) morphTextureStride = 2; + if ( geometry.morphAttributes.color !== undefined ) morphTextureStride = 3; + + // + + let vertexShader, fragmentShader; + let customVertexShaderID, customFragmentShaderID; + + if ( shaderID ) { + + const shader = ShaderLib[ shaderID ]; + + vertexShader = shader.vertexShader; + fragmentShader = shader.fragmentShader; + + } else { + + vertexShader = material.vertexShader; + fragmentShader = material.fragmentShader; + + const vertexShaderStage = _customShaders.getVertexShaderStage( material ); + const fragmentShaderStage = _customShaders.getFragmentShaderStage( material ); + + _customShaders.update( material, vertexShaderStage, fragmentShaderStage ); + + customVertexShaderID = vertexShaderStage.id; + customFragmentShaderID = fragmentShaderStage.id; + + } + + const currentRenderTarget = renderer.getRenderTarget(); + const reversedDepthBuffer = renderer.state.buffers.depth.getReversed(); + + const IS_INSTANCEDMESH = object.isInstancedMesh === true; + const IS_BATCHEDMESH = object.isBatchedMesh === true; + + const HAS_MAP = !! material.map; + const HAS_MATCAP = !! material.matcap; + const HAS_ENVMAP = !! envMap; + const HAS_AOMAP = !! material.aoMap; + const HAS_LIGHTMAP = !! material.lightMap; + const HAS_BUMPMAP = !! material.bumpMap && material.wireframe === false; + const HAS_NORMALMAP = !! material.normalMap; + const HAS_DISPLACEMENTMAP = !! material.displacementMap; + const HAS_EMISSIVEMAP = !! material.emissiveMap; + + const HAS_METALNESSMAP = !! material.metalnessMap; + const HAS_ROUGHNESSMAP = !! material.roughnessMap; + + const HAS_ANISOTROPY = material.anisotropy > 0; + const HAS_CLEARCOAT = material.clearcoat > 0; + const HAS_DISPERSION = material.dispersion > 0; + const HAS_RETROREFLECTION = material.retroreflectivity > 0; + const HAS_IRIDESCENCE = material.iridescence > 0; + const HAS_SHEEN = material.sheen > 0; + const HAS_TRANSMISSION = material.transmission > 0; + + const HAS_ANISOTROPYMAP = HAS_ANISOTROPY && !! material.anisotropyMap; + + const HAS_CLEARCOATMAP = HAS_CLEARCOAT && !! material.clearcoatMap; + const HAS_CLEARCOAT_NORMALMAP = HAS_CLEARCOAT && !! material.clearcoatNormalMap; + const HAS_CLEARCOAT_ROUGHNESSMAP = HAS_CLEARCOAT && !! material.clearcoatRoughnessMap; + + const HAS_IRIDESCENCEMAP = HAS_IRIDESCENCE && !! material.iridescenceMap; + const HAS_IRIDESCENCE_THICKNESSMAP = HAS_IRIDESCENCE && !! material.iridescenceThicknessMap; + + const HAS_SHEEN_COLORMAP = HAS_SHEEN && !! material.sheenColorMap; + const HAS_SHEEN_ROUGHNESSMAP = HAS_SHEEN && !! material.sheenRoughnessMap; + + const HAS_SPECULARMAP = !! material.specularMap; + const HAS_SPECULAR_COLORMAP = !! material.specularColorMap; + const HAS_SPECULAR_INTENSITYMAP = !! material.specularIntensityMap; + + const HAS_TRANSMISSIONMAP = HAS_TRANSMISSION && !! material.transmissionMap; + const HAS_THICKNESSMAP = HAS_TRANSMISSION && !! material.thicknessMap; + + const HAS_GRADIENTMAP = !! material.gradientMap; + + const HAS_ALPHAMAP = !! material.alphaMap; + + const HAS_ALPHATEST = material.alphaTest > 0; + + const HAS_ALPHAHASH = !! material.alphaHash; + + const HAS_EXTENSIONS = !! material.extensions; + + let toneMapping = NoToneMapping; + + if ( material.toneMapped ) { + + if ( currentRenderTarget === null || currentRenderTarget.isXRRenderTarget === true ) { + + toneMapping = renderer.toneMapping; + + } + + } + + const parameters = { + + shaderID: shaderID, + shaderType: material.type, + shaderName: material.name, + + vertexShader: vertexShader, + fragmentShader: fragmentShader, + defines: material.defines, + + customVertexShaderID: customVertexShaderID, + customFragmentShaderID: customFragmentShaderID, + + isRawShaderMaterial: material.isRawShaderMaterial === true, + glslVersion: material.glslVersion, + + precision: precision, + + batching: IS_BATCHEDMESH, + batchingColor: IS_BATCHEDMESH && object._colorsTexture !== null, + instancing: IS_INSTANCEDMESH, + instancingColor: IS_INSTANCEDMESH && object.instanceColor !== null, + instancingMorph: IS_INSTANCEDMESH && object.morphTexture !== null, + + outputColorSpace: ( currentRenderTarget === null ) ? renderer.outputColorSpace : ( currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.colorSpace : ColorManagement.workingColorSpace ), + alphaToCoverage: !! material.alphaToCoverage, + + map: HAS_MAP, + matcap: HAS_MATCAP, + envMap: HAS_ENVMAP, + envMapMode: HAS_ENVMAP && envMap.mapping, + envMapCubeUVHeight: envMapCubeUVHeight, + aoMap: HAS_AOMAP, + lightMap: HAS_LIGHTMAP, + bumpMap: HAS_BUMPMAP, + normalMap: HAS_NORMALMAP, + displacementMap: HAS_DISPLACEMENTMAP, + emissiveMap: HAS_EMISSIVEMAP, + + normalMapObjectSpace: HAS_NORMALMAP && material.normalMapType === ObjectSpaceNormalMap, + normalMapTangentSpace: HAS_NORMALMAP && material.normalMapType === TangentSpaceNormalMap, + packedNormalMap: HAS_NORMALMAP && material.normalMapType === TangentSpaceNormalMap && isPackedRGFormat( material.normalMap.format ), + + metalnessMap: HAS_METALNESSMAP, + roughnessMap: HAS_ROUGHNESSMAP, + + anisotropy: HAS_ANISOTROPY, + anisotropyMap: HAS_ANISOTROPYMAP, + + clearcoat: HAS_CLEARCOAT, + clearcoatMap: HAS_CLEARCOATMAP, + clearcoatNormalMap: HAS_CLEARCOAT_NORMALMAP, + clearcoatRoughnessMap: HAS_CLEARCOAT_ROUGHNESSMAP, + + dispersion: HAS_DISPERSION, + retroreflection: HAS_RETROREFLECTION, + + iridescence: HAS_IRIDESCENCE, + iridescenceMap: HAS_IRIDESCENCEMAP, + iridescenceThicknessMap: HAS_IRIDESCENCE_THICKNESSMAP, + + sheen: HAS_SHEEN, + sheenColorMap: HAS_SHEEN_COLORMAP, + sheenRoughnessMap: HAS_SHEEN_ROUGHNESSMAP, + + specularMap: HAS_SPECULARMAP, + specularColorMap: HAS_SPECULAR_COLORMAP, + specularIntensityMap: HAS_SPECULAR_INTENSITYMAP, + + transmission: HAS_TRANSMISSION, + transmissionMap: HAS_TRANSMISSIONMAP, + thicknessMap: HAS_THICKNESSMAP, + + gradientMap: HAS_GRADIENTMAP, + + opaque: material.transparent === false && material.blending === NormalBlending && material.alphaToCoverage === false, + + alphaMap: HAS_ALPHAMAP, + alphaTest: HAS_ALPHATEST, + alphaHash: HAS_ALPHAHASH, + + combine: material.combine, + + // + + mapUv: HAS_MAP && getChannel( material.map.channel ), + aoMapUv: HAS_AOMAP && getChannel( material.aoMap.channel ), + lightMapUv: HAS_LIGHTMAP && getChannel( material.lightMap.channel ), + bumpMapUv: HAS_BUMPMAP && getChannel( material.bumpMap.channel ), + normalMapUv: HAS_NORMALMAP && getChannel( material.normalMap.channel ), + displacementMapUv: HAS_DISPLACEMENTMAP && getChannel( material.displacementMap.channel ), + emissiveMapUv: HAS_EMISSIVEMAP && getChannel( material.emissiveMap.channel ), + + metalnessMapUv: HAS_METALNESSMAP && getChannel( material.metalnessMap.channel ), + roughnessMapUv: HAS_ROUGHNESSMAP && getChannel( material.roughnessMap.channel ), + + anisotropyMapUv: HAS_ANISOTROPYMAP && getChannel( material.anisotropyMap.channel ), + + clearcoatMapUv: HAS_CLEARCOATMAP && getChannel( material.clearcoatMap.channel ), + clearcoatNormalMapUv: HAS_CLEARCOAT_NORMALMAP && getChannel( material.clearcoatNormalMap.channel ), + clearcoatRoughnessMapUv: HAS_CLEARCOAT_ROUGHNESSMAP && getChannel( material.clearcoatRoughnessMap.channel ), + + iridescenceMapUv: HAS_IRIDESCENCEMAP && getChannel( material.iridescenceMap.channel ), + iridescenceThicknessMapUv: HAS_IRIDESCENCE_THICKNESSMAP && getChannel( material.iridescenceThicknessMap.channel ), + + sheenColorMapUv: HAS_SHEEN_COLORMAP && getChannel( material.sheenColorMap.channel ), + sheenRoughnessMapUv: HAS_SHEEN_ROUGHNESSMAP && getChannel( material.sheenRoughnessMap.channel ), + + specularMapUv: HAS_SPECULARMAP && getChannel( material.specularMap.channel ), + specularColorMapUv: HAS_SPECULAR_COLORMAP && getChannel( material.specularColorMap.channel ), + specularIntensityMapUv: HAS_SPECULAR_INTENSITYMAP && getChannel( material.specularIntensityMap.channel ), + + transmissionMapUv: HAS_TRANSMISSIONMAP && getChannel( material.transmissionMap.channel ), + thicknessMapUv: HAS_THICKNESSMAP && getChannel( material.thicknessMap.channel ), + + alphaMapUv: HAS_ALPHAMAP && getChannel( material.alphaMap.channel ), + + // + + vertexTangents: !! geometry.attributes.tangent && ( HAS_NORMALMAP || HAS_ANISOTROPY ), + vertexNormals: !! geometry.attributes.normal, + vertexColors: material.vertexColors, + vertexAlphas: material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4, + + pointsUvs: object.isPoints === true && !! geometry.attributes.uv && ( HAS_MAP || HAS_ALPHAMAP ), + + fog: !! fog, + useFog: material.fog === true, + fogExp2: ( !! fog && fog.isFogExp2 ), + + flatShading: material.wireframe === false && ( + material.flatShading === true || + ( geometry.attributes.normal === undefined && HAS_NORMALMAP === false && + ( material.isMeshLambertMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial || material.isMeshPhysicalMaterial ) + ) + ), + + sizeAttenuation: material.sizeAttenuation === true, + logarithmicDepthBuffer: logarithmicDepthBuffer, + reversedDepthBuffer: reversedDepthBuffer, + + skinning: object.isSkinnedMesh === true, + + hasPositionAttribute: geometry.attributes.position !== undefined, + + morphTargets: geometry.morphAttributes.position !== undefined, + morphNormals: geometry.morphAttributes.normal !== undefined, + morphColors: geometry.morphAttributes.color !== undefined, + morphTargetsCount: morphTargetsCount, + morphTextureStride: morphTextureStride, + + numSunLights: lights.sun.length, + numDirLights: lights.directional.length, + numPointLights: lights.point.length, + numSpotLights: lights.spot.length, + numSpotLightMaps: lights.spotLightMap.length, + numRectAreaLights: lights.rectArea.length, + numHemiLights: lights.hemi.length, + + numSunLightShadows: lights.sunShadowMap.length, + numDirLightShadows: lights.directionalShadowMap.length, + numPointLightShadows: lights.pointShadowMap.length, + numSpotLightShadows: lights.spotShadowMap.length, + numSpotLightShadowsWithMaps: lights.numSpotLightShadowsWithMaps, + + numLightProbes: lights.numLightProbes, + + numLightProbeGrids: lightProbeGrids.length, + + numClippingPlanes: clipping.numPlanes, + numClipIntersection: clipping.numIntersection, + + dithering: material.dithering, + + shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0, + shadowMapType: renderer.shadowMap.type, + + toneMapping: toneMapping, + + decodeVideoTexture: HAS_MAP && ( material.map.isVideoTexture === true ) && ( ColorManagement.getTransfer( material.map.colorSpace ) === SRGBTransfer ), + decodeVideoTextureEmissive: HAS_EMISSIVEMAP && ( material.emissiveMap.isVideoTexture === true ) && ( ColorManagement.getTransfer( material.emissiveMap.colorSpace ) === SRGBTransfer ), + + premultipliedAlpha: material.premultipliedAlpha, + + doubleSided: material.side === DoubleSide, + flipSided: material.side === BackSide, + + useDepthPacking: material.depthPacking >= 0, + depthPacking: material.depthPacking || 0, + + index0AttributeName: material.index0AttributeName, + + extensionClipCullDistance: HAS_EXTENSIONS && material.extensions.clipCullDistance === true && extensions.has( 'WEBGL_clip_cull_distance' ), + extensionMultiDraw: ( HAS_EXTENSIONS && material.extensions.multiDraw === true || IS_BATCHEDMESH ) && extensions.has( 'WEBGL_multi_draw' ), + + rendererExtensionParallelShaderCompile: extensions.has( 'KHR_parallel_shader_compile' ), + + customProgramCacheKey: material.customProgramCacheKey() + + }; + + // the usage of getChannel() determines the active texture channels for this shader + + parameters.vertexUv1s = _activeChannels.has( 1 ); + parameters.vertexUv2s = _activeChannels.has( 2 ); + parameters.vertexUv3s = _activeChannels.has( 3 ); + + _activeChannels.clear(); + + return parameters; + + } + + function getProgramCacheKey( parameters ) { + + const array = []; + + if ( parameters.shaderID ) { + + array.push( parameters.shaderID ); + + } else { + + array.push( parameters.customVertexShaderID ); + array.push( parameters.customFragmentShaderID ); + + } + + if ( parameters.defines !== undefined ) { + + for ( const name in parameters.defines ) { + + array.push( name ); + array.push( parameters.defines[ name ] ); + + } + + } + + if ( parameters.isRawShaderMaterial === false ) { + + getProgramCacheKeyParameters( array, parameters ); + getProgramCacheKeyBooleans( array, parameters ); + array.push( renderer.outputColorSpace ); + + } + + array.push( parameters.customProgramCacheKey ); + + return array.join(); + + } + + function getProgramCacheKeyParameters( array, parameters ) { + + array.push( parameters.precision ); + array.push( parameters.outputColorSpace ); + array.push( parameters.envMapMode ); + array.push( parameters.envMapCubeUVHeight ); + array.push( parameters.mapUv ); + array.push( parameters.alphaMapUv ); + array.push( parameters.lightMapUv ); + array.push( parameters.aoMapUv ); + array.push( parameters.bumpMapUv ); + array.push( parameters.normalMapUv ); + array.push( parameters.displacementMapUv ); + array.push( parameters.emissiveMapUv ); + array.push( parameters.metalnessMapUv ); + array.push( parameters.roughnessMapUv ); + array.push( parameters.anisotropyMapUv ); + array.push( parameters.clearcoatMapUv ); + array.push( parameters.clearcoatNormalMapUv ); + array.push( parameters.clearcoatRoughnessMapUv ); + array.push( parameters.iridescenceMapUv ); + array.push( parameters.iridescenceThicknessMapUv ); + array.push( parameters.sheenColorMapUv ); + array.push( parameters.sheenRoughnessMapUv ); + array.push( parameters.specularMapUv ); + array.push( parameters.specularColorMapUv ); + array.push( parameters.specularIntensityMapUv ); + array.push( parameters.transmissionMapUv ); + array.push( parameters.thicknessMapUv ); + array.push( parameters.combine ); + array.push( parameters.fogExp2 ); + array.push( parameters.sizeAttenuation ); + array.push( parameters.morphTargetsCount ); + array.push( parameters.morphAttributeCount ); + array.push( parameters.numSunLights ); + array.push( parameters.numDirLights ); + array.push( parameters.numPointLights ); + array.push( parameters.numSpotLights ); + array.push( parameters.numSpotLightMaps ); + array.push( parameters.numHemiLights ); + array.push( parameters.numRectAreaLights ); + array.push( parameters.numSunLightShadows ); + array.push( parameters.numDirLightShadows ); + array.push( parameters.numPointLightShadows ); + array.push( parameters.numSpotLightShadows ); + array.push( parameters.numSpotLightShadowsWithMaps ); + array.push( parameters.numLightProbes ); + array.push( parameters.shadowMapType ); + array.push( parameters.toneMapping ); + array.push( parameters.numClippingPlanes ); + array.push( parameters.numClipIntersection ); + array.push( parameters.depthPacking ); + + } + + function getProgramCacheKeyBooleans( array, parameters ) { + + _programLayers.disableAll(); + + if ( parameters.instancing ) + _programLayers.enable( 0 ); + if ( parameters.instancingColor ) + _programLayers.enable( 1 ); + if ( parameters.instancingMorph ) + _programLayers.enable( 2 ); + if ( parameters.matcap ) + _programLayers.enable( 3 ); + if ( parameters.envMap ) + _programLayers.enable( 4 ); + if ( parameters.normalMapObjectSpace ) + _programLayers.enable( 5 ); + if ( parameters.normalMapTangentSpace ) + _programLayers.enable( 6 ); + if ( parameters.clearcoat ) + _programLayers.enable( 7 ); + if ( parameters.iridescence ) + _programLayers.enable( 8 ); + if ( parameters.alphaTest ) + _programLayers.enable( 9 ); + if ( parameters.vertexColors ) + _programLayers.enable( 10 ); + if ( parameters.vertexAlphas ) + _programLayers.enable( 11 ); + if ( parameters.vertexUv1s ) + _programLayers.enable( 12 ); + if ( parameters.vertexUv2s ) + _programLayers.enable( 13 ); + if ( parameters.vertexUv3s ) + _programLayers.enable( 14 ); + if ( parameters.vertexTangents ) + _programLayers.enable( 15 ); + if ( parameters.anisotropy ) + _programLayers.enable( 16 ); + if ( parameters.alphaHash ) + _programLayers.enable( 17 ); + if ( parameters.batching ) + _programLayers.enable( 18 ); + if ( parameters.dispersion ) + _programLayers.enable( 19 ); + if ( parameters.retroreflection ) + _programLayers.enable( 24 ); + if ( parameters.batchingColor ) + _programLayers.enable( 20 ); + if ( parameters.gradientMap ) + _programLayers.enable( 21 ); + if ( parameters.packedNormalMap ) + _programLayers.enable( 22 ); + if ( parameters.vertexNormals ) + _programLayers.enable( 23 ); + + array.push( _programLayers.mask ); + _programLayers.disableAll(); + + if ( parameters.fog ) + _programLayers.enable( 0 ); + if ( parameters.useFog ) + _programLayers.enable( 1 ); + if ( parameters.flatShading ) + _programLayers.enable( 2 ); + if ( parameters.logarithmicDepthBuffer ) + _programLayers.enable( 3 ); + if ( parameters.reversedDepthBuffer ) + _programLayers.enable( 4 ); + if ( parameters.skinning ) + _programLayers.enable( 5 ); + if ( parameters.morphTargets ) + _programLayers.enable( 6 ); + if ( parameters.morphNormals ) + _programLayers.enable( 7 ); + if ( parameters.morphColors ) + _programLayers.enable( 8 ); + if ( parameters.premultipliedAlpha ) + _programLayers.enable( 9 ); + if ( parameters.shadowMapEnabled ) + _programLayers.enable( 10 ); + if ( parameters.doubleSided ) + _programLayers.enable( 11 ); + if ( parameters.flipSided ) + _programLayers.enable( 12 ); + if ( parameters.useDepthPacking ) + _programLayers.enable( 13 ); + if ( parameters.dithering ) + _programLayers.enable( 14 ); + if ( parameters.transmission ) + _programLayers.enable( 15 ); + if ( parameters.sheen ) + _programLayers.enable( 16 ); + if ( parameters.opaque ) + _programLayers.enable( 17 ); + if ( parameters.pointsUvs ) + _programLayers.enable( 18 ); + if ( parameters.decodeVideoTexture ) + _programLayers.enable( 19 ); + if ( parameters.decodeVideoTextureEmissive ) + _programLayers.enable( 20 ); + if ( parameters.alphaToCoverage ) + _programLayers.enable( 21 ); + if ( parameters.numLightProbeGrids > 0 ) + _programLayers.enable( 22 ); + if ( parameters.hasPositionAttribute ) + _programLayers.enable( 23 ); + + array.push( _programLayers.mask ); + + } + + function getUniforms( material ) { + + const shaderID = shaderIDs[ material.type ]; + let uniforms; + + if ( shaderID ) { + + const shader = ShaderLib[ shaderID ]; + uniforms = UniformsUtils.clone( shader.uniforms ); + + } else { + + uniforms = material.uniforms; + + } + + return uniforms; + + } + + function acquireProgram( parameters, cacheKey ) { + + let program = programsMap.get( cacheKey ); + + if ( program !== undefined ) { + + ++ program.usedTimes; + + } else { + + program = new WebGLProgram( renderer, cacheKey, parameters, bindingStates ); + programs.push( program ); + + programsMap.set( cacheKey, program ); + + } + + return program; + + } + + function releaseProgram( program ) { + + if ( -- program.usedTimes === 0 ) { + + // Remove from unordered set + const i = programs.indexOf( program ); + programs[ i ] = programs[ programs.length - 1 ]; + programs.pop(); + + // Remove from map + programsMap.delete( program.cacheKey ); + + // Free WebGL resources + program.destroy(); + + } + + } + + function releaseShaderCache( material ) { + + _customShaders.remove( material ); + + } + + function dispose() { + + _customShaders.dispose(); + + } + + return { + getParameters: getParameters, + getProgramCacheKey: getProgramCacheKey, + getUniforms: getUniforms, + acquireProgram: acquireProgram, + releaseProgram: releaseProgram, + releaseShaderCache: releaseShaderCache, + // Exposed for resource monitoring & error feedback via renderer.info: + programs: programs, + dispose: dispose + }; + +} + +function WebGLProperties() { + + let properties = new WeakMap(); + + function has( object ) { + + return properties.has( object ); + + } + + function get( object ) { + + let map = properties.get( object ); + + if ( map === undefined ) { + + map = {}; + properties.set( object, map ); + + } + + return map; + + } + + function remove( object ) { + + properties.delete( object ); + + } + + function update( object, key, value ) { + + properties.get( object )[ key ] = value; + + } + + function dispose() { + + properties = new WeakMap(); + + } + + return { + has: has, + get: get, + remove: remove, + update: update, + dispose: dispose + }; + +} + +function painterSortStable( a, b ) { + + if ( a.groupOrder !== b.groupOrder ) { + + return a.groupOrder - b.groupOrder; + + } else if ( a.renderOrder !== b.renderOrder ) { + + return a.renderOrder - b.renderOrder; + + } else if ( a.material.id !== b.material.id ) { + + return a.material.id - b.material.id; + + } else if ( a.materialVariant !== b.materialVariant ) { + + return a.materialVariant - b.materialVariant; + + } else if ( a.z !== b.z ) { + + return a.z - b.z; + + } else { + + return a.id - b.id; + + } + +} + +function reversePainterSortStable( a, b ) { + + if ( a.groupOrder !== b.groupOrder ) { + + return a.groupOrder - b.groupOrder; + + } else if ( a.renderOrder !== b.renderOrder ) { + + return a.renderOrder - b.renderOrder; + + } else if ( a.z !== b.z ) { + + return b.z - a.z; + + } else { + + return a.id - b.id; + + } + +} + + +function WebGLRenderList() { + + const renderItems = []; + let renderItemsIndex = 0; + + const opaque = []; + const transmissive = []; + const transparent = []; + + function init() { + + renderItemsIndex = 0; + + opaque.length = 0; + transmissive.length = 0; + transparent.length = 0; + + } + + function materialVariant( object ) { + + let variant = 0; + if ( object.isInstancedMesh ) variant += 2; + if ( object.isSkinnedMesh ) variant += 1; + return variant; + + } + + function getNextRenderItem( object, geometry, material, groupOrder, z, group ) { + + let renderItem = renderItems[ renderItemsIndex ]; + + if ( renderItem === undefined ) { + + renderItem = { + id: object.id, + object: object, + geometry: geometry, + material: material, + materialVariant: materialVariant( object ), + groupOrder: groupOrder, + renderOrder: object.renderOrder, + z: z, + group: group + }; + + renderItems[ renderItemsIndex ] = renderItem; + + } else { + + renderItem.id = object.id; + renderItem.object = object; + renderItem.geometry = geometry; + renderItem.material = material; + renderItem.materialVariant = materialVariant( object ); + renderItem.groupOrder = groupOrder; + renderItem.renderOrder = object.renderOrder; + renderItem.z = z; + renderItem.group = group; + + } + + renderItemsIndex ++; + + return renderItem; + + } + + function push( object, geometry, material, groupOrder, z, group, camera ) { + + // with a reversed depth buffer the projected z is inverted + + if ( camera.reversedDepth === true ) z = - z; + + const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group ); + + if ( material.transmission > 0.0 ) { + + transmissive.push( renderItem ); + + } else if ( material.transparent === true ) { + + transparent.push( renderItem ); + + } else { + + opaque.push( renderItem ); + + } + + } + + function unshift( object, geometry, material, groupOrder, z, group ) { + + const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group ); + + if ( material.transmission > 0.0 ) { + + transmissive.unshift( renderItem ); + + } else if ( material.transparent === true ) { + + transparent.unshift( renderItem ); + + } else { + + opaque.unshift( renderItem ); + + } + + } + + function sort( customOpaqueSort, customTransparentSort ) { + + if ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable ); + if ( transmissive.length > 1 ) transmissive.sort( customTransparentSort || reversePainterSortStable ); + if ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable ); + + } + + function finish() { + + // Clear references from inactive renderItems in the list + + for ( let i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) { + + const renderItem = renderItems[ i ]; + + if ( renderItem.id === null ) break; + + renderItem.id = null; + renderItem.object = null; + renderItem.geometry = null; + renderItem.material = null; + renderItem.group = null; + + } + + } + + return { + + opaque: opaque, + transmissive: transmissive, + transparent: transparent, + + init: init, + push: push, + unshift: unshift, + finish: finish, + + sort: sort + }; + +} + +function WebGLRenderLists() { + + let lists = new WeakMap(); + + function get( scene, renderCallDepth ) { + + const listArray = lists.get( scene ); + let list; + + if ( listArray === undefined ) { + + list = new WebGLRenderList(); + lists.set( scene, [ list ] ); + + } else { + + if ( renderCallDepth >= listArray.length ) { + + list = new WebGLRenderList(); + listArray.push( list ); + + } else { + + list = listArray[ renderCallDepth ]; + + } + + } + + return list; + + } + + function dispose() { + + lists = new WeakMap(); + + } + + return { + get: get, + dispose: dispose + }; + +} + +function UniformsCache() { + + const lights = {}; + + return { + + get: function ( light ) { + + if ( lights[ light.id ] !== undefined ) { + + return lights[ light.id ]; + + } + + let uniforms; + + switch ( light.type ) { + + case 'SunLight': + case 'DirectionalLight': + uniforms = { + direction: new Vector3(), + color: new Color() + }; + break; + + case 'SpotLight': + uniforms = { + position: new Vector3(), + direction: new Vector3(), + color: new Color(), + distance: 0, + coneCos: 0, + penumbraCos: 0, + decay: 0 + }; + break; + + case 'PointLight': + uniforms = { + position: new Vector3(), + color: new Color(), + distance: 0, + decay: 0 + }; + break; + + case 'HemisphereLight': + uniforms = { + direction: new Vector3(), + skyColor: new Color(), + groundColor: new Color() + }; + break; + + case 'RectAreaLight': + uniforms = { + color: new Color(), + position: new Vector3(), + halfWidth: new Vector3(), + halfHeight: new Vector3() + }; + break; + + } + + lights[ light.id ] = uniforms; + + return uniforms; + + } + + }; + +} + +function ShadowUniformsCache() { + + const lights = {}; + + return { + + get: function ( light ) { + + if ( lights[ light.id ] !== undefined ) { + + return lights[ light.id ]; + + } + + let uniforms; + + switch ( light.type ) { + + case 'SunLight': + case 'DirectionalLight': + uniforms = { + shadowIntensity: 1, + shadowBias: 0, + shadowNormalBias: 0, + shadowRadius: 1, + shadowMapSize: new Vector2() + }; + break; + + case 'SpotLight': + uniforms = { + shadowIntensity: 1, + shadowBias: 0, + shadowNormalBias: 0, + shadowRadius: 1, + shadowMapSize: new Vector2() + }; + break; + + case 'PointLight': + uniforms = { + shadowIntensity: 1, + shadowBias: 0, + shadowNormalBias: 0, + shadowRadius: 1, + shadowMapSize: new Vector2(), + shadowCameraNear: 1, + shadowCameraFar: 1000 + }; + break; + + // TODO (abelnation): set RectAreaLight shadow uniforms + + } + + lights[ light.id ] = uniforms; + + return uniforms; + + } + + }; + +} + + + +let nextVersion = 0; + +function shadowCastingAndTexturingLightsFirst( lightA, lightB ) { + + return ( lightB.castShadow ? 2 : 0 ) - ( lightA.castShadow ? 2 : 0 ) + ( lightB.map ? 1 : 0 ) - ( lightA.map ? 1 : 0 ); + +} + +function WebGLLights( extensions ) { + + const cache = new UniformsCache(); + + const shadowCache = ShadowUniformsCache(); + + const state = { + + version: 0, + + hash: { + sunLength: -1, + directionalLength: -1, + pointLength: -1, + spotLength: -1, + rectAreaLength: -1, + hemiLength: -1, + + numSunShadows: -1, + numDirectionalShadows: -1, + numPointShadows: -1, + numSpotShadows: -1, + numSpotMaps: -1, + + numLightProbes: -1 + }, + + ambient: [ 0, 0, 0 ], + probe: [], + sun: [], + sunShadow: [], + sunShadowMap: [], + sunShadowMatrix: [], + sunShadowCascade: [], + directional: [], + directionalShadow: [], + directionalShadowMap: [], + directionalShadowMatrix: [], + spot: [], + spotLightMap: [], + spotShadow: [], + spotShadowMap: [], + spotLightMatrix: [], + rectArea: [], + rectAreaLTC1: null, + rectAreaLTC2: null, + point: [], + pointShadow: [], + pointShadowMap: [], + pointShadowMatrix: [], + hemi: [], + numSpotLightShadowsWithMaps: 0, + numLightProbes: 0 + + }; + + for ( let i = 0; i < 9; i ++ ) state.probe.push( new Vector3() ); + + const vector3 = new Vector3(); + const matrix4 = new Matrix4(); + const matrix42 = new Matrix4(); + + function setup( lights ) { + + let r = 0, g = 0, b = 0; + + for ( let i = 0; i < 9; i ++ ) state.probe[ i ].set( 0, 0, 0 ); + + let sunLength = 0; + let numSunShadows = 0; + let numSunShadowCascades = 0; + let directionalLength = 0; + let pointLength = 0; + let spotLength = 0; + let rectAreaLength = 0; + let hemiLength = 0; + + let numDirectionalShadows = 0; + let numPointShadows = 0; + let numSpotShadows = 0; + let numSpotMaps = 0; + let numSpotShadowsWithMaps = 0; + + let numLightProbes = 0; + + // ordering : [shadow casting + map texturing, map texturing, shadow casting, none ] + lights.sort( shadowCastingAndTexturingLightsFirst ); + + for ( let i = 0, l = lights.length; i < l; i ++ ) { + + const light = lights[ i ]; + + const color = light.color; + const intensity = light.intensity; + const distance = light.distance; + + let shadowMap = null; + + if ( light.shadow && light.shadow.map ) { + + if ( light.shadow.map.texture.format === RGFormat ) { + + // VSM uses color texture with blurred mean/std_dev + shadowMap = light.shadow.map.texture; + + } else { + + // Other types use depth texture + shadowMap = light.shadow.map.depthTexture || light.shadow.map.texture; + + } + + } + + if ( light.isAmbientLight ) { + + r += color.r * intensity; + g += color.g * intensity; + b += color.b * intensity; + + } else if ( light.isLightProbe ) { + + for ( let j = 0; j < 9; j ++ ) { + + state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity ); + + } + + numLightProbes ++; + + } else if ( light.isSunLight ) { + + const uniforms = cache.get( light ); + + uniforms.color.copy( light.color ).multiplyScalar( light.intensity ); + + if ( light.castShadow ) { + + const shadow = light.shadow; + + const shadowUniforms = shadowCache.get( light ); + + shadowUniforms.shadowIntensity = shadow.intensity; + shadowUniforms.shadowBias = shadow.bias; + shadowUniforms.shadowNormalBias = shadow.normalBias; + shadowUniforms.shadowRadius = shadow.radius; + shadowUniforms.shadowMapSize.copy( shadow.mapSize ).multiply( shadow.getFrameExtents() ); + + state.sunShadow[ numSunShadows ] = shadowUniforms; + state.sunShadowMap[ numSunShadows ] = shadowMap; + + const cascadeCount = shadow.getViewportCount(); + + for ( let j = 0; j < cascadeCount; j ++ ) { + + state.sunShadowMatrix[ numSunShadowCascades + j ] = shadow.getMatrix( j ); + state.sunShadowCascade[ numSunShadowCascades + j ] = shadow._cascadeData[ j ]; + + } + + numSunShadowCascades += cascadeCount; + numSunShadows ++; + + } + + state.sun[ sunLength ] = uniforms; + + sunLength ++; + + } else if ( light.isDirectionalLight ) { + + const uniforms = cache.get( light ); + + uniforms.color.copy( light.color ).multiplyScalar( light.intensity ); + + if ( light.castShadow ) { + + const shadow = light.shadow; + + const shadowUniforms = shadowCache.get( light ); + + shadowUniforms.shadowIntensity = shadow.intensity; + shadowUniforms.shadowBias = shadow.bias; + shadowUniforms.shadowNormalBias = shadow.normalBias; + shadowUniforms.shadowRadius = shadow.radius; + shadowUniforms.shadowMapSize = shadow.mapSize; + + state.directionalShadow[ directionalLength ] = shadowUniforms; + state.directionalShadowMap[ directionalLength ] = shadowMap; + state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix; + + numDirectionalShadows ++; + + } + + state.directional[ directionalLength ] = uniforms; + + directionalLength ++; + + } else if ( light.isSpotLight ) { + + const uniforms = cache.get( light ); + + uniforms.position.setFromMatrixPosition( light.matrixWorld ); + + uniforms.color.copy( color ).multiplyScalar( intensity ); + uniforms.distance = distance; + + uniforms.coneCos = Math.cos( light.angle ); + uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) ); + uniforms.decay = light.decay; + + state.spot[ spotLength ] = uniforms; + + const shadow = light.shadow; + + if ( light.map ) { + + state.spotLightMap[ numSpotMaps ] = light.map; + numSpotMaps ++; + + // make sure the lightMatrix is up to date + // TODO : do it if required only + shadow.updateMatrices( light ); + + if ( light.castShadow ) numSpotShadowsWithMaps ++; + + } + + state.spotLightMatrix[ spotLength ] = shadow.matrix; + + if ( light.castShadow ) { + + const shadowUniforms = shadowCache.get( light ); + + shadowUniforms.shadowIntensity = shadow.intensity; + shadowUniforms.shadowBias = shadow.bias; + shadowUniforms.shadowNormalBias = shadow.normalBias; + shadowUniforms.shadowRadius = shadow.radius; + shadowUniforms.shadowMapSize = shadow.mapSize; + + state.spotShadow[ spotLength ] = shadowUniforms; + state.spotShadowMap[ spotLength ] = shadowMap; + + numSpotShadows ++; + + } + + spotLength ++; + + } else if ( light.isRectAreaLight ) { + + const uniforms = cache.get( light ); + + uniforms.color.copy( color ).multiplyScalar( intensity ); + + uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 ); + uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 ); + + state.rectArea[ rectAreaLength ] = uniforms; + + rectAreaLength ++; + + } else if ( light.isPointLight ) { + + const uniforms = cache.get( light ); + + uniforms.color.copy( light.color ).multiplyScalar( light.intensity ); + uniforms.distance = light.distance; + uniforms.decay = light.decay; + + if ( light.castShadow ) { + + const shadow = light.shadow; + + const shadowUniforms = shadowCache.get( light ); + + shadowUniforms.shadowIntensity = shadow.intensity; + shadowUniforms.shadowBias = shadow.bias; + shadowUniforms.shadowNormalBias = shadow.normalBias; + shadowUniforms.shadowRadius = shadow.radius; + shadowUniforms.shadowMapSize = shadow.mapSize; + shadowUniforms.shadowCameraNear = shadow.camera.near; + shadowUniforms.shadowCameraFar = shadow.camera.far; + + state.pointShadow[ pointLength ] = shadowUniforms; + state.pointShadowMap[ pointLength ] = shadowMap; + state.pointShadowMatrix[ pointLength ] = light.shadow.matrix; + + numPointShadows ++; + + } + + state.point[ pointLength ] = uniforms; + + pointLength ++; + + } else if ( light.isHemisphereLight ) { + + const uniforms = cache.get( light ); + + uniforms.skyColor.copy( light.color ).multiplyScalar( intensity ); + uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity ); + + state.hemi[ hemiLength ] = uniforms; + + hemiLength ++; + + } + + } + + if ( rectAreaLength > 0 ) { + + if ( extensions.has( 'OES_texture_float_linear' ) === true ) { + + state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1; + state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2; + + } else { + + state.rectAreaLTC1 = UniformsLib.LTC_HALF_1; + state.rectAreaLTC2 = UniformsLib.LTC_HALF_2; + + } + + } + + state.ambient[ 0 ] = r; + state.ambient[ 1 ] = g; + state.ambient[ 2 ] = b; + + const hash = state.hash; + + if ( hash.sunLength !== sunLength || + hash.directionalLength !== directionalLength || + hash.pointLength !== pointLength || + hash.spotLength !== spotLength || + hash.rectAreaLength !== rectAreaLength || + hash.hemiLength !== hemiLength || + hash.numSunShadows !== numSunShadows || + hash.numDirectionalShadows !== numDirectionalShadows || + hash.numPointShadows !== numPointShadows || + hash.numSpotShadows !== numSpotShadows || + hash.numSpotMaps !== numSpotMaps || + hash.numLightProbes !== numLightProbes ) { + + state.sun.length = sunLength; + state.directional.length = directionalLength; + state.spot.length = spotLength; + state.rectArea.length = rectAreaLength; + state.point.length = pointLength; + state.hemi.length = hemiLength; + + state.sunShadow.length = numSunShadows; + state.sunShadowMap.length = numSunShadows; + state.sunShadowMatrix.length = numSunShadowCascades; + state.sunShadowCascade.length = numSunShadowCascades; + state.directionalShadow.length = numDirectionalShadows; + state.directionalShadowMap.length = numDirectionalShadows; + state.directionalShadowMatrix.length = numDirectionalShadows; + state.pointShadow.length = numPointShadows; + state.pointShadowMap.length = numPointShadows; + state.pointShadowMatrix.length = numPointShadows; + state.spotShadow.length = numSpotShadows; + state.spotShadowMap.length = numSpotShadows; + state.spotLightMatrix.length = numSpotShadows + numSpotMaps - numSpotShadowsWithMaps; + state.spotLightMap.length = numSpotMaps; + state.numSpotLightShadowsWithMaps = numSpotShadowsWithMaps; + state.numLightProbes = numLightProbes; + + hash.sunLength = sunLength; + hash.directionalLength = directionalLength; + hash.pointLength = pointLength; + hash.spotLength = spotLength; + hash.rectAreaLength = rectAreaLength; + hash.hemiLength = hemiLength; + + hash.numSunShadows = numSunShadows; + hash.numDirectionalShadows = numDirectionalShadows; + hash.numPointShadows = numPointShadows; + hash.numSpotShadows = numSpotShadows; + hash.numSpotMaps = numSpotMaps; + + hash.numLightProbes = numLightProbes; + + state.version = nextVersion ++; + + } + + } + + function setupView( lights, camera ) { + + let sunLength = 0; + let directionalLength = 0; + let pointLength = 0; + let spotLength = 0; + let rectAreaLength = 0; + let hemiLength = 0; + + const viewMatrix = camera.matrixWorldInverse; + + for ( let i = 0, l = lights.length; i < l; i ++ ) { + + const light = lights[ i ]; + + if ( light.isSunLight ) { + + const uniforms = state.sun[ sunLength ]; + + uniforms.direction.setFromMatrixPosition( light.matrixWorld ); + uniforms.direction.transformDirection( viewMatrix ); + + sunLength ++; + + } else if ( light.isDirectionalLight ) { + + const uniforms = state.directional[ directionalLength ]; + + uniforms.direction.setFromMatrixPosition( light.matrixWorld ); + vector3.setFromMatrixPosition( light.target.matrixWorld ); + uniforms.direction.sub( vector3 ); + uniforms.direction.transformDirection( viewMatrix ); + + directionalLength ++; + + } else if ( light.isSpotLight ) { + + const uniforms = state.spot[ spotLength ]; + + uniforms.position.setFromMatrixPosition( light.matrixWorld ); + uniforms.position.applyMatrix4( viewMatrix ); + + uniforms.direction.setFromMatrixPosition( light.matrixWorld ); + vector3.setFromMatrixPosition( light.target.matrixWorld ); + uniforms.direction.sub( vector3 ); + uniforms.direction.transformDirection( viewMatrix ); + + spotLength ++; + + } else if ( light.isRectAreaLight ) { + + const uniforms = state.rectArea[ rectAreaLength ]; + + uniforms.position.setFromMatrixPosition( light.matrixWorld ); + uniforms.position.applyMatrix4( viewMatrix ); + + // extract local rotation of light to derive width/height half vectors + matrix42.identity(); + matrix4.copy( light.matrixWorld ); + matrix4.premultiply( viewMatrix ); + matrix42.extractRotation( matrix4 ); + + uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 ); + uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 ); + + uniforms.halfWidth.applyMatrix4( matrix42 ); + uniforms.halfHeight.applyMatrix4( matrix42 ); + + rectAreaLength ++; + + } else if ( light.isPointLight ) { + + const uniforms = state.point[ pointLength ]; + + uniforms.position.setFromMatrixPosition( light.matrixWorld ); + uniforms.position.applyMatrix4( viewMatrix ); + + pointLength ++; + + } else if ( light.isHemisphereLight ) { + + const uniforms = state.hemi[ hemiLength ]; + + uniforms.direction.setFromMatrixPosition( light.matrixWorld ); + uniforms.direction.transformDirection( viewMatrix ); + + hemiLength ++; + + } + + } + + } + + return { + setup: setup, + setupView: setupView, + state: state + }; + +} + +function WebGLRenderState( extensions ) { + + const lights = new WebGLLights( extensions ); + + const lightsArray = []; + const shadowsArray = []; + const lightProbeGridArray = []; + + function init( camera ) { + + state.camera = camera; + + lightsArray.length = 0; + shadowsArray.length = 0; + lightProbeGridArray.length = 0; + + } + + function pushLight( light ) { + + lightsArray.push( light ); + + } + + function pushShadow( shadowLight ) { + + shadowsArray.push( shadowLight ); + + } + + function pushLightProbeGrid( volume ) { + + lightProbeGridArray.push( volume ); + + } + + function setupLights() { + + lights.setup( lightsArray ); + + } + + function setupLightsView( camera ) { + + lights.setupView( lightsArray, camera ); + + } + + const state = { + lightsArray: lightsArray, + shadowsArray: shadowsArray, + lightProbeGridArray: lightProbeGridArray, + + camera: null, + + lights: lights, + + transmissionRenderTarget: {}, + textureUnits: 0 + }; + + return { + init: init, + state: state, + setupLights: setupLights, + setupLightsView: setupLightsView, + + pushLight: pushLight, + pushShadow: pushShadow, + pushLightProbeGrid: pushLightProbeGrid + }; + +} + +function WebGLRenderStates( extensions ) { + + let renderStates = new WeakMap(); + + function get( scene, renderCallDepth = 0 ) { + + const renderStateArray = renderStates.get( scene ); + let renderState; + + if ( renderStateArray === undefined ) { + + renderState = new WebGLRenderState( extensions ); + renderStates.set( scene, [ renderState ] ); + + } else { + + if ( renderCallDepth >= renderStateArray.length ) { + + renderState = new WebGLRenderState( extensions ); + renderStateArray.push( renderState ); + + } else { + + renderState = renderStateArray[ renderCallDepth ]; + + } + + } + + return renderState; + + } + + function dispose() { + + renderStates = new WeakMap(); + + } + + return { + get: get, + dispose: dispose + }; + +} + +const vertex = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}"; + +const fragment = "uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\nvoid main() {\n\tconst float samples = float( VSM_SAMPLES );\n\tfloat mean = 0.0;\n\tfloat squared_mean = 0.0;\n\tfloat uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );\n\tfloat uvStart = samples <= 1.0 ? 0.0 : - 1.0;\n\tfor ( float i = 0.0; i < samples; i ++ ) {\n\t\tfloat uvOffset = uvStart + i * uvStride;\n\t\t#ifdef HORIZONTAL_PASS\n\t\t\tvec2 distribution = texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ).rg;\n\t\t\tmean += distribution.x;\n\t\t\tsquared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n\t\t#else\n\t\t\tfloat depth = texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ).r;\n\t\t\tmean += depth;\n\t\t\tsquared_mean += depth * depth;\n\t\t#endif\n\t}\n\tmean = mean / samples;\n\tsquared_mean = squared_mean / samples;\n\tfloat std_dev = sqrt( max( 0.0, squared_mean - mean * mean ) );\n\tgl_FragColor = vec4( mean, std_dev, 0.0, 1.0 );\n}"; + +const _cubeDirections = [ + /*@__PURE__*/ new Vector3( 1, 0, 0 ), /*@__PURE__*/ new Vector3( -1, 0, 0 ), /*@__PURE__*/ new Vector3( 0, 1, 0 ), + /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, 0, 1 ), /*@__PURE__*/ new Vector3( 0, 0, -1 ) +]; + +const _cubeUps = [ + /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, 0, 1 ), + /*@__PURE__*/ new Vector3( 0, 0, -1 ), /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, -1, 0 ) +]; + +const _projScreenMatrix = /*@__PURE__*/ new Matrix4(); +const _lightPositionWorld = /*@__PURE__*/ new Vector3(); +const _lookTarget = /*@__PURE__*/ new Vector3(); + +function WebGLShadowMap( renderer, objects, capabilities ) { + + let _frustum = new Frustum(); + + const _shadowMapSize = new Vector2(), + _viewportSize = new Vector2(), + + _viewport = new Vector4(), + + _depthMaterial = new MeshDepthMaterial(), + _distanceMaterial = new MeshDistanceMaterial(), + + _materialCache = {}, + + _maxTextureSize = capabilities.maxTextureSize; + + const shadowSide = { [ FrontSide ]: BackSide, [ BackSide ]: FrontSide, [ DoubleSide ]: DoubleSide }; + + const shadowMaterialVertical = new ShaderMaterial( { + defines: { + VSM_SAMPLES: 8 + }, + uniforms: { + shadow_pass: { value: null }, + resolution: { value: new Vector2() }, + radius: { value: 4.0 } + }, + + vertexShader: vertex, + fragmentShader: fragment + + } ); + + const shadowMaterialHorizontal = shadowMaterialVertical.clone(); + shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1; + + const fullScreenTri = new BufferGeometry(); + fullScreenTri.setAttribute( + 'position', + new BufferAttribute( + new Float32Array( [ -1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5 ] ), + 3 + ) + ); + + const fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical ); + + const scope = this; + + this.enabled = false; + + this.autoUpdate = true; + this.needsUpdate = false; + + this.type = PCFShadowMap; + let _previousType = this.type; + + this.render = function ( lights, scene, camera ) { + + if ( scope.enabled === false ) return; + if ( scope.autoUpdate === false && scope.needsUpdate === false ) return; + + if ( lights.length === 0 ) return; + + if ( this.type === PCFSoftShadowMap ) { + + warn( 'WebGLShadowMap: PCFSoftShadowMap has been removed. Using PCFShadowMap instead.' ); + this.type = PCFShadowMap; + + } + + const currentRenderTarget = renderer.getRenderTarget(); + const activeCubeFace = renderer.getActiveCubeFace(); + const activeMipmapLevel = renderer.getActiveMipmapLevel(); + + const _state = renderer.state; + + // Set GL state for depth map. + _state.setBlending( NoBlending ); + + if ( _state.buffers.depth.getReversed() === true ) { + + _state.buffers.color.setClear( 0, 0, 0, 0 ); + + } else { + + _state.buffers.color.setClear( 1, 1, 1, 1 ); + + } + + _state.buffers.depth.setTest( true ); + _state.setScissorTest( false ); + + // check for shadow map type changes + + const typeChanged = _previousType !== this.type; + + // When shadow map type changes, materials need recompilation because sampler types change + // (sampler2DShadow for PCF vs sampler2D for Basic) + if ( typeChanged ) { + + scene.traverse( function ( object ) { + + if ( object.material ) { + + if ( Array.isArray( object.material ) ) { + + object.material.forEach( mat => mat.needsUpdate = true ); + + } else { + + object.material.needsUpdate = true; + + } + + } + + } ); + + } + + // render depth map + + for ( let i = 0, il = lights.length; i < il; i ++ ) { + + const light = lights[ i ]; + const shadow = light.shadow; + + if ( shadow === undefined ) { + + warn( 'WebGLShadowMap:', light, 'has no shadow.' ); + continue; + + } + + if ( shadow.autoUpdate === false && shadow.needsUpdate === false ) continue; + + _shadowMapSize.copy( shadow.mapSize ); + + const shadowFrameExtents = shadow.getFrameExtents(); + + _shadowMapSize.multiply( shadowFrameExtents ); + + _viewportSize.copy( shadow.mapSize ); + + if ( _shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize ) { + + if ( _shadowMapSize.x > _maxTextureSize ) { + + _viewportSize.x = Math.floor( _maxTextureSize / shadowFrameExtents.x ); + _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x; + shadow.mapSize.x = _viewportSize.x; + + } + + if ( _shadowMapSize.y > _maxTextureSize ) { + + _viewportSize.y = Math.floor( _maxTextureSize / shadowFrameExtents.y ); + _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y; + shadow.mapSize.y = _viewportSize.y; + + } + + } + + const reversedDepthBuffer = renderer.state.buffers.depth.getReversed(); + shadow.camera._reversedDepth = reversedDepthBuffer; + + if ( shadow.map === null || typeChanged === true ) { + + if ( shadow.map !== null ) { + + if ( shadow.map.depthTexture !== null ) { + + shadow.map.depthTexture.dispose(); + shadow.map.depthTexture = null; + + } + + shadow.map.dispose(); + + } + + if ( this.type === VSMShadowMap ) { + + if ( light.isPointLight ) { + + warn( 'WebGLShadowMap: VSM shadow maps are not supported for PointLights. Use PCF or BasicShadowMap instead.' ); + continue; + + } + + shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, { + format: RGFormat, + type: HalfFloatType, + minFilter: LinearFilter, + magFilter: LinearFilter, + generateMipmaps: false + } ); + shadow.map.texture.name = light.name + '.shadowMap'; + + // Native depth texture for VSM - depth is captured here, then blurred into the color texture + shadow.map.depthTexture = new DepthTexture( _shadowMapSize.x, _shadowMapSize.y, FloatType ); + shadow.map.depthTexture.name = light.name + '.shadowMapDepth'; + shadow.map.depthTexture.format = DepthFormat; + shadow.map.depthTexture.compareFunction = null; // For regular sampling (not shadow comparison) + shadow.map.depthTexture.minFilter = NearestFilter; + shadow.map.depthTexture.magFilter = NearestFilter; + + } else { + + if ( light.isPointLight ) { + + shadow.map = new WebGLCubeRenderTarget( _shadowMapSize.x ); + shadow.map.depthTexture = new CubeDepthTexture( _shadowMapSize.x, UnsignedIntType ); + + } else { + + shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y ); + shadow.map.depthTexture = new DepthTexture( _shadowMapSize.x, _shadowMapSize.y, UnsignedIntType ); + + } + + shadow.map.depthTexture.name = light.name + '.shadowMap'; + shadow.map.depthTexture.format = DepthFormat; + + if ( this.type === PCFShadowMap ) { + + shadow.map.depthTexture.compareFunction = reversedDepthBuffer ? GreaterEqualCompare : LessEqualCompare; + shadow.map.depthTexture.minFilter = LinearFilter; + shadow.map.depthTexture.magFilter = LinearFilter; + + } else { + + shadow.map.depthTexture.compareFunction = null; + shadow.map.depthTexture.minFilter = NearestFilter; + shadow.map.depthTexture.magFilter = NearestFilter; + + } + + } + + shadow.camera.updateProjectionMatrix(); + + } + + if ( shadow.map.isWebGLCubeRenderTarget !== true && ( shadow.map.width !== _shadowMapSize.x || shadow.map.height !== _shadowMapSize.y ) ) { + + shadow.map.setSize( _shadowMapSize.x, _shadowMapSize.y ); + + } + + // For cube render targets (PointLights), render all 6 faces. Sun lights + // render one atlas viewport per cascade. + const faceCount = shadow.map.isWebGLCubeRenderTarget ? 6 : shadow.getViewportCount(); + + if ( light.isPointLight !== true ) shadow.updateMatrices( light, camera ); + + for ( let face = 0; face < faceCount; face ++ ) { + + const shadowCamera = shadow.getCamera( face ); + + if ( light.isPointLight ) { + + const camera = shadow.camera; + const shadowMatrix = shadow.matrix; + + const far = light.distance || camera.far; + + if ( far !== camera.far ) { + + camera.far = far; + camera.updateProjectionMatrix(); + + } + + _lightPositionWorld.setFromMatrixPosition( light.matrixWorld ); + camera.position.copy( _lightPositionWorld ); + + _lookTarget.copy( camera.position ); + _lookTarget.add( _cubeDirections[ face ] ); + camera.up.copy( _cubeUps[ face ] ); + camera.lookAt( _lookTarget ); + camera.updateMatrixWorld(); + + shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z ); + + _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse ); + shadow._frustum.setFromProjectionMatrix( _projScreenMatrix, camera.coordinateSystem, camera.reversedDepth ); + + } + + // For cube render targets, render to each face separately + if ( shadow.map.isWebGLCubeRenderTarget ) { + + renderer.setRenderTarget( shadow.map, face ); + renderer.clear(); + + } else { + + // For 2D render targets, use viewports + if ( face === 0 ) { + + renderer.setRenderTarget( shadow.map ); + renderer.clear(); + + } + + const viewport = shadow.getViewport( face ); + + _viewport.set( + _viewportSize.x * viewport.x, + _viewportSize.y * viewport.y, + _viewportSize.x * viewport.z, + _viewportSize.y * viewport.w + ); + + _state.viewport( _viewport ); + + } + + _frustum = shadow.getFrustum( face ); + + renderObject( scene, camera, shadowCamera, light, this.type ); + + } + + // do blur pass for VSM + + if ( shadow.isPointLightShadow !== true && this.type === VSMShadowMap ) { + + VSMPass( shadow, camera ); + + } + + shadow.needsUpdate = false; + + } + + _previousType = this.type; + + scope.needsUpdate = false; + + renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel ); + + }; + + function VSMPass( shadow, camera ) { + + const geometry = objects.update( fullScreenMesh ); + + if ( shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples ) { + + shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples; + shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples; + + shadowMaterialVertical.needsUpdate = true; + shadowMaterialHorizontal.needsUpdate = true; + + } + + if ( shadow.mapPass === null ) { + + shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, { + format: RGFormat, + type: HalfFloatType + } ); + + } else if ( shadow.mapPass.width !== shadow.map.width || shadow.mapPass.height !== shadow.map.height ) { + + shadow.mapPass.setSize( shadow.map.width, shadow.map.height ); + + } + + // vertical pass - read from native depth texture + + shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.depthTexture; + shadowMaterialVertical.uniforms.resolution.value.set( shadow.map.width, shadow.map.height ); + shadowMaterialVertical.uniforms.radius.value = shadow.radius; + renderer.setRenderTarget( shadow.mapPass ); + renderer.clear(); + renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null ); + + // horizontal pass + + shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture; + shadowMaterialHorizontal.uniforms.resolution.value.set( shadow.map.width, shadow.map.height ); + shadowMaterialHorizontal.uniforms.radius.value = shadow.radius; + renderer.setRenderTarget( shadow.map ); + renderer.clear(); + renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null ); + + } + + function getDepthMaterial( object, material, light, type ) { + + let result = null; + + const customMaterial = ( light.isPointLight === true ) ? object.customDistanceMaterial : object.customDepthMaterial; + + if ( customMaterial !== undefined ) { + + result = customMaterial; + + } else { + + result = ( light.isPointLight === true ) ? _distanceMaterial : _depthMaterial; + + if ( ( renderer.localClippingEnabled && material.clipShadows === true && Array.isArray( material.clippingPlanes ) && material.clippingPlanes.length !== 0 ) || + ( material.displacementMap && material.displacementScale !== 0 ) || + ( material.alphaMap && material.alphaTest > 0 ) || + ( material.map && material.alphaTest > 0 ) || + ( material.alphaToCoverage === true ) ) { + + // in this case we need a unique material instance reflecting the + // appropriate state + + const keyA = result.uuid, keyB = material.uuid; + + let materialsForVariant = _materialCache[ keyA ]; + + if ( materialsForVariant === undefined ) { + + materialsForVariant = {}; + _materialCache[ keyA ] = materialsForVariant; + + } + + let cachedMaterial = materialsForVariant[ keyB ]; + + if ( cachedMaterial === undefined ) { + + cachedMaterial = result.clone(); + materialsForVariant[ keyB ] = cachedMaterial; + material.addEventListener( 'dispose', onMaterialDispose ); + + } + + result = cachedMaterial; + + } + + } + + result.visible = material.visible; + result.wireframe = material.wireframe; + + if ( type === VSMShadowMap ) { + + result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side; + + } else { + + result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ]; + + } + + result.alphaMap = material.alphaMap; + result.alphaTest = ( material.alphaToCoverage === true ) ? 0.5 : material.alphaTest; // approximate alphaToCoverage by using a fixed alphaTest value + result.map = material.map; + + result.clipShadows = material.clipShadows; + result.clippingPlanes = material.clippingPlanes; + result.clipIntersection = material.clipIntersection; + + result.displacementMap = material.displacementMap; + result.displacementScale = material.displacementScale; + result.displacementBias = material.displacementBias; + + result.wireframeLinewidth = material.wireframeLinewidth; + result.linewidth = material.linewidth; + + if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) { + + const materialProperties = renderer.properties.get( result ); + materialProperties.light = light; + + } + + return result; + + } + + function renderObject( object, camera, shadowCamera, light, type ) { + + if ( object.visible === false ) return; + + const visible = object.layers.test( camera.layers ); + + if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) { + + if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || object.intersectsFrustum( _frustum ) ) ) { + + object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld ); + + const geometry = objects.update( object ); + const material = object.material; + + if ( Array.isArray( material ) ) { + + const groups = geometry.groups; + + for ( let k = 0, kl = groups.length; k < kl; k ++ ) { + + const group = groups[ k ]; + const groupMaterial = material[ group.materialIndex ]; + + if ( groupMaterial && groupMaterial.visible ) { + + const depthMaterial = getDepthMaterial( object, groupMaterial, light, type ); + + object.onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, group ); + + renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group ); + + object.onAfterShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, group ); + + } + + } + + } else if ( material.visible ) { + + const depthMaterial = getDepthMaterial( object, material, light, type ); + + object.onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, null ); + + renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null ); + + object.onAfterShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, null ); + + } + + } + + } + + const children = object.children; + + for ( let i = 0, l = children.length; i < l; i ++ ) { + + renderObject( children[ i ], camera, shadowCamera, light, type ); + + } + + } + + function onMaterialDispose( event ) { + + const material = event.target; + + material.removeEventListener( 'dispose', onMaterialDispose ); + + // make sure to remove the unique distance/depth materials used for shadow map rendering + + for ( const id in _materialCache ) { + + const cache = _materialCache[ id ]; + + const uuid = event.target.uuid; + + if ( uuid in cache ) { + + const shadowMaterial = cache[ uuid ]; + shadowMaterial.dispose(); + delete cache[ uuid ]; + + } + + } + + } + +} + +function WebGLState( gl, extensions ) { + + function ColorBuffer() { + + let locked = false; + + const color = new Vector4(); + let currentColorMask = null; + const currentColorClear = new Vector4( 0, 0, 0, 0 ); + + return { + + setMask: function ( colorMask ) { + + if ( currentColorMask !== colorMask && ! locked ) { + + gl.colorMask( colorMask, colorMask, colorMask, colorMask ); + currentColorMask = colorMask; + + } + + }, + + setLocked: function ( lock ) { + + locked = lock; + + }, + + setClear: function ( r, g, b, a, premultipliedAlpha ) { + + if ( premultipliedAlpha === true ) { + + r *= a; g *= a; b *= a; + + } + + color.set( r, g, b, a ); + + if ( currentColorClear.equals( color ) === false ) { + + gl.clearColor( r, g, b, a ); + currentColorClear.copy( color ); + + } + + }, + + reset: function () { + + locked = false; + + currentColorMask = null; + currentColorClear.set( -1, 0, 0, 0 ); // set to invalid state + + } + + }; + + } + + function DepthBuffer() { + + let locked = false; + + let currentReversed = false; + let currentDepthMask = null; + let currentDepthFunc = null; + let currentDepthClear = null; + + return { + + setReversed: function ( reversed ) { + + if ( currentReversed !== reversed ) { + + const ext = extensions.get( 'EXT_clip_control' ); + + if ( reversed ) { + + ext.clipControlEXT( ext.LOWER_LEFT_EXT, ext.ZERO_TO_ONE_EXT ); + + } else { + + ext.clipControlEXT( ext.LOWER_LEFT_EXT, ext.NEGATIVE_ONE_TO_ONE_EXT ); + + } + + currentReversed = reversed; + + const oldDepth = currentDepthClear; + currentDepthClear = null; + this.setClear( oldDepth ); + + } + + }, + + getReversed: function () { + + return currentReversed; + + }, + + setTest: function ( depthTest ) { + + if ( depthTest ) { + + enable( gl.DEPTH_TEST ); + + } else { + + disable( gl.DEPTH_TEST ); + + } + + }, + + setMask: function ( depthMask ) { + + if ( currentDepthMask !== depthMask && ! locked ) { + + gl.depthMask( depthMask ); + currentDepthMask = depthMask; + + } + + }, + + setFunc: function ( depthFunc ) { + + if ( currentReversed ) depthFunc = ReversedDepthFuncs[ depthFunc ]; + + if ( currentDepthFunc !== depthFunc ) { + + switch ( depthFunc ) { + + case NeverDepth: + + gl.depthFunc( gl.NEVER ); + break; + + case AlwaysDepth: + + gl.depthFunc( gl.ALWAYS ); + break; + + case LessDepth: + + gl.depthFunc( gl.LESS ); + break; + + case LessEqualDepth: + + gl.depthFunc( gl.LEQUAL ); + break; + + case EqualDepth: + + gl.depthFunc( gl.EQUAL ); + break; + + case GreaterEqualDepth: + + gl.depthFunc( gl.GEQUAL ); + break; + + case GreaterDepth: + + gl.depthFunc( gl.GREATER ); + break; + + case NotEqualDepth: + + gl.depthFunc( gl.NOTEQUAL ); + break; + + default: + + gl.depthFunc( gl.LEQUAL ); + + } + + currentDepthFunc = depthFunc; + + } + + }, + + setLocked: function ( lock ) { + + locked = lock; + + }, + + setClear: function ( depth ) { + + if ( currentDepthClear !== depth ) { + + currentDepthClear = depth; + + if ( currentReversed ) { + + depth = 1 - depth; + + } + + gl.clearDepth( depth ); + + } + + }, + + reset: function () { + + locked = false; + + currentDepthMask = null; + currentDepthFunc = null; + currentDepthClear = null; + currentReversed = false; + + } + + }; + + } + + function StencilBuffer() { + + let locked = false; + + let currentStencilMask = null; + let currentStencilFunc = null; + let currentStencilRef = null; + let currentStencilFuncMask = null; + let currentStencilFail = null; + let currentStencilZFail = null; + let currentStencilZPass = null; + let currentStencilClear = null; + + return { + + setTest: function ( stencilTest ) { + + if ( ! locked ) { + + if ( stencilTest ) { + + enable( gl.STENCIL_TEST ); + + } else { + + disable( gl.STENCIL_TEST ); + + } + + } + + }, + + setMask: function ( stencilMask ) { + + if ( currentStencilMask !== stencilMask && ! locked ) { + + gl.stencilMask( stencilMask ); + currentStencilMask = stencilMask; + + } + + }, + + setFunc: function ( stencilFunc, stencilRef, stencilMask ) { + + if ( currentStencilFunc !== stencilFunc || + currentStencilRef !== stencilRef || + currentStencilFuncMask !== stencilMask ) { + + gl.stencilFunc( stencilFunc, stencilRef, stencilMask ); + + currentStencilFunc = stencilFunc; + currentStencilRef = stencilRef; + currentStencilFuncMask = stencilMask; + + } + + }, + + setOp: function ( stencilFail, stencilZFail, stencilZPass ) { + + if ( currentStencilFail !== stencilFail || + currentStencilZFail !== stencilZFail || + currentStencilZPass !== stencilZPass ) { + + gl.stencilOp( stencilFail, stencilZFail, stencilZPass ); + + currentStencilFail = stencilFail; + currentStencilZFail = stencilZFail; + currentStencilZPass = stencilZPass; + + } + + }, + + setLocked: function ( lock ) { + + locked = lock; + + }, + + setClear: function ( stencil ) { + + if ( currentStencilClear !== stencil ) { + + gl.clearStencil( stencil ); + currentStencilClear = stencil; + + } + + }, + + reset: function () { + + locked = false; + + currentStencilMask = null; + currentStencilFunc = null; + currentStencilRef = null; + currentStencilFuncMask = null; + currentStencilFail = null; + currentStencilZFail = null; + currentStencilZPass = null; + currentStencilClear = null; + + } + + }; + + } + + // + + const colorBuffer = new ColorBuffer(); + const depthBuffer = new DepthBuffer(); + const stencilBuffer = new StencilBuffer(); + + const uboBindings = new WeakMap(); + const uboProgramMap = new WeakMap(); + + let enabledCapabilities = {}; + let parameters = {}; + + let currentBoundFramebuffers = {}; + let currentDrawbuffers = new WeakMap(); + let defaultDrawbuffers = []; + + let currentProgram = null; + + let currentBlendingEnabled = false; + let currentBlending = null; + let currentBlendEquation = null; + let currentBlendSrc = null; + let currentBlendDst = null; + let currentBlendEquationAlpha = null; + let currentBlendSrcAlpha = null; + let currentBlendDstAlpha = null; + let currentBlendColor = new Color( 0, 0, 0 ); + let currentBlendAlpha = 0; + let currentPremultipledAlpha = false; + + let currentFlipSided = null; + let currentCullFace = null; + + let currentLineWidth = null; + + let currentPolygonOffsetFactor = null; + let currentPolygonOffsetUnits = null; + + const maxTextures = gl.getParameter( gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS ); + + let lineWidthAvailable = false; + let version = 0; + const glVersion = gl.getParameter( gl.VERSION ); + + if ( glVersion.indexOf( 'WebGL' ) !== -1 ) { + + version = parseFloat( /^WebGL (\d)/.exec( glVersion )[ 1 ] ); + lineWidthAvailable = ( version >= 1.0 ); + + } else if ( glVersion.indexOf( 'OpenGL ES' ) !== -1 ) { + + version = parseFloat( /^OpenGL ES (\d)/.exec( glVersion )[ 1 ] ); + lineWidthAvailable = ( version >= 2.0 ); + + } + + let currentTextureSlot = null; + let currentBoundTextures = {}; + + const scissorParam = gl.getParameter( gl.SCISSOR_BOX ); + const viewportParam = gl.getParameter( gl.VIEWPORT ); + + const currentScissor = new Vector4().fromArray( scissorParam ); + const currentViewport = new Vector4().fromArray( viewportParam ); + + function createTexture( type, target, count, dimensions ) { + + const data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4. + const texture = gl.createTexture(); + + gl.bindTexture( type, texture ); + gl.texParameteri( type, gl.TEXTURE_MIN_FILTER, gl.NEAREST ); + gl.texParameteri( type, gl.TEXTURE_MAG_FILTER, gl.NEAREST ); + + for ( let i = 0; i < count; i ++ ) { + + if ( type === gl.TEXTURE_3D || type === gl.TEXTURE_2D_ARRAY ) { + + gl.texImage3D( target, 0, gl.RGBA, 1, 1, dimensions, 0, gl.RGBA, gl.UNSIGNED_BYTE, data ); + + } else { + + gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data ); + + } + + } + + return texture; + + } + + const emptyTextures = {}; + emptyTextures[ gl.TEXTURE_2D ] = createTexture( gl.TEXTURE_2D, gl.TEXTURE_2D, 1 ); + emptyTextures[ gl.TEXTURE_CUBE_MAP ] = createTexture( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6 ); + emptyTextures[ gl.TEXTURE_2D_ARRAY ] = createTexture( gl.TEXTURE_2D_ARRAY, gl.TEXTURE_2D_ARRAY, 1, 1 ); + emptyTextures[ gl.TEXTURE_3D ] = createTexture( gl.TEXTURE_3D, gl.TEXTURE_3D, 1, 1 ); + + // init + + colorBuffer.setClear( 0, 0, 0, 1 ); + depthBuffer.setClear( 1 ); + stencilBuffer.setClear( 0 ); + + enable( gl.DEPTH_TEST ); + depthBuffer.setFunc( LessEqualDepth ); + + setFlipSided( false ); + setCullFace( CullFaceBack ); + enable( gl.CULL_FACE ); + + setBlending( NoBlending ); + + // + + function enable( id ) { + + if ( enabledCapabilities[ id ] !== true ) { + + gl.enable( id ); + enabledCapabilities[ id ] = true; + + } + + } + + function disable( id ) { + + if ( enabledCapabilities[ id ] !== false ) { + + gl.disable( id ); + enabledCapabilities[ id ] = false; + + } + + } + + function bindFramebuffer( target, framebuffer ) { + + if ( currentBoundFramebuffers[ target ] !== framebuffer ) { + + gl.bindFramebuffer( target, framebuffer ); + + currentBoundFramebuffers[ target ] = framebuffer; + + // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER + + if ( target === gl.DRAW_FRAMEBUFFER ) { + + currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer; + + } + + if ( target === gl.FRAMEBUFFER ) { + + currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer; + + } + + return true; + + } + + return false; + + } + + function drawBuffers( renderTarget, framebuffer ) { + + let drawBuffers = defaultDrawbuffers; + + let needsUpdate = false; + + if ( renderTarget ) { + + drawBuffers = currentDrawbuffers.get( framebuffer ); + + if ( drawBuffers === undefined ) { + + drawBuffers = []; + currentDrawbuffers.set( framebuffer, drawBuffers ); + + } + + const textures = renderTarget.textures; + + if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) { + + for ( let i = 0, il = textures.length; i < il; i ++ ) { + + drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i; + + } + + drawBuffers.length = textures.length; + + needsUpdate = true; + + } + + } else { + + if ( drawBuffers[ 0 ] !== gl.BACK ) { + + drawBuffers[ 0 ] = gl.BACK; + + needsUpdate = true; + + } + + } + + if ( needsUpdate ) { + + gl.drawBuffers( drawBuffers ); + + } + + } + + function useProgram( program ) { + + if ( currentProgram !== program ) { + + gl.useProgram( program ); + + currentProgram = program; + + return true; + + } + + return false; + + } + + const equationToGL = { + [ AddEquation ]: gl.FUNC_ADD, + [ SubtractEquation ]: gl.FUNC_SUBTRACT, + [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT + }; + + equationToGL[ MinEquation ] = gl.MIN; + equationToGL[ MaxEquation ] = gl.MAX; + + const factorToGL = { + [ ZeroFactor ]: gl.ZERO, + [ OneFactor ]: gl.ONE, + [ SrcColorFactor ]: gl.SRC_COLOR, + [ SrcAlphaFactor ]: gl.SRC_ALPHA, + [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE, + [ DstColorFactor ]: gl.DST_COLOR, + [ DstAlphaFactor ]: gl.DST_ALPHA, + [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR, + [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA, + [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR, + [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA, + [ ConstantColorFactor ]: gl.CONSTANT_COLOR, + [ OneMinusConstantColorFactor ]: gl.ONE_MINUS_CONSTANT_COLOR, + [ ConstantAlphaFactor ]: gl.CONSTANT_ALPHA, + [ OneMinusConstantAlphaFactor ]: gl.ONE_MINUS_CONSTANT_ALPHA + }; + + function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, blendColor, blendAlpha, premultipliedAlpha ) { + + if ( blending === NoBlending ) { + + if ( currentBlendingEnabled === true ) { + + disable( gl.BLEND ); + currentBlendingEnabled = false; + + } + + return; + + } + + if ( currentBlendingEnabled === false ) { + + enable( gl.BLEND ); + currentBlendingEnabled = true; + + } + + if ( blending !== CustomBlending ) { + + if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) { + + if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) { + + gl.blendEquation( gl.FUNC_ADD ); + + currentBlendEquation = AddEquation; + currentBlendEquationAlpha = AddEquation; + + } + + if ( premultipliedAlpha ) { + + switch ( blending ) { + + case NormalBlending: + gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA ); + break; + + case AdditiveBlending: + gl.blendFunc( gl.ONE, gl.ONE ); + break; + + case SubtractiveBlending: + gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE ); + break; + + case MultiplyBlending: + gl.blendFuncSeparate( gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ZERO, gl.ONE ); + break; + + default: + error( 'WebGLState: Invalid blending: ', blending ); + break; + + } + + } else { + + switch ( blending ) { + + case NormalBlending: + gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA ); + break; + + case AdditiveBlending: + gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE, gl.ONE, gl.ONE ); + break; + + case SubtractiveBlending: + error( 'WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true' ); + break; + + case MultiplyBlending: + error( 'WebGLState: MultiplyBlending requires material.premultipliedAlpha = true' ); + break; + + default: + error( 'WebGLState: Invalid blending: ', blending ); + break; + + } + + } + + currentBlendSrc = null; + currentBlendDst = null; + currentBlendSrcAlpha = null; + currentBlendDstAlpha = null; + currentBlendColor.set( 0, 0, 0 ); + currentBlendAlpha = 0; + + currentBlending = blending; + currentPremultipledAlpha = premultipliedAlpha; + + } + + return; + + } + + // custom blending + + blendEquationAlpha = blendEquationAlpha || blendEquation; + blendSrcAlpha = blendSrcAlpha || blendSrc; + blendDstAlpha = blendDstAlpha || blendDst; + + if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) { + + gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] ); + + currentBlendEquation = blendEquation; + currentBlendEquationAlpha = blendEquationAlpha; + + } + + if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) { + + gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] ); + + currentBlendSrc = blendSrc; + currentBlendDst = blendDst; + currentBlendSrcAlpha = blendSrcAlpha; + currentBlendDstAlpha = blendDstAlpha; + + } + + if ( blendColor.equals( currentBlendColor ) === false || blendAlpha !== currentBlendAlpha ) { + + gl.blendColor( blendColor.r, blendColor.g, blendColor.b, blendAlpha ); + + currentBlendColor.copy( blendColor ); + currentBlendAlpha = blendAlpha; + + } + + currentBlending = blending; + currentPremultipledAlpha = false; + + } + + function setMaterial( material, frontFaceCW ) { + + material.side === DoubleSide + ? disable( gl.CULL_FACE ) + : enable( gl.CULL_FACE ); + + let flipSided = ( material.side === BackSide ); + if ( frontFaceCW ) flipSided = ! flipSided; + + setFlipSided( flipSided ); + + ( material.blending === NormalBlending && material.transparent === false ) + ? setBlending( NoBlending ) + : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.blendColor, material.blendAlpha, material.premultipliedAlpha ); + + depthBuffer.setFunc( material.depthFunc ); + depthBuffer.setTest( material.depthTest ); + depthBuffer.setMask( material.depthWrite ); + colorBuffer.setMask( material.colorWrite ); + + const stencilWrite = material.stencilWrite; + stencilBuffer.setTest( stencilWrite ); + if ( stencilWrite ) { + + stencilBuffer.setMask( material.stencilWriteMask ); + stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask ); + stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass ); + + } + + setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits ); + + material.alphaToCoverage === true + ? enable( gl.SAMPLE_ALPHA_TO_COVERAGE ) + : disable( gl.SAMPLE_ALPHA_TO_COVERAGE ); + + } + + // + + function setFlipSided( flipSided ) { + + if ( currentFlipSided !== flipSided ) { + + if ( flipSided ) { + + gl.frontFace( gl.CW ); + + } else { + + gl.frontFace( gl.CCW ); + + } + + currentFlipSided = flipSided; + + } + + } + + function setCullFace( cullFace ) { + + if ( cullFace !== CullFaceNone ) { + + enable( gl.CULL_FACE ); + + if ( cullFace !== currentCullFace ) { + + if ( cullFace === CullFaceBack ) { + + gl.cullFace( gl.BACK ); + + } else if ( cullFace === CullFaceFront ) { + + gl.cullFace( gl.FRONT ); + + } else { + + gl.cullFace( gl.FRONT_AND_BACK ); + + } + + } + + } else { + + disable( gl.CULL_FACE ); + + } + + currentCullFace = cullFace; + + } + + function setLineWidth( width ) { + + if ( width !== currentLineWidth ) { + + if ( lineWidthAvailable ) gl.lineWidth( width ); + + currentLineWidth = width; + + } + + } + + function setPolygonOffset( polygonOffset, factor, units ) { + + if ( polygonOffset ) { + + enable( gl.POLYGON_OFFSET_FILL ); + + if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) { + + currentPolygonOffsetFactor = factor; + currentPolygonOffsetUnits = units; + + if ( depthBuffer.getReversed() ) { + + factor = - factor; + + } + + gl.polygonOffset( factor, units ); + + } + + } else { + + disable( gl.POLYGON_OFFSET_FILL ); + + } + + } + + function setScissorTest( scissorTest ) { + + if ( scissorTest ) { + + enable( gl.SCISSOR_TEST ); + + } else { + + disable( gl.SCISSOR_TEST ); + + } + + } + + // texture + + function activeTexture( webglSlot ) { + + if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1; + + if ( currentTextureSlot !== webglSlot ) { + + gl.activeTexture( webglSlot ); + currentTextureSlot = webglSlot; + + } + + } + + function bindTexture( webglType, webglTexture, webglSlot ) { + + if ( webglSlot === undefined ) { + + if ( currentTextureSlot === null ) { + + webglSlot = gl.TEXTURE0 + maxTextures - 1; + + } else { + + webglSlot = currentTextureSlot; + + } + + } + + let boundTexture = currentBoundTextures[ webglSlot ]; + + if ( boundTexture === undefined ) { + + boundTexture = { type: undefined, texture: undefined }; + currentBoundTextures[ webglSlot ] = boundTexture; + + } + + if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) { + + if ( currentTextureSlot !== webglSlot ) { + + gl.activeTexture( webglSlot ); + currentTextureSlot = webglSlot; + + } + + gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] ); + + boundTexture.type = webglType; + boundTexture.texture = webglTexture; + + } + + } + + function unbindTexture() { + + const boundTexture = currentBoundTextures[ currentTextureSlot ]; + + if ( boundTexture !== undefined && boundTexture.type !== undefined ) { + + gl.bindTexture( boundTexture.type, null ); + + boundTexture.type = undefined; + boundTexture.texture = undefined; + + } + + } + + function compressedTexImage2D() { + + try { + + gl.compressedTexImage2D( ...arguments ); + + } catch ( e ) { + + error( 'WebGLState:', e ); + + } + + } + + function compressedTexImage3D() { + + try { + + gl.compressedTexImage3D( ...arguments ); + + } catch ( e ) { + + error( 'WebGLState:', e ); + + } + + } + + function texSubImage2D() { + + try { + + gl.texSubImage2D( ...arguments ); + + } catch ( e ) { + + error( 'WebGLState:', e ); + + } + + } + + function texSubImage3D() { + + try { + + gl.texSubImage3D( ...arguments ); + + } catch ( e ) { + + error( 'WebGLState:', e ); + + } + + } + + function compressedTexSubImage2D() { + + try { + + gl.compressedTexSubImage2D( ...arguments ); + + } catch ( e ) { + + error( 'WebGLState:', e ); + + } + + } + + function compressedTexSubImage3D() { + + try { + + gl.compressedTexSubImage3D( ...arguments ); + + } catch ( e ) { + + error( 'WebGLState:', e ); + + } + + } + + function texStorage2D() { + + try { + + gl.texStorage2D( ...arguments ); + + } catch ( e ) { + + error( 'WebGLState:', e ); + + } + + } + + function texStorage3D() { + + try { + + gl.texStorage3D( ...arguments ); + + } catch ( e ) { + + error( 'WebGLState:', e ); + + } + + } + + function texImage2D() { + + try { + + gl.texImage2D( ...arguments ); + + } catch ( e ) { + + error( 'WebGLState:', e ); + + } + + } + + function texImage3D() { + + try { + + gl.texImage3D( ...arguments ); + + } catch ( e ) { + + error( 'WebGLState:', e ); + + } + + } + + function getParameter( name ) { + + if ( parameters[ name ] !== undefined ) { + + return parameters[ name ]; + + } else { + + return gl.getParameter( name ); + + } + + } + + function pixelStorei( name, value ) { + + if ( parameters[ name ] !== value ) { + + gl.pixelStorei( name, value ); + parameters[ name ] = value; + + } + + } + + // + + function scissor( scissor ) { + + if ( currentScissor.equals( scissor ) === false ) { + + gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w ); + currentScissor.copy( scissor ); + + } + + } + + function viewport( viewport ) { + + if ( currentViewport.equals( viewport ) === false ) { + + gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w ); + currentViewport.copy( viewport ); + + } + + } + + function updateUBOMapping( uniformsGroup, program ) { + + let mapping = uboProgramMap.get( program ); + + if ( mapping === undefined ) { + + mapping = new WeakMap(); + + uboProgramMap.set( program, mapping ); + + } + + let blockIndex = mapping.get( uniformsGroup ); + + if ( blockIndex === undefined ) { + + blockIndex = gl.getUniformBlockIndex( program, uniformsGroup.name ); + + mapping.set( uniformsGroup, blockIndex ); + + } + + } + + function uniformBlockBinding( uniformsGroup, program ) { + + const mapping = uboProgramMap.get( program ); + const blockIndex = mapping.get( uniformsGroup ); + + if ( uboBindings.get( program ) !== blockIndex ) { + + // bind shader specific block index to global block point + gl.uniformBlockBinding( program, blockIndex, uniformsGroup.__bindingPointIndex ); + + uboBindings.set( program, blockIndex ); + + } + + } + + // + + function reset() { + + // reset state + + gl.disable( gl.BLEND ); + gl.disable( gl.CULL_FACE ); + gl.disable( gl.DEPTH_TEST ); + gl.disable( gl.POLYGON_OFFSET_FILL ); + gl.disable( gl.SCISSOR_TEST ); + gl.disable( gl.STENCIL_TEST ); + gl.disable( gl.SAMPLE_ALPHA_TO_COVERAGE ); + + gl.blendEquation( gl.FUNC_ADD ); + gl.blendFunc( gl.ONE, gl.ZERO ); + gl.blendFuncSeparate( gl.ONE, gl.ZERO, gl.ONE, gl.ZERO ); + gl.blendColor( 0, 0, 0, 0 ); + + gl.colorMask( true, true, true, true ); + gl.clearColor( 0, 0, 0, 0 ); + + gl.depthMask( true ); + gl.depthFunc( gl.LESS ); + + depthBuffer.setReversed( false ); + + gl.clearDepth( 1 ); + + gl.stencilMask( 0xffffffff ); + gl.stencilFunc( gl.ALWAYS, 0, 0xffffffff ); + gl.stencilOp( gl.KEEP, gl.KEEP, gl.KEEP ); + gl.clearStencil( 0 ); + + gl.cullFace( gl.BACK ); + gl.frontFace( gl.CCW ); + + gl.polygonOffset( 0, 0 ); + + gl.activeTexture( gl.TEXTURE0 ); + + gl.bindFramebuffer( gl.FRAMEBUFFER, null ); + gl.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null ); + gl.bindFramebuffer( gl.READ_FRAMEBUFFER, null ); + + gl.useProgram( null ); + + gl.lineWidth( 1 ); + + gl.scissor( 0, 0, gl.canvas.width, gl.canvas.height ); + gl.viewport( 0, 0, gl.canvas.width, gl.canvas.height ); + + gl.pixelStorei( gl.PACK_ALIGNMENT, 4 ); + gl.pixelStorei( gl.UNPACK_ALIGNMENT, 4 ); + gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false ); + gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false ); + gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.BROWSER_DEFAULT_WEBGL ); + gl.pixelStorei( gl.PACK_ROW_LENGTH, 0 ); + gl.pixelStorei( gl.PACK_SKIP_PIXELS, 0 ); + gl.pixelStorei( gl.PACK_SKIP_ROWS, 0 ); + gl.pixelStorei( gl.UNPACK_ROW_LENGTH, 0 ); + gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, 0 ); + gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, 0 ); + gl.pixelStorei( gl.UNPACK_SKIP_ROWS, 0 ); + gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, 0 ); + + // reset internals + + enabledCapabilities = {}; + parameters = {}; + + currentTextureSlot = null; + currentBoundTextures = {}; + + currentBoundFramebuffers = {}; + currentDrawbuffers = new WeakMap(); + defaultDrawbuffers = []; + + currentProgram = null; + + currentBlendingEnabled = false; + currentBlending = null; + currentBlendEquation = null; + currentBlendSrc = null; + currentBlendDst = null; + currentBlendEquationAlpha = null; + currentBlendSrcAlpha = null; + currentBlendDstAlpha = null; + currentBlendColor = new Color( 0, 0, 0 ); + currentBlendAlpha = 0; + currentPremultipledAlpha = false; + + currentFlipSided = null; + currentCullFace = null; + + currentLineWidth = null; + + currentPolygonOffsetFactor = null; + currentPolygonOffsetUnits = null; + + currentScissor.set( 0, 0, gl.canvas.width, gl.canvas.height ); + currentViewport.set( 0, 0, gl.canvas.width, gl.canvas.height ); + + colorBuffer.reset(); + depthBuffer.reset(); + stencilBuffer.reset(); + + } + + return { + + buffers: { + color: colorBuffer, + depth: depthBuffer, + stencil: stencilBuffer + }, + + enable: enable, + disable: disable, + + bindFramebuffer: bindFramebuffer, + drawBuffers: drawBuffers, + + useProgram: useProgram, + + setBlending: setBlending, + setMaterial: setMaterial, + + setFlipSided: setFlipSided, + setCullFace: setCullFace, + + setLineWidth: setLineWidth, + setPolygonOffset: setPolygonOffset, + + setScissorTest: setScissorTest, + + activeTexture: activeTexture, + bindTexture: bindTexture, + unbindTexture: unbindTexture, + compressedTexImage2D: compressedTexImage2D, + compressedTexImage3D: compressedTexImage3D, + texImage2D: texImage2D, + texImage3D: texImage3D, + pixelStorei: pixelStorei, + getParameter: getParameter, + + updateUBOMapping: updateUBOMapping, + uniformBlockBinding: uniformBlockBinding, + + texStorage2D: texStorage2D, + texStorage3D: texStorage3D, + texSubImage2D: texSubImage2D, + texSubImage3D: texSubImage3D, + compressedTexSubImage2D: compressedTexSubImage2D, + compressedTexSubImage3D: compressedTexSubImage3D, + + scissor: scissor, + viewport: viewport, + + reset: reset + + }; + +} + +function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) { + + const multisampledRTTExt = extensions.has( 'WEBGL_multisampled_render_to_texture' ) ? extensions.get( 'WEBGL_multisampled_render_to_texture' ) : null; + const supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent ); + + const _imageDimensions = new Vector2(); + const _videoTextures = new WeakMap(); + const _htmlTextures = new Set(); + let _canvas; + + const _sources = new WeakMap(); // maps WebglTexture objects to instances of TextureSource + + // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas, + // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")! + // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d). + + let useOffscreenCanvas = false; + + try { + + useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined' + && ( new OffscreenCanvas( 1, 1 ).getContext( '2d' ) ) !== null; + + + } catch ( err ) { + + // Ignore any errors + + } + + function createCanvas( width, height ) { + + // Use OffscreenCanvas when available. Specially needed in web workers + + return useOffscreenCanvas ? + new OffscreenCanvas( width, height ) : createElementNS( 'canvas' ); + + } + + function resizeImage( image, needsNewCanvas, maxSize ) { + + let scale = 1; + + const dimensions = getDimensions( image ); + + // handle case if texture exceeds max size + + if ( dimensions.width > maxSize || dimensions.height > maxSize ) { + + scale = maxSize / Math.max( dimensions.width, dimensions.height ); + + } + + // only perform resize if necessary + + if ( scale < 1 ) { + + // only perform resize for certain image types + + if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) || + ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) || + ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) || + ( typeof VideoFrame !== 'undefined' && image instanceof VideoFrame ) ) { + + const width = Math.floor( scale * dimensions.width ); + const height = Math.floor( scale * dimensions.height ); + + if ( _canvas === undefined ) _canvas = createCanvas( width, height ); + + // cube textures can't reuse the same canvas + + const canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas; + + canvas.width = width; + canvas.height = height; + + const context = canvas.getContext( '2d' ); + context.drawImage( image, 0, 0, width, height ); + + warn( 'WebGLRenderer: Texture has been resized from (' + dimensions.width + 'x' + dimensions.height + ') to (' + width + 'x' + height + ').' ); + + return canvas; + + } else { + + if ( 'data' in image ) { + + warn( 'WebGLRenderer: Image in DataTexture is too big (' + dimensions.width + 'x' + dimensions.height + ').' ); + + } + + return image; + + } + + } + + return image; + + } + + function textureNeedsGenerateMipmaps( texture ) { + + return texture.generateMipmaps; + + } + + function generateMipmap( target ) { + + _gl.generateMipmap( target ); + + } + + function getTargetType( texture ) { + + if ( texture.isWebGLCubeRenderTarget ) return _gl.TEXTURE_CUBE_MAP; + if ( texture.isWebGL3DRenderTarget ) return _gl.TEXTURE_3D; + if ( texture.isWebGLArrayRenderTarget || texture.isCompressedArrayTexture ) return _gl.TEXTURE_2D_ARRAY; + return _gl.TEXTURE_2D; + + } + + function getInternalFormat( internalFormatName, glFormat, glType, normalized, colorSpace, forceLinearTransfer = false ) { + + if ( internalFormatName !== null ) { + + if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ]; + + warn( 'WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' ); + + } + + let ext_texture_norm16; + + if ( normalized ) { + + ext_texture_norm16 = extensions.get( 'EXT_texture_norm16' ); + + if ( ! ext_texture_norm16 ) { + + warn( 'WebGLRenderer: Unable to use normalized textures without EXT_texture_norm16 extension' ); + + } + + } + + let internalFormat = glFormat; + + if ( glFormat === _gl.RED ) { + + if ( glType === _gl.FLOAT ) internalFormat = _gl.R32F; + if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.R16F; + if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8; + if ( glType === _gl.UNSIGNED_SHORT && ext_texture_norm16 ) internalFormat = ext_texture_norm16.R16_EXT; + if ( glType === _gl.SHORT && ext_texture_norm16 ) internalFormat = ext_texture_norm16.R16_SNORM_EXT; + + } + + if ( glFormat === _gl.RED_INTEGER ) { + + if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8UI; + if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.R16UI; + if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.R32UI; + if ( glType === _gl.BYTE ) internalFormat = _gl.R8I; + if ( glType === _gl.SHORT ) internalFormat = _gl.R16I; + if ( glType === _gl.INT ) internalFormat = _gl.R32I; + + } + + if ( glFormat === _gl.RG ) { + + if ( glType === _gl.FLOAT ) internalFormat = _gl.RG32F; + if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RG16F; + if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RG8; + if ( glType === _gl.UNSIGNED_SHORT && ext_texture_norm16 ) internalFormat = ext_texture_norm16.RG16_EXT; + if ( glType === _gl.SHORT && ext_texture_norm16 ) internalFormat = ext_texture_norm16.RG16_SNORM_EXT; + + } + + if ( glFormat === _gl.RG_INTEGER ) { + + if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RG8UI; + if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.RG16UI; + if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.RG32UI; + if ( glType === _gl.BYTE ) internalFormat = _gl.RG8I; + if ( glType === _gl.SHORT ) internalFormat = _gl.RG16I; + if ( glType === _gl.INT ) internalFormat = _gl.RG32I; + + } + + if ( glFormat === _gl.RGB_INTEGER ) { + + if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RGB8UI; + if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.RGB16UI; + if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.RGB32UI; + if ( glType === _gl.BYTE ) internalFormat = _gl.RGB8I; + if ( glType === _gl.SHORT ) internalFormat = _gl.RGB16I; + if ( glType === _gl.INT ) internalFormat = _gl.RGB32I; + + } + + if ( glFormat === _gl.RGBA_INTEGER ) { + + if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RGBA8UI; + if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.RGBA16UI; + if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.RGBA32UI; + if ( glType === _gl.BYTE ) internalFormat = _gl.RGBA8I; + if ( glType === _gl.SHORT ) internalFormat = _gl.RGBA16I; + if ( glType === _gl.INT ) internalFormat = _gl.RGBA32I; + + } + + if ( glFormat === _gl.RGB ) { + + if ( glType === _gl.UNSIGNED_SHORT && ext_texture_norm16 ) internalFormat = ext_texture_norm16.RGB16_EXT; + if ( glType === _gl.SHORT && ext_texture_norm16 ) internalFormat = ext_texture_norm16.RGB16_SNORM_EXT; + if ( glType === _gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = _gl.RGB9_E5; + if ( glType === _gl.UNSIGNED_INT_10F_11F_11F_REV ) internalFormat = _gl.R11F_G11F_B10F; + + } + + if ( glFormat === _gl.RGBA ) { + + const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace ); + + if ( glType === _gl.FLOAT ) internalFormat = _gl.RGBA32F; + if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RGBA16F; + if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? _gl.SRGB8_ALPHA8 : _gl.RGBA8; + if ( glType === _gl.UNSIGNED_SHORT && ext_texture_norm16 ) internalFormat = ext_texture_norm16.RGBA16_EXT; + if ( glType === _gl.SHORT && ext_texture_norm16 ) internalFormat = ext_texture_norm16.RGBA16_SNORM_EXT; + if ( glType === _gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = _gl.RGBA4; + if ( glType === _gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = _gl.RGB5_A1; + + } + + if ( internalFormat === _gl.R16F || internalFormat === _gl.R32F || + internalFormat === _gl.RG16F || internalFormat === _gl.RG32F || + internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F ) { + + extensions.get( 'EXT_color_buffer_float' ); + + } + + return internalFormat; + + } + + function getInternalDepthFormat( useStencil, depthType ) { + + let glInternalFormat; + if ( useStencil ) { + + if ( depthType === null || depthType === UnsignedIntType || depthType === UnsignedInt248Type ) { + + glInternalFormat = _gl.DEPTH24_STENCIL8; + + } else if ( depthType === FloatType ) { + + glInternalFormat = _gl.DEPTH32F_STENCIL8; + + } else if ( depthType === UnsignedShortType ) { + + glInternalFormat = _gl.DEPTH24_STENCIL8; + warn( 'DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.' ); + + } + + } else { + + if ( depthType === null || depthType === UnsignedIntType || depthType === UnsignedInt248Type ) { + + glInternalFormat = _gl.DEPTH_COMPONENT24; + + } else if ( depthType === FloatType ) { + + glInternalFormat = _gl.DEPTH_COMPONENT32F; + + } else if ( depthType === UnsignedShortType ) { + + glInternalFormat = _gl.DEPTH_COMPONENT16; + + } + + } + + return glInternalFormat; + + } + + function getMipLevels( texture, image ) { + + if ( textureNeedsGenerateMipmaps( texture ) === true || ( texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) ) { + + return Math.log2( Math.max( image.width, image.height ) ) + 1; + + } else if ( texture.mipmaps !== undefined && texture.mipmaps.length > 0 ) { + + // user-defined mipmaps + + return texture.mipmaps.length; + + } else if ( texture.isCompressedTexture && Array.isArray( texture.image ) ) { + + return image.mipmaps.length; + + } else { + + // texture without mipmaps (only base level) + + return 1; + + } + + } + + // + + function onTextureDispose( event ) { + + const texture = event.target; + + texture.removeEventListener( 'dispose', onTextureDispose ); + + deallocateTexture( texture ); + + if ( texture.isVideoTexture ) { + + _videoTextures.delete( texture ); + + } + + if ( texture.isHTMLTexture ) { + + _htmlTextures.delete( texture ); + + } + + } + + function onRenderTargetDispose( event ) { + + const renderTarget = event.target; + + renderTarget.removeEventListener( 'dispose', onRenderTargetDispose ); + + deallocateRenderTarget( renderTarget ); + + } + + // + + function deallocateTexture( texture ) { + + const textureProperties = properties.get( texture ); + + if ( textureProperties.__webglInit === undefined ) return; + + // check if it's necessary to remove the WebGLTexture object + + const source = texture.source; + const webglTextures = _sources.get( source ); + + if ( webglTextures ) { + + const webglTexture = webglTextures[ textureProperties.__cacheKey ]; + webglTexture.usedTimes --; + + // the WebGLTexture object is not used anymore, remove it + + if ( webglTexture.usedTimes === 0 ) { + + deleteTexture( texture ); + + } + + // remove the weak map entry if no WebGLTexture uses the source anymore + + if ( Object.keys( webglTextures ).length === 0 ) { + + _sources.delete( source ); + + } + + } + + properties.remove( texture ); + + } + + function deleteTexture( texture ) { + + const textureProperties = properties.get( texture ); + _gl.deleteTexture( textureProperties.__webglTexture ); + + const source = texture.source; + const webglTextures = _sources.get( source ); + delete webglTextures[ textureProperties.__cacheKey ]; + + info.memory.textures --; + + } + + function deallocateRenderTarget( renderTarget ) { + + const renderTargetProperties = properties.get( renderTarget ); + + if ( renderTarget.depthTexture ) { + + renderTarget.depthTexture.dispose(); + + properties.remove( renderTarget.depthTexture ); + + } + + if ( renderTarget.isWebGLCubeRenderTarget ) { + + for ( let i = 0; i < 6; i ++ ) { + + if ( Array.isArray( renderTargetProperties.__webglFramebuffer[ i ] ) ) { + + for ( let level = 0; level < renderTargetProperties.__webglFramebuffer[ i ].length; level ++ ) _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ][ level ] ); + + } else { + + _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] ); + + } + + if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] ); + + } + + } else { + + if ( Array.isArray( renderTargetProperties.__webglFramebuffer ) ) { + + for ( let level = 0; level < renderTargetProperties.__webglFramebuffer.length; level ++ ) _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ level ] ); + + } else { + + _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer ); + + } + + if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer ); + if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer ); + + if ( renderTargetProperties.__webglColorRenderbuffer ) { + + for ( let i = 0; i < renderTargetProperties.__webglColorRenderbuffer.length; i ++ ) { + + if ( renderTargetProperties.__webglColorRenderbuffer[ i ] ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer[ i ] ); + + } + + } + + if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer ); + + } + + const textures = renderTarget.textures; + + for ( let i = 0, il = textures.length; i < il; i ++ ) { + + const attachmentProperties = properties.get( textures[ i ] ); + + if ( attachmentProperties.__webglTexture ) { + + _gl.deleteTexture( attachmentProperties.__webglTexture ); + + info.memory.textures --; + + } + + properties.remove( textures[ i ] ); + + } + + properties.remove( renderTarget ); + + } + + // + + let textureUnits = 0; + + function resetTextureUnits() { + + textureUnits = 0; + + } + + function getTextureUnits() { + + return textureUnits; + + } + + function setTextureUnits( value ) { + + textureUnits = value; + + } + + function allocateTextureUnit() { + + const textureUnit = textureUnits; + + if ( textureUnit >= capabilities.maxTextures ) { + + warn( 'WebGLTextures: Trying to use ' + ( textureUnit + 1 ) + ' texture units while this GPU supports only ' + capabilities.maxTextures ); + + } + + textureUnits += 1; + + return textureUnit; + + } + + function getTextureCacheKey( texture ) { + + const array = []; + + array.push( texture.wrapS ); + array.push( texture.wrapT ); + array.push( texture.wrapR || 0 ); + array.push( texture.magFilter ); + array.push( texture.minFilter ); + array.push( texture.anisotropy ); + array.push( texture.internalFormat ); + array.push( texture.format ); + array.push( texture.type ); + array.push( texture.generateMipmaps ); + array.push( texture.premultiplyAlpha ); + array.push( texture.flipY ); + array.push( texture.unpackAlignment ); + array.push( texture.colorSpace ); + + return array.join(); + + } + + // + + function setTexture2D( texture, slot ) { + + const textureProperties = properties.get( texture ); + + if ( texture.isVideoTexture ) updateVideoTexture( texture ); + + if ( texture.isRenderTargetTexture === false && texture.isExternalTexture !== true && texture.version > 0 && textureProperties.__version !== texture.version ) { + + const image = texture.image; + + if ( image === null ) { + + warn( 'WebGLRenderer: Texture marked for update but no image data found.' ); + + } else if ( image.complete === false ) { + + warn( 'WebGLRenderer: Texture marked for update but image is incomplete' ); + + } else { + + uploadTexture( textureProperties, texture, slot ); + return; + + } + + } else if ( texture.isExternalTexture ) { + + textureProperties.__webglTexture = texture.sourceTexture ? texture.sourceTexture : null; + + } + + state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot ); + + } + + function setTexture2DArray( texture, slot ) { + + const textureProperties = properties.get( texture ); + + if ( texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version ) { + + uploadTexture( textureProperties, texture, slot ); + return; + + } else if ( texture.isExternalTexture ) { + + textureProperties.__webglTexture = texture.sourceTexture ? texture.sourceTexture : null; + + } + + state.bindTexture( _gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture, _gl.TEXTURE0 + slot ); + + } + + function setTexture3D( texture, slot ) { + + const textureProperties = properties.get( texture ); + + if ( texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version ) { + + uploadTexture( textureProperties, texture, slot ); + return; + + } + + state.bindTexture( _gl.TEXTURE_3D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot ); + + } + + function setTextureCube( texture, slot ) { + + const textureProperties = properties.get( texture ); + + if ( texture.isCubeDepthTexture !== true && texture.version > 0 && textureProperties.__version !== texture.version ) { + + uploadCubeTexture( textureProperties, texture, slot ); + return; + + } + + state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot ); + + } + + const wrappingToGL = { + [ RepeatWrapping ]: _gl.REPEAT, + [ ClampToEdgeWrapping ]: _gl.CLAMP_TO_EDGE, + [ MirroredRepeatWrapping ]: _gl.MIRRORED_REPEAT + }; + + const filterToGL = { + [ NearestFilter ]: _gl.NEAREST, + [ NearestMipmapNearestFilter ]: _gl.NEAREST_MIPMAP_NEAREST, + [ NearestMipmapLinearFilter ]: _gl.NEAREST_MIPMAP_LINEAR, + + [ LinearFilter ]: _gl.LINEAR, + [ LinearMipmapNearestFilter ]: _gl.LINEAR_MIPMAP_NEAREST, + [ LinearMipmapLinearFilter ]: _gl.LINEAR_MIPMAP_LINEAR + }; + + const compareToGL = { + [ NeverCompare ]: _gl.NEVER, + [ AlwaysCompare ]: _gl.ALWAYS, + [ LessCompare ]: _gl.LESS, + [ LessEqualCompare ]: _gl.LEQUAL, + [ EqualCompare ]: _gl.EQUAL, + [ GreaterEqualCompare ]: _gl.GEQUAL, + [ GreaterCompare ]: _gl.GREATER, + [ NotEqualCompare ]: _gl.NOTEQUAL + }; + + function setTextureParameters( textureType, texture ) { + + if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false && + ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter || + texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter ) ) { + + warn( 'WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device.' ); + + } + + _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] ); + _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] ); + + if ( textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY ) { + + _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] ); + + } + + _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] ); + _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[ texture.minFilter ] ); + + if ( texture.compareFunction ) { + + _gl.texParameteri( textureType, _gl.TEXTURE_COMPARE_MODE, _gl.COMPARE_REF_TO_TEXTURE ); + _gl.texParameteri( textureType, _gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] ); + + } + + if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) { + + if ( texture.magFilter === NearestFilter ) return; + if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return; + if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension + + if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) { + + const extension = extensions.get( 'EXT_texture_filter_anisotropic' ); + _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) ); + properties.get( texture ).__currentAnisotropy = texture.anisotropy; + + } + + } + + } + + function initTexture( textureProperties, texture ) { + + let forceUpload = false; + + if ( textureProperties.__webglInit === undefined ) { + + textureProperties.__webglInit = true; + + texture.addEventListener( 'dispose', onTextureDispose ); + + } + + // create TextureSource <-> WebGLTextures mapping if necessary + + const source = texture.source; + let webglTextures = _sources.get( source ); + + if ( webglTextures === undefined ) { + + webglTextures = {}; + _sources.set( source, webglTextures ); + + } + + // check if there is already a WebGLTexture object for the given texture parameters + + const textureCacheKey = getTextureCacheKey( texture ); + + if ( textureCacheKey !== textureProperties.__cacheKey ) { + + // if not, create a new instance of WebGLTexture + + if ( webglTextures[ textureCacheKey ] === undefined ) { + + // create new entry + + webglTextures[ textureCacheKey ] = { + texture: _gl.createTexture(), + usedTimes: 0 + }; + + info.memory.textures ++; + + // when a new instance of WebGLTexture was created, a texture upload is required + // even if the image contents are identical + + forceUpload = true; + + } + + webglTextures[ textureCacheKey ].usedTimes ++; + + // every time the texture cache key changes, it's necessary to check if an instance of + // WebGLTexture can be deleted in order to avoid a memory leak. + + const webglTexture = webglTextures[ textureProperties.__cacheKey ]; + + if ( webglTexture !== undefined ) { + + webglTextures[ textureProperties.__cacheKey ].usedTimes --; + + if ( webglTexture.usedTimes === 0 ) { + + deleteTexture( texture ); + + } + + } + + // store references to cache key and WebGLTexture object + + textureProperties.__cacheKey = textureCacheKey; + textureProperties.__webglTexture = webglTextures[ textureCacheKey ].texture; + + } + + return forceUpload; + + } + + function getRow( index, rowLength, componentStride ) { + + return Math.floor( Math.floor( index / componentStride ) / rowLength ); + + } + + function updateTexture( texture, image, glFormat, glType ) { + + const componentStride = 4; // only RGBA supported + + const updateRanges = texture.updateRanges; + + if ( updateRanges.length === 0 ) { + + state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, image.width, image.height, glFormat, glType, image.data ); + + } else { + + // Before applying update ranges, we merge any adjacent / overlapping + // ranges to reduce load on `gl.texSubImage2D`. Empirically, this has led + // to performance improvements for applications which make heavy use of + // update ranges. Likely due to GPU command overhead. + // + // Note that to reduce garbage collection between frames, we merge the + // update ranges in-place. This is safe because this method will clear the + // update ranges once updated. + + updateRanges.sort( ( a, b ) => a.start - b.start ); + + // To merge the update ranges in-place, we work from left to right in the + // existing updateRanges array, merging ranges. This may result in a final + // array which is smaller than the original. This index tracks the last + // index representing a merged range, any data after this index can be + // trimmed once the merge algorithm is completed. + let mergeIndex = 0; + + for ( let i = 1; i < updateRanges.length; i ++ ) { + + const previousRange = updateRanges[ mergeIndex ]; + const range = updateRanges[ i ]; + + // Only merge if in the same row and overlapping/adjacent + const previousEnd = previousRange.start + previousRange.count; + const currentRow = getRow( range.start, image.width, componentStride ); + const previousRow = getRow( previousRange.start, image.width, componentStride ); + + // We add one here to merge adjacent ranges. This is safe because ranges + // operate over positive integers. + if ( + range.start <= previousEnd + 1 && + currentRow === previousRow && + getRow( range.start + range.count - 1, image.width, componentStride ) === currentRow // ensure range doesn't spill + ) { + + previousRange.count = Math.max( + previousRange.count, + range.start + range.count - previousRange.start + ); + + } else { + + ++ mergeIndex; + updateRanges[ mergeIndex ] = range; + + } + + + } + + // Trim the array to only contain the merged ranges. + updateRanges.length = mergeIndex + 1; + + const currentUnpackRowLen = state.getParameter( _gl.UNPACK_ROW_LENGTH ); + const currentUnpackSkipPixels = state.getParameter( _gl.UNPACK_SKIP_PIXELS ); + const currentUnpackSkipRows = state.getParameter( _gl.UNPACK_SKIP_ROWS ); + + state.pixelStorei( _gl.UNPACK_ROW_LENGTH, image.width ); + + for ( let i = 0, l = updateRanges.length; i < l; i ++ ) { + + const range = updateRanges[ i ]; + + const pixelStart = Math.floor( range.start / componentStride ); + const pixelCount = Math.ceil( range.count / componentStride ); + + const x = pixelStart % image.width; + const y = Math.floor( pixelStart / image.width ); + + // Assumes update ranges refer to contiguous memory + const width = pixelCount; + const height = 1; + + state.pixelStorei( _gl.UNPACK_SKIP_PIXELS, x ); + state.pixelStorei( _gl.UNPACK_SKIP_ROWS, y ); + + state.texSubImage2D( _gl.TEXTURE_2D, 0, x, y, width, height, glFormat, glType, image.data ); + + } + + texture.clearUpdateRanges(); + + state.pixelStorei( _gl.UNPACK_ROW_LENGTH, currentUnpackRowLen ); + state.pixelStorei( _gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels ); + state.pixelStorei( _gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows ); + + } + + } + + function uploadTexture( textureProperties, texture, slot ) { + + let textureType = _gl.TEXTURE_2D; + + if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) textureType = _gl.TEXTURE_2D_ARRAY; + if ( texture.isData3DTexture ) textureType = _gl.TEXTURE_3D; + + const forceUpload = initTexture( textureProperties, texture ); + const source = texture.source; + + state.bindTexture( textureType, textureProperties.__webglTexture, _gl.TEXTURE0 + slot ); + + const sourceProperties = properties.get( source ); + + if ( source.version !== sourceProperties.__version || forceUpload === true ) { + + state.activeTexture( _gl.TEXTURE0 + slot ); + + const isImageBitmap = ( typeof ImageBitmap !== 'undefined' && texture.image instanceof ImageBitmap ); + + if ( isImageBitmap === false ) { + + const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace ); + const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace ); + const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL; + + state.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY ); + state.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha ); + state.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion ); + + } + + state.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment ); + + let image = resizeImage( texture.image, false, capabilities.maxTextureSize ); + image = verifyColorSpace( texture, image ); + + const glFormat = utils.convert( texture.format, texture.colorSpace ); + + const glType = utils.convert( texture.type ); + let glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.normalized, texture.colorSpace, texture.isVideoTexture ); + + setTextureParameters( textureType, texture ); + + let mipmap; + const mipmaps = texture.mipmaps; + + const useTexStorage = ( texture.isVideoTexture !== true ); + const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true ); + const dataReady = source.dataReady; + const levels = getMipLevels( texture, image ); + + if ( texture.isDepthTexture ) { + + glInternalFormat = getInternalDepthFormat( texture.format === DepthStencilFormat, texture.type ); + + // + + if ( allocateMemory ) { + + if ( useTexStorage ) { + + state.texStorage2D( _gl.TEXTURE_2D, 1, glInternalFormat, image.width, image.height ); + + } else { + + state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null ); + + } + + } + + } else if ( texture.isDataTexture ) { + + // use manually created mipmaps if available + // if there are no manual mipmaps + // set 0 level mipmap and then use GL to generate other mipmap levels + + if ( mipmaps.length > 0 ) { + + if ( useTexStorage && allocateMemory ) { + + state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height ); + + } + + for ( let i = 0, il = mipmaps.length; i < il; i ++ ) { + + mipmap = mipmaps[ i ]; + + if ( useTexStorage ) { + + if ( dataReady ) { + + state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data ); + + } + + } else { + + state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); + + } + + } + + texture.generateMipmaps = false; + + } else { + + if ( useTexStorage ) { + + if ( allocateMemory ) { + + state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height ); + + } + + if ( dataReady ) { + + updateTexture( texture, image, glFormat, glType ); + + } + + } else { + + state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data ); + + } + + } + + } else if ( texture.isCompressedTexture ) { + + if ( texture.isCompressedArrayTexture ) { + + if ( useTexStorage && allocateMemory ) { + + state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height, image.depth ); + + } + + for ( let i = 0, il = mipmaps.length; i < il; i ++ ) { + + mipmap = mipmaps[ i ]; + + if ( texture.format !== RGBAFormat ) { + + if ( glFormat !== null ) { + + if ( useTexStorage ) { + + if ( dataReady ) { + + if ( texture.layerUpdates.size > 0 ) { + + const layerByteLength = getByteLength( mipmap.width, mipmap.height, texture.format, texture.type ); + + for ( const layerIndex of texture.layerUpdates ) { + + const layerData = mipmap.data.subarray( + layerIndex * layerByteLength / mipmap.data.BYTES_PER_ELEMENT, + ( layerIndex + 1 ) * layerByteLength / mipmap.data.BYTES_PER_ELEMENT + ); + state.compressedTexSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, layerIndex, mipmap.width, mipmap.height, 1, glFormat, layerData ); + + } + + } else { + + state.compressedTexSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data ); + + } + + } + + } else { + + state.compressedTexImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, mipmap.data, 0, 0 ); + + } + + } else { + + warn( 'WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' ); + + } + + } else { + + if ( useTexStorage ) { + + if ( dataReady ) { + + state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data ); + + } + + } else { + + state.texImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, glFormat, glType, mipmap.data ); + + } + + } + + } + + if ( texture.layerUpdates.size > 0 ) texture.clearLayerUpdates(); + + } else { + + if ( useTexStorage && allocateMemory ) { + + state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height ); + + } + + for ( let i = 0, il = mipmaps.length; i < il; i ++ ) { + + mipmap = mipmaps[ i ]; + + if ( texture.format !== RGBAFormat ) { + + if ( glFormat !== null ) { + + if ( useTexStorage ) { + + if ( dataReady ) { + + state.compressedTexSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data ); + + } + + } else { + + state.compressedTexImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data ); + + } + + } else { + + warn( 'WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' ); + + } + + } else { + + if ( useTexStorage ) { + + if ( dataReady ) { + + state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data ); + + } + + } else { + + state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); + + } + + } + + } + + } + + } else if ( texture.isDataArrayTexture ) { + + if ( useTexStorage ) { + + if ( allocateMemory ) { + + state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, image.width, image.height, image.depth ); + + } + + if ( dataReady ) { + + if ( texture.layerUpdates.size > 0 ) { + + const layerByteLength = getByteLength( image.width, image.height, texture.format, texture.type ); + + for ( const layerIndex of texture.layerUpdates ) { + + const layerData = image.data.subarray( + layerIndex * layerByteLength / image.data.BYTES_PER_ELEMENT, + ( layerIndex + 1 ) * layerByteLength / image.data.BYTES_PER_ELEMENT + ); + state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, 0, 0, 0, layerIndex, image.width, image.height, 1, glFormat, glType, layerData ); + + } + + texture.clearLayerUpdates(); + + } else { + + state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data ); + + } + + } + + } else { + + state.texImage3D( _gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data ); + + } + + } else if ( texture.isData3DTexture ) { + + if ( useTexStorage ) { + + if ( allocateMemory ) { + + state.texStorage3D( _gl.TEXTURE_3D, levels, glInternalFormat, image.width, image.height, image.depth ); + + } + + if ( dataReady ) { + + state.texSubImage3D( _gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data ); + + } + + } else { + + state.texImage3D( _gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data ); + + } + + } else if ( texture.isFramebufferTexture ) { + + if ( allocateMemory ) { + + if ( useTexStorage ) { + + state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height ); + + } else { + + let width = image.width, height = image.height; + + for ( let i = 0; i < levels; i ++ ) { + + state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, width, height, 0, glFormat, glType, null ); + + width >>= 1; + height >>= 1; + + } + + } + + } + + } else if ( texture.isHTMLTexture ) { + + if ( 'texElementImage2D' in _gl ) { + + const canvas = _gl.canvas; + + // Ensure the canvas supports HTML-in-Canvas and the element is a child. + if ( ! canvas.hasAttribute( 'layoutsubtree' ) ) { + + canvas.setAttribute( 'layoutsubtree', 'true' ); + + } + + if ( image.parentNode !== canvas ) { + + canvas.appendChild( image ); + + // Register and set up a shared paint callback for all HTMLTextures. + _htmlTextures.add( texture ); + + canvas.onpaint = ( event ) => { + + const changed = event.changedElements; + + for ( const t of _htmlTextures ) { + + if ( changed.includes( t.image ) ) { + + t.needsUpdate = true; + + } + + } + + }; + + canvas.requestPaint(); + return; + + } + + if ( _gl.texElementImage2D.length === 3 ) { + + // Chrome 150+ + + _gl.texElementImage2D( _gl.TEXTURE_2D, _gl.RGBA8, image ); + + } else { + + // Chrome 138 - 149 + + const level = 0; + const internalFormat = _gl.RGBA; + const srcFormat = _gl.RGBA; + const srcType = _gl.UNSIGNED_BYTE; + + _gl.texElementImage2D( _gl.TEXTURE_2D, level, internalFormat, srcFormat, srcType, image ); + + } + + _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.LINEAR ); + _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE ); + _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE ); + + } + + } else { + + // regular Texture (image, video, canvas) + + // use manually created mipmaps if available + // if there are no manual mipmaps + // set 0 level mipmap and then use GL to generate other mipmap levels + + if ( mipmaps.length > 0 ) { + + if ( useTexStorage && allocateMemory ) { + + const dimensions = getDimensions( mipmaps[ 0 ] ); + + state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height ); + + } + + for ( let i = 0, il = mipmaps.length; i < il; i ++ ) { + + mipmap = mipmaps[ i ]; + + if ( useTexStorage ) { + + if ( dataReady ) { + + state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, glFormat, glType, mipmap ); + + } + + } else { + + state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap ); + + } + + } + + texture.generateMipmaps = false; + + } else { + + if ( useTexStorage ) { + + if ( allocateMemory ) { + + const dimensions = getDimensions( image ); + + state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height ); + + } + + if ( dataReady ) { + + state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, glFormat, glType, image ); + + } + + } else { + + state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image ); + + } + + } + + } + + if ( textureNeedsGenerateMipmaps( texture ) ) { + + generateMipmap( textureType ); + + } + + sourceProperties.__version = source.version; + + if ( texture.onUpdate ) texture.onUpdate( texture ); + + } + + textureProperties.__version = texture.version; + + } + + function uploadCubeTexture( textureProperties, texture, slot ) { + + if ( texture.image.length !== 6 ) return; + + const forceUpload = initTexture( textureProperties, texture ); + const source = texture.source; + + state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot ); + + const sourceProperties = properties.get( source ); + + if ( source.version !== sourceProperties.__version || forceUpload === true ) { + + state.activeTexture( _gl.TEXTURE0 + slot ); + + const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace ); + const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace ); + const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL; + + state.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY ); + state.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha ); + state.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment ); + state.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion ); + + const isCompressed = ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture ); + const isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture ); + + const cubeImage = []; + + for ( let i = 0; i < 6; i ++ ) { + + if ( ! isCompressed && ! isDataTexture ) { + + cubeImage[ i ] = resizeImage( texture.image[ i ], true, capabilities.maxCubemapSize ); + + } else { + + cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ]; + + } + + cubeImage[ i ] = verifyColorSpace( texture, cubeImage[ i ] ); + + } + + const image = cubeImage[ 0 ], + glFormat = utils.convert( texture.format, texture.colorSpace ), + glType = utils.convert( texture.type ), + glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.normalized, texture.colorSpace ); + + const useTexStorage = ( texture.isVideoTexture !== true ); + const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true ); + const dataReady = source.dataReady; + let levels = getMipLevels( texture, image ); + + setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture ); + + let mipmaps; + + if ( isCompressed ) { + + if ( useTexStorage && allocateMemory ) { + + state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, image.width, image.height ); + + } + + for ( let i = 0; i < 6; i ++ ) { + + mipmaps = cubeImage[ i ].mipmaps; + + for ( let j = 0; j < mipmaps.length; j ++ ) { + + const mipmap = mipmaps[ j ]; + + if ( texture.format !== RGBAFormat ) { + + if ( glFormat !== null ) { + + if ( useTexStorage ) { + + if ( dataReady ) { + + state.compressedTexSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data ); + + } + + } else { + + state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data ); + + } + + } else { + + warn( 'WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' ); + + } + + } else { + + if ( useTexStorage ) { + + if ( dataReady ) { + + state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data ); + + } + + } else { + + state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); + + } + + } + + } + + } + + } else { + + mipmaps = texture.mipmaps; + + if ( useTexStorage && allocateMemory ) { + + // TODO: Uniformly handle mipmap definitions + // Normal textures and compressed cube textures define base level + mips with their mipmap array + // Uncompressed cube textures use their mipmap array only for mips (no base level) + + if ( mipmaps.length > 0 ) levels ++; + + const dimensions = getDimensions( cubeImage[ 0 ] ); + + state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, dimensions.width, dimensions.height ); + + } + + for ( let i = 0; i < 6; i ++ ) { + + if ( isDataTexture ) { + + if ( useTexStorage ) { + + if ( dataReady ) { + + state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, cubeImage[ i ].width, cubeImage[ i ].height, glFormat, glType, cubeImage[ i ].data ); + + } + + } else { + + state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data ); + + } + + for ( let j = 0; j < mipmaps.length; j ++ ) { + + const mipmap = mipmaps[ j ]; + const mipmapImage = mipmap.image[ i ].image; + + if ( useTexStorage ) { + + if ( dataReady ) { + + state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data ); + + } + + } else { + + state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data ); + + } + + } + + } else { + + if ( useTexStorage ) { + + if ( dataReady ) { + + state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, glFormat, glType, cubeImage[ i ] ); + + } + + } else { + + state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] ); + + } + + for ( let j = 0; j < mipmaps.length; j ++ ) { + + const mipmap = mipmaps[ j ]; + + if ( useTexStorage ) { + + if ( dataReady ) { + + state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, glFormat, glType, mipmap.image[ i ] ); + + } + + } else { + + state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] ); + + } + + } + + } + + } + + } + + if ( textureNeedsGenerateMipmaps( texture ) ) { + + // We assume images for cube map have the same size. + generateMipmap( _gl.TEXTURE_CUBE_MAP ); + + } + + sourceProperties.__version = source.version; + + if ( texture.onUpdate ) texture.onUpdate( texture ); + + } + + textureProperties.__version = texture.version; + + } + + // Render targets + + // Setup storage for target texture and bind it to correct framebuffer + function setupFrameBufferTexture( framebuffer, renderTarget, texture, attachment, textureTarget, level ) { + + const glFormat = utils.convert( texture.format, texture.colorSpace ); + const glType = utils.convert( texture.type ); + const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.normalized, texture.colorSpace ); + const renderTargetProperties = properties.get( renderTarget ); + const textureProperties = properties.get( texture ); + + textureProperties.__renderTarget = renderTarget; + + if ( ! renderTargetProperties.__hasExternalTextures ) { + + const width = Math.max( 1, renderTarget.width >> level ); + const height = Math.max( 1, renderTarget.height >> level ); + + if ( textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY ) { + + state.texImage3D( textureTarget, level, glInternalFormat, width, height, renderTarget.depth, 0, glFormat, glType, null ); + + } else { + + state.texImage2D( textureTarget, level, glInternalFormat, width, height, 0, glFormat, glType, null ); + + } + + } + + state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); + + if ( useMultisampledRTT( renderTarget ) ) { + + multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, attachment, textureTarget, textureProperties.__webglTexture, 0, getRenderTargetSamples( renderTarget ) ); + + } else if ( textureTarget === _gl.TEXTURE_2D || ( textureTarget >= _gl.TEXTURE_CUBE_MAP_POSITIVE_X && textureTarget <= _gl.TEXTURE_CUBE_MAP_NEGATIVE_Z ) ) { // see #24753 + + _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, textureProperties.__webglTexture, level ); + + } + + state.bindFramebuffer( _gl.FRAMEBUFFER, null ); + + } + + // Setup storage for internal depth/stencil buffers and bind to correct framebuffer + function setupRenderBufferStorage( renderbuffer, renderTarget, useMultisample ) { + + _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer ); + + if ( renderTarget.depthBuffer ) { + + // retrieve the depth attachment types + const depthTexture = renderTarget.depthTexture; + const depthType = depthTexture && depthTexture.isDepthTexture ? depthTexture.type : null; + const glInternalFormat = getInternalDepthFormat( renderTarget.stencilBuffer, depthType ); + const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT; + + // set up the attachment + if ( useMultisampledRTT( renderTarget ) ) { + + multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, getRenderTargetSamples( renderTarget ), glInternalFormat, renderTarget.width, renderTarget.height ); + + } else if ( useMultisample ) { + + _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, getRenderTargetSamples( renderTarget ), glInternalFormat, renderTarget.width, renderTarget.height ); + + } else { + + _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height ); + + } + + _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer ); + + } else { + + const textures = renderTarget.textures; + + for ( let i = 0; i < textures.length; i ++ ) { + + const texture = textures[ i ]; + + const glFormat = utils.convert( texture.format, texture.colorSpace ); + const glType = utils.convert( texture.type ); + const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.normalized, texture.colorSpace ); + + if ( useMultisampledRTT( renderTarget ) ) { + + multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, getRenderTargetSamples( renderTarget ), glInternalFormat, renderTarget.width, renderTarget.height ); + + } else if ( useMultisample ) { + + _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, getRenderTargetSamples( renderTarget ), glInternalFormat, renderTarget.width, renderTarget.height ); + + } else { + + _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height ); + + } + + } + + } + + _gl.bindRenderbuffer( _gl.RENDERBUFFER, null ); + + } + + // Setup resources for a Depth Texture for a FBO (needs an extension) + function setupDepthTexture( framebuffer, renderTarget, cubeFace ) { + + const isCube = ( renderTarget.isWebGLCubeRenderTarget === true ); + + state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); + + if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) { + + throw new Error( 'THREE.WebGLTextures: renderTarget.depthTexture must be an instance of THREE.DepthTexture.' ); + + } + + const textureProperties = properties.get( renderTarget.depthTexture ); + textureProperties.__renderTarget = renderTarget; + + // upload an empty depth texture with framebuffer size + if ( ! textureProperties.__webglTexture || + renderTarget.depthTexture.image.width !== renderTarget.width || + renderTarget.depthTexture.image.height !== renderTarget.height ) { + + renderTarget.depthTexture.image.width = renderTarget.width; + renderTarget.depthTexture.image.height = renderTarget.height; + renderTarget.depthTexture.needsUpdate = true; + + } + + if ( isCube ) { + + // For cube depth textures, initialize and bind without uploading image data + if ( textureProperties.__webglInit === undefined ) { + + textureProperties.__webglInit = true; + renderTarget.depthTexture.addEventListener( 'dispose', onTextureDispose ); + + } + + // Only create and allocate storage once + if ( textureProperties.__webglTexture === undefined ) { + + textureProperties.__webglTexture = _gl.createTexture(); + + state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture ); + setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget.depthTexture ); + + // Allocate storage for all 6 faces with correct depth texture format + const glFormat = utils.convert( renderTarget.depthTexture.format ); + const glType = utils.convert( renderTarget.depthTexture.type ); + + // Use proper internal format for depth textures + let glInternalFormat; + if ( renderTarget.depthTexture.format === DepthFormat ) { + + glInternalFormat = _gl.DEPTH_COMPONENT24; + + } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) { + + glInternalFormat = _gl.DEPTH24_STENCIL8; + + } + + for ( let i = 0; i < 6; i ++ ) { + + _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null ); + + } + + } + + } else { + + setTexture2D( renderTarget.depthTexture, 0 ); + + } + + const webglDepthTexture = textureProperties.__webglTexture; + const samples = getRenderTargetSamples( renderTarget ); + + const glTextureType = isCube ? _gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace : _gl.TEXTURE_2D; + const glAttachmentType = renderTarget.depthTexture.format === DepthStencilFormat ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT; + + if ( renderTarget.depthTexture.format === DepthFormat ) { + + if ( useMultisampledRTT( renderTarget ) ) { + + multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, glAttachmentType, glTextureType, webglDepthTexture, 0, samples ); + + } else { + + _gl.framebufferTexture2D( _gl.FRAMEBUFFER, glAttachmentType, glTextureType, webglDepthTexture, 0 ); + + } + + } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) { + + if ( useMultisampledRTT( renderTarget ) ) { + + multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, glAttachmentType, glTextureType, webglDepthTexture, 0, samples ); + + } else { + + _gl.framebufferTexture2D( _gl.FRAMEBUFFER, glAttachmentType, glTextureType, webglDepthTexture, 0 ); + + } + + } else { + + throw new Error( 'THREE.WebGLTextures: Unknown depthTexture format.' ); + + } + + } + + // Setup GL resources for a non-texture depth buffer + function setupDepthRenderbuffer( renderTarget ) { + + const renderTargetProperties = properties.get( renderTarget ); + const isCube = ( renderTarget.isWebGLCubeRenderTarget === true ); + + // if the bound depth texture has changed + if ( renderTargetProperties.__boundDepthTexture !== renderTarget.depthTexture ) { + + // fire the dispose event to get rid of stored state associated with the previously bound depth buffer + const depthTexture = renderTarget.depthTexture; + if ( renderTargetProperties.__depthDisposeCallback ) { + + renderTargetProperties.__depthDisposeCallback(); + + } + + // set up dispose listeners to track when the currently attached buffer is implicitly unbound + if ( depthTexture ) { + + const disposeEvent = () => { + + delete renderTargetProperties.__boundDepthTexture; + delete renderTargetProperties.__depthDisposeCallback; + depthTexture.removeEventListener( 'dispose', disposeEvent ); + + }; + + depthTexture.addEventListener( 'dispose', disposeEvent ); + renderTargetProperties.__depthDisposeCallback = disposeEvent; + + } + + renderTargetProperties.__boundDepthTexture = depthTexture; + + } + + if ( renderTarget.depthTexture && ! renderTargetProperties.__autoAllocateDepthBuffer ) { + + if ( isCube ) { + + // For cube render targets with depth texture, setup each face + for ( let i = 0; i < 6; i ++ ) { + + setupDepthTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, i ); + + } + + } else { + + const mipmaps = renderTarget.texture.mipmaps; + + if ( mipmaps && mipmaps.length > 0 ) { + + setupDepthTexture( renderTargetProperties.__webglFramebuffer[ 0 ], renderTarget, 0 ); + + } else { + + setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget, 0 ); + + } + + } + + } else { + + if ( isCube ) { + + renderTargetProperties.__webglDepthbuffer = []; + + for ( let i = 0; i < 6; i ++ ) { + + state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] ); + + if ( renderTargetProperties.__webglDepthbuffer[ i ] === undefined ) { + + renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer(); + setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false ); + + } else { + + // attach buffer if it's been created already + const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT; + const renderbuffer = renderTargetProperties.__webglDepthbuffer[ i ]; + _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer ); + _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer ); + + } + + } + + } else { + + const mipmaps = renderTarget.texture.mipmaps; + + if ( mipmaps && mipmaps.length > 0 ) { + + state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ 0 ] ); + + } else { + + state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer ); + + } + + if ( renderTargetProperties.__webglDepthbuffer === undefined ) { + + renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer(); + setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false ); + + } else { + + // attach buffer if it's been created already + const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT; + const renderbuffer = renderTargetProperties.__webglDepthbuffer; + _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer ); + _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer ); + + } + + } + + } + + state.bindFramebuffer( _gl.FRAMEBUFFER, null ); + + } + + // rebind framebuffer with external textures + function rebindTextures( renderTarget, colorTexture, depthTexture ) { + + const renderTargetProperties = properties.get( renderTarget ); + + if ( colorTexture !== undefined ) { + + setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, 0 ); + + } + + if ( depthTexture !== undefined ) { + + setupDepthRenderbuffer( renderTarget ); + + } + + } + + // Set up GL resources for the render target + function setupRenderTarget( renderTarget ) { + + const texture = renderTarget.texture; + + const renderTargetProperties = properties.get( renderTarget ); + const textureProperties = properties.get( texture ); + + renderTarget.addEventListener( 'dispose', onRenderTargetDispose ); + + const textures = renderTarget.textures; + + const isCube = ( renderTarget.isWebGLCubeRenderTarget === true ); + const isMultipleRenderTargets = ( textures.length > 1 ); + + if ( ! isMultipleRenderTargets ) { + + if ( textureProperties.__webglTexture === undefined ) { + + textureProperties.__webglTexture = _gl.createTexture(); + + } + + textureProperties.__version = texture.version; + info.memory.textures ++; + + } + + // Setup framebuffer + + if ( isCube ) { + + renderTargetProperties.__webglFramebuffer = []; + + for ( let i = 0; i < 6; i ++ ) { + + if ( texture.mipmaps && texture.mipmaps.length > 0 ) { + + renderTargetProperties.__webglFramebuffer[ i ] = []; + + for ( let level = 0; level < texture.mipmaps.length; level ++ ) { + + renderTargetProperties.__webglFramebuffer[ i ][ level ] = _gl.createFramebuffer(); + + } + + } else { + + renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer(); + + } + + } + + } else { + + if ( texture.mipmaps && texture.mipmaps.length > 0 ) { + + renderTargetProperties.__webglFramebuffer = []; + + for ( let level = 0; level < texture.mipmaps.length; level ++ ) { + + renderTargetProperties.__webglFramebuffer[ level ] = _gl.createFramebuffer(); + + } + + } else { + + renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer(); + + } + + if ( isMultipleRenderTargets ) { + + for ( let i = 0, il = textures.length; i < il; i ++ ) { + + const attachmentProperties = properties.get( textures[ i ] ); + + if ( attachmentProperties.__webglTexture === undefined ) { + + attachmentProperties.__webglTexture = _gl.createTexture(); + + info.memory.textures ++; + + } + + } + + } + + if ( ( renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) { + + renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer(); + renderTargetProperties.__webglColorRenderbuffer = []; + + state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer ); + + for ( let i = 0; i < textures.length; i ++ ) { + + const texture = textures[ i ]; + renderTargetProperties.__webglColorRenderbuffer[ i ] = _gl.createRenderbuffer(); + + _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] ); + + const glFormat = utils.convert( texture.format, texture.colorSpace ); + const glType = utils.convert( texture.type ); + const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.normalized, texture.colorSpace, renderTarget.isXRRenderTarget === true ); + const samples = getRenderTargetSamples( renderTarget ); + _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height ); + + _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] ); + + } + + _gl.bindRenderbuffer( _gl.RENDERBUFFER, null ); + + if ( renderTarget.depthBuffer ) { + + renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer(); + setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true ); + + } + + state.bindFramebuffer( _gl.FRAMEBUFFER, null ); + + } + + } + + // Setup color buffer + + if ( isCube ) { + + state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture ); + setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture ); + + for ( let i = 0; i < 6; i ++ ) { + + if ( texture.mipmaps && texture.mipmaps.length > 0 ) { + + for ( let level = 0; level < texture.mipmaps.length; level ++ ) { + + setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ][ level ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level ); + + } + + } else { + + setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0 ); + + } + + } + + if ( textureNeedsGenerateMipmaps( texture ) ) { + + generateMipmap( _gl.TEXTURE_CUBE_MAP ); + + } + + state.unbindTexture(); + + } else if ( isMultipleRenderTargets ) { + + for ( let i = 0, il = textures.length; i < il; i ++ ) { + + const attachment = textures[ i ]; + const attachmentProperties = properties.get( attachment ); + + let glTextureType = _gl.TEXTURE_2D; + + if ( renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget ) { + + glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY; + + } + + state.bindTexture( glTextureType, attachmentProperties.__webglTexture ); + setTextureParameters( glTextureType, attachment ); + setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, glTextureType, 0 ); + + if ( textureNeedsGenerateMipmaps( attachment ) ) { + + generateMipmap( glTextureType ); + + } + + } + + state.unbindTexture(); + + } else { + + let glTextureType = _gl.TEXTURE_2D; + + if ( renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget ) { + + glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY; + + } + + state.bindTexture( glTextureType, textureProperties.__webglTexture ); + setTextureParameters( glTextureType, texture ); + + if ( texture.mipmaps && texture.mipmaps.length > 0 ) { + + for ( let level = 0; level < texture.mipmaps.length; level ++ ) { + + setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ level ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, level ); + + } + + } else { + + setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, 0 ); + + } + + if ( textureNeedsGenerateMipmaps( texture ) ) { + + generateMipmap( glTextureType ); + + } + + state.unbindTexture(); + + } + + // Setup depth and stencil buffers + + if ( renderTarget.depthBuffer ) { + + setupDepthRenderbuffer( renderTarget ); + + } + + } + + function updateRenderTargetMipmap( renderTarget ) { + + const textures = renderTarget.textures; + + for ( let i = 0, il = textures.length; i < il; i ++ ) { + + const texture = textures[ i ]; + + if ( textureNeedsGenerateMipmaps( texture ) ) { + + const targetType = getTargetType( renderTarget ); + const webglTexture = properties.get( texture ).__webglTexture; + + state.bindTexture( targetType, webglTexture ); + generateMipmap( targetType ); + state.unbindTexture(); + + } + + } + + } + + const invalidationArrayRead = []; + const invalidationArrayDraw = []; + + function updateMultisampleRenderTarget( renderTarget ) { + + if ( renderTarget.samples > 0 ) { + + if ( useMultisampledRTT( renderTarget ) === false ) { + + const textures = renderTarget.textures; + const width = renderTarget.width; + const height = renderTarget.height; + let mask = _gl.COLOR_BUFFER_BIT; + const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT; + const renderTargetProperties = properties.get( renderTarget ); + const isMultipleRenderTargets = ( textures.length > 1 ); + + // If MRT we need to remove FBO attachments + if ( isMultipleRenderTargets ) { + + for ( let i = 0; i < textures.length; i ++ ) { + + state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer ); + _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, null ); + + state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer ); + _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, null, 0 ); + + } + + } + + state.bindFramebuffer( _gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer ); + + const mipmaps = renderTarget.texture.mipmaps; + + if ( mipmaps && mipmaps.length > 0 ) { + + state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ 0 ] ); + + } else { + + state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer ); + + } + + for ( let i = 0; i < textures.length; i ++ ) { + + if ( renderTarget.resolveDepthBuffer ) { + + if ( renderTarget.depthBuffer ) mask |= _gl.DEPTH_BUFFER_BIT; + + // resolving stencil is slow with a D3D backend. disable it for all transmission render targets (see #27799) + + if ( renderTarget.stencilBuffer && renderTarget.resolveStencilBuffer ) mask |= _gl.STENCIL_BUFFER_BIT; + + } + + if ( isMultipleRenderTargets ) { + + _gl.framebufferRenderbuffer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] ); + + const webglTexture = properties.get( textures[ i ] ).__webglTexture; + _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, webglTexture, 0 ); + + } + + _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST ); + + if ( supportsInvalidateFramebuffer === true ) { + + invalidationArrayRead.length = 0; + invalidationArrayDraw.length = 0; + + invalidationArrayRead.push( _gl.COLOR_ATTACHMENT0 + i ); + + if ( renderTarget.depthBuffer && renderTarget.storeMultisampledDepthBuffer === false ) { + + invalidationArrayRead.push( depthStyle ); + invalidationArrayDraw.push( depthStyle ); + + _gl.invalidateFramebuffer( _gl.DRAW_FRAMEBUFFER, invalidationArrayDraw ); + + } + + _gl.invalidateFramebuffer( _gl.READ_FRAMEBUFFER, invalidationArrayRead ); + + } + + } + + state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null ); + state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null ); + + // If MRT since pre-blit we removed the FBO we need to reconstruct the attachments + if ( isMultipleRenderTargets ) { + + for ( let i = 0; i < textures.length; i ++ ) { + + state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer ); + _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] ); + + const webglTexture = properties.get( textures[ i ] ).__webglTexture; + + state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer ); + _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, webglTexture, 0 ); + + } + + } + + state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer ); + + } else { + + if ( renderTarget.depthBuffer && renderTarget.storeMultisampledDepthBuffer === false && supportsInvalidateFramebuffer ) { + + const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT; + + _gl.invalidateFramebuffer( _gl.DRAW_FRAMEBUFFER, [ depthStyle ] ); + + } + + } + + } + + } + + function getRenderTargetSamples( renderTarget ) { + + return Math.min( capabilities.maxSamples, renderTarget.samples ); + + } + + function useMultisampledRTT( renderTarget ) { + + const renderTargetProperties = properties.get( renderTarget ); + + return renderTarget.samples > 0 && extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTargetProperties.__useRenderToTexture !== false; + + } + + function updateVideoTexture( texture ) { + + const frame = info.render.frame; + + // Check the last frame we updated the VideoTexture + + if ( _videoTextures.get( texture ) !== frame ) { + + _videoTextures.set( texture, frame ); + texture.update(); + + } + + } + + function verifyColorSpace( texture, image ) { + + const colorSpace = texture.colorSpace; + const format = texture.format; + const type = texture.type; + + if ( texture.isCompressedTexture === true || texture.isVideoTexture === true ) return image; + + if ( colorSpace !== LinearSRGBColorSpace && colorSpace !== NoColorSpace ) { + + // sRGB + + if ( ColorManagement.getTransfer( colorSpace ) === SRGBTransfer ) { + + // in WebGL 2 uncompressed textures can only be sRGB encoded if they have the RGBA8 format + + if ( format !== RGBAFormat || type !== UnsignedByteType ) { + + warn( 'WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.' ); + + } + + } else { + + error( 'WebGLTextures: Unsupported texture color space:', colorSpace ); + + } + + } + + return image; + + } + + function getDimensions( image ) { + + if ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) { + + // if intrinsic data are not available, fallback to width/height + + _imageDimensions.width = image.naturalWidth || image.width; + _imageDimensions.height = image.naturalHeight || image.height; + + } else if ( typeof VideoFrame !== 'undefined' && image instanceof VideoFrame ) { + + _imageDimensions.width = image.displayWidth; + _imageDimensions.height = image.displayHeight; + + } else { + + _imageDimensions.width = image.width; + _imageDimensions.height = image.height; + + } + + return _imageDimensions; + + } + + // + + this.allocateTextureUnit = allocateTextureUnit; + this.resetTextureUnits = resetTextureUnits; + this.getTextureUnits = getTextureUnits; + this.setTextureUnits = setTextureUnits; + + this.setTexture2D = setTexture2D; + this.setTexture2DArray = setTexture2DArray; + this.setTexture3D = setTexture3D; + this.setTextureCube = setTextureCube; + this.rebindTextures = rebindTextures; + this.setupRenderTarget = setupRenderTarget; + this.updateRenderTargetMipmap = updateRenderTargetMipmap; + this.updateMultisampleRenderTarget = updateMultisampleRenderTarget; + this.setupDepthRenderbuffer = setupDepthRenderbuffer; + this.setupFrameBufferTexture = setupFrameBufferTexture; + this.useMultisampledRTT = useMultisampledRTT; + + this.isReversedDepthBuffer = function () { + + return state.buffers.depth.getReversed(); + + }; + +} + +function WebGLUtils( gl, extensions ) { + + function convert( p, colorSpace = NoColorSpace ) { + + let extension; + + const transfer = ColorManagement.getTransfer( colorSpace ); + + if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE; + if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4; + if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1; + if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV; + if ( p === UnsignedInt101111Type ) return gl.UNSIGNED_INT_10F_11F_11F_REV; + + if ( p === ByteType ) return gl.BYTE; + if ( p === ShortType ) return gl.SHORT; + if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT; + if ( p === IntType ) return gl.INT; + if ( p === UnsignedIntType ) return gl.UNSIGNED_INT; + if ( p === FloatType ) return gl.FLOAT; + if ( p === HalfFloatType ) return gl.HALF_FLOAT; + + if ( p === AlphaFormat ) return gl.ALPHA; + if ( p === RGBFormat ) return gl.RGB; + if ( p === RGBAFormat ) return gl.RGBA; + if ( p === DepthFormat ) return gl.DEPTH_COMPONENT; + if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL; + + // WebGL2 formats. + + if ( p === RedFormat ) return gl.RED; + if ( p === RedIntegerFormat ) return gl.RED_INTEGER; + if ( p === RGFormat ) return gl.RG; + if ( p === RGIntegerFormat ) return gl.RG_INTEGER; + if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER; + + // S3TC + + if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) { + + if ( transfer === SRGBTransfer ) { + + extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' ); + + if ( extension !== null ) { + + if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT; + if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT; + if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT; + if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT; + + } else { + + return null; + + } + + } else { + + extension = extensions.get( 'WEBGL_compressed_texture_s3tc' ); + + if ( extension !== null ) { + + if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT; + if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT; + if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT; + if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT; + + } else { + + return null; + + } + + } + + } + + // PVRTC + + if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) { + + extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' ); + + if ( extension !== null ) { + + if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG; + if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG; + if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG; + if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG; + + } else { + + return null; + + } + + } + + // ETC + + if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format || p === R11_EAC_Format || p === SIGNED_R11_EAC_Format || p === RG11_EAC_Format || p === SIGNED_RG11_EAC_Format ) { + + extension = extensions.get( 'WEBGL_compressed_texture_etc' ); + + if ( extension !== null ) { + + if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2; + if ( p === RGBA_ETC2_EAC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC; + if ( p === R11_EAC_Format ) return extension.COMPRESSED_R11_EAC; + if ( p === SIGNED_R11_EAC_Format ) return extension.COMPRESSED_SIGNED_R11_EAC; + if ( p === RG11_EAC_Format ) return extension.COMPRESSED_RG11_EAC; + if ( p === SIGNED_RG11_EAC_Format ) return extension.COMPRESSED_SIGNED_RG11_EAC; + + } else { + + return null; + + } + + } + + // ASTC + + if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format || + p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format || + p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format || + p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format || + p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) { + + extension = extensions.get( 'WEBGL_compressed_texture_astc' ); + + if ( extension !== null ) { + + if ( p === RGBA_ASTC_4x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR; + if ( p === RGBA_ASTC_5x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR; + if ( p === RGBA_ASTC_5x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR; + if ( p === RGBA_ASTC_6x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR; + if ( p === RGBA_ASTC_6x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR; + if ( p === RGBA_ASTC_8x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR; + if ( p === RGBA_ASTC_8x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR; + if ( p === RGBA_ASTC_8x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR; + if ( p === RGBA_ASTC_10x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR; + if ( p === RGBA_ASTC_10x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR; + if ( p === RGBA_ASTC_10x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR; + if ( p === RGBA_ASTC_10x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR; + if ( p === RGBA_ASTC_12x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR; + if ( p === RGBA_ASTC_12x12_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR; + + } else { + + return null; + + } + + } + + // BPTC + + if ( p === RGBA_BPTC_Format || p === RGB_BPTC_SIGNED_Format || p === RGB_BPTC_UNSIGNED_Format ) { + + extension = extensions.get( 'EXT_texture_compression_bptc' ); + + if ( extension !== null ) { + + if ( p === RGBA_BPTC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT; + if ( p === RGB_BPTC_SIGNED_Format ) return extension.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT; + if ( p === RGB_BPTC_UNSIGNED_Format ) return extension.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT; + + } else { + + return null; + + } + + } + + // RGTC + + if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) { + + extension = extensions.get( 'EXT_texture_compression_rgtc' ); + + if ( extension !== null ) { + + if ( p === RED_RGTC1_Format ) return extension.COMPRESSED_RED_RGTC1_EXT; + if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT; + if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT; + if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT; + + } else { + + return null; + + } + + } + + // + + if ( p === UnsignedInt248Type ) return gl.UNSIGNED_INT_24_8; + + // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats) + + return ( gl[ p ] !== undefined ) ? gl[ p ] : null; + + } + + return { convert: convert }; + +} + +const _occlusion_vertex = ` +void main() { + + gl_Position = vec4( position, 1.0 ); + +}`; + +const _occlusion_fragment = ` +uniform sampler2DArray depthColor; +uniform float depthWidth; +uniform float depthHeight; + +void main() { + + vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight ); + + if ( coord.x >= 1.0 ) { + + gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r; + + } else { + + gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r; + + } + +}`; + +/** + * A XR module that manages the access to the Depth Sensing API. + */ +class WebXRDepthSensing { + + /** + * Constructs a new depth sensing module. + */ + constructor() { + + /** + * An opaque texture representing the depth of the user's environment. + * + * @type {?ExternalTexture} + */ + this.texture = null; + + /** + * A plane mesh for visualizing the depth texture. + * + * @type {?Mesh} + */ + this.mesh = null; + + /** + * The depth near value. + * + * @type {number} + */ + this.depthNear = 0; + + /** + * The depth near far. + * + * @type {number} + */ + this.depthFar = 0; + + } + + /** + * Inits the depth sensing module + * + * @param {XRWebGLDepthInformation} depthData - The XR depth data. + * @param {XRRenderState} renderState - The XR render state. + */ + init( depthData, renderState ) { + + if ( this.texture === null ) { + + const texture = new ExternalTexture( depthData.texture ); + + if ( ( depthData.depthNear !== renderState.depthNear ) || ( depthData.depthFar !== renderState.depthFar ) ) { + + this.depthNear = depthData.depthNear; + this.depthFar = depthData.depthFar; + + } + + this.texture = texture; + + } + + } + + /** + * Returns a plane mesh that visualizes the depth texture. + * + * @param {ArrayCamera} cameraXR - The XR camera. + * @return {?Mesh} The plane mesh. + */ + getMesh( cameraXR ) { + + if ( this.texture !== null ) { + + if ( this.mesh === null ) { + + const viewport = cameraXR.cameras[ 0 ].viewport; + const material = new ShaderMaterial( { + vertexShader: _occlusion_vertex, + fragmentShader: _occlusion_fragment, + uniforms: { + depthColor: { value: this.texture }, + depthWidth: { value: viewport.z }, + depthHeight: { value: viewport.w } + } + } ); + + this.mesh = new Mesh( new PlaneGeometry( 20, 20 ), material ); + + } + + } + + return this.mesh; + + } + + /** + * Resets the module + */ + reset() { + + this.texture = null; + this.mesh = null; + + } + + /** + * Returns a texture representing the depth of the user's environment. + * + * @return {?ExternalTexture} The depth texture. + */ + getDepthTexture() { + + return this.texture; + + } + +} + +/** + * This class represents an abstraction of the WebXR Device API and is + * internally used by {@link WebGLRenderer}. `WebXRManager` also provides a public + * interface that allows users to enable/disable XR and perform XR related + * tasks like for instance retrieving controllers. + * + * @augments EventDispatcher + * @hideconstructor + */ +class WebXRManager extends EventDispatcher { + + /** + * Constructs a new WebGL renderer. + * + * @param {WebGLRenderer} renderer - The renderer. + * @param {WebGL2RenderingContext} gl - The rendering context. + */ + constructor( renderer, gl ) { + + super(); + + const scope = this; + + let session = null; + + let framebufferScaleFactor = 1.0; + + let referenceSpace = null; + let referenceSpaceType = 'local-floor'; + // Set default foveation to maximum. + let foveation = 1.0; + let customReferenceSpace = null; + + let pose = null; + let glBinding = null; + let glProjLayer = null; + let glBaseLayer = null; + let xrFrame = null; + + const supportsGlBinding = typeof XRWebGLBinding !== 'undefined'; + + const depthSensing = new WebXRDepthSensing(); + const cameraAccessTextures = {}; + const attributes = gl.getContextAttributes(); + + let initialRenderTarget = null; + let newRenderTarget = null; + + const controllers = []; + const controllerInputSources = []; + + const currentSize = new Vector2(); + let currentPixelRatio = null; + let currentCameraSettings = null; + + // + + const cameraL = new PerspectiveCamera(); + cameraL.viewport = new Vector4(); + + const cameraR = new PerspectiveCamera(); + cameraR.viewport = new Vector4(); + + const cameras = [ cameraL, cameraR ]; + + const cameraXR = new ArrayCamera(); + + let _currentDepthNear = null; + let _currentDepthFar = null; + + // + + /** + * Whether the manager's XR camera should be automatically updated or not. + * + * @type {boolean} + * @default true + */ + this.cameraAutoUpdate = true; + + /** + * This flag notifies the renderer to be ready for XR rendering. Set it to `true` + * if you are going to use XR in your app. + * + * @type {boolean} + * @default false + */ + this.enabled = false; + + /** + * Whether XR presentation is active or not. + * + * @type {boolean} + * @readonly + * @default false + */ + this.isPresenting = false; + + /** + * Returns a group representing the `target ray` space of the XR controller. + * Use this space for visualizing 3D objects that support the user in pointing + * tasks like UI interaction. + * + * @param {number} index - The index of the controller. + * @return {Group} A group representing the `target ray` space. + */ + this.getController = function ( index ) { + + let controller = controllers[ index ]; + + if ( controller === undefined ) { + + controller = new WebXRController(); + controllers[ index ] = controller; + + } + + return controller.getTargetRaySpace(); + + }; + + /** + * Returns a group representing the `grip` space of the XR controller. + * Use this space for visualizing 3D objects that support the user in pointing + * tasks like UI interaction. + * + * Note: If you want to show something in the user's hand AND offer a + * pointing ray at the same time, you'll want to attached the handheld object + * to the group returned by `getControllerGrip()` and the ray to the + * group returned by `getController()`. The idea is to have two + * different groups in two different coordinate spaces for the same WebXR + * controller. + * + * @param {number} index - The index of the controller. + * @return {Group} A group representing the `grip` space. + */ + this.getControllerGrip = function ( index ) { + + let controller = controllers[ index ]; + + if ( controller === undefined ) { + + controller = new WebXRController(); + controllers[ index ] = controller; + + } + + return controller.getGripSpace(); + + }; + + /** + * Returns a group representing the `hand` space of the XR controller. + * Use this space for visualizing 3D objects that support the user in pointing + * tasks like UI interaction. + * + * @param {number} index - The index of the controller. + * @return {Group} A group representing the `hand` space. + */ + this.getHand = function ( index ) { + + let controller = controllers[ index ]; + + if ( controller === undefined ) { + + controller = new WebXRController(); + controllers[ index ] = controller; + + } + + return controller.getHandSpace(); + + }; + + // + + function onSessionEvent( event ) { + + const controllerIndex = controllerInputSources.indexOf( event.inputSource ); + + if ( controllerIndex === -1 ) { + + return; + + } + + const controller = controllers[ controllerIndex ]; + + if ( controller !== undefined ) { + + controller.update( event.inputSource, event.frame, customReferenceSpace || referenceSpace ); + controller.dispatchEvent( { type: event.type, data: event.inputSource } ); + + } + + } + + function onSessionEnd() { + + session.removeEventListener( 'select', onSessionEvent ); + session.removeEventListener( 'selectstart', onSessionEvent ); + session.removeEventListener( 'selectend', onSessionEvent ); + session.removeEventListener( 'squeeze', onSessionEvent ); + session.removeEventListener( 'squeezestart', onSessionEvent ); + session.removeEventListener( 'squeezeend', onSessionEvent ); + session.removeEventListener( 'end', onSessionEnd ); + session.removeEventListener( 'inputsourceschange', onInputSourcesChange ); + + for ( let i = 0; i < controllers.length; i ++ ) { + + const inputSource = controllerInputSources[ i ]; + + if ( inputSource === null ) continue; + + controllerInputSources[ i ] = null; + + controllers[ i ].disconnect( inputSource ); + + } + + _currentDepthNear = null; + _currentDepthFar = null; + + depthSensing.reset(); + for ( const key in cameraAccessTextures ) { + + delete cameraAccessTextures[ key ]; + + } + + // restore framebuffer/rendering state + + renderer.setRenderTarget( initialRenderTarget ); + + glBaseLayer = null; + glProjLayer = null; + glBinding = null; + session = null; + newRenderTarget = null; + + // + + animation.stop(); + + scope.isPresenting = false; + + renderer.setPixelRatio( currentPixelRatio ); + renderer.setSize( currentSize.width, currentSize.height, false ); + + if ( currentCameraSettings !== null ) { + + const camera = currentCameraSettings.camera; + + camera.fov = currentCameraSettings.fov; + camera.zoom = currentCameraSettings.zoom; + camera.updateProjectionMatrix(); + + currentCameraSettings = null; + + } + + scope.dispatchEvent( { type: 'sessionend' } ); + + } + + /** + * Sets the framebuffer scale factor. + * + * This method can not be used during a XR session. + * + * @param {number} value - The framebuffer scale factor. + */ + this.setFramebufferScaleFactor = function ( value ) { + + framebufferScaleFactor = value; + + if ( scope.isPresenting === true ) { + + warn( 'WebXRManager: Cannot change framebuffer scale while presenting.' ); + + } + + }; + + /** + * Sets the reference space type. Can be used to configure a spatial relationship with the user's physical + * environment. Depending on how the user moves in 3D space, setting an appropriate reference space can + * improve tracking. Default is `local-floor`. Valid values can be found here + * https://developer.mozilla.org/en-US/docs/Web/API/XRReferenceSpace#reference_space_types. + * + * This method can not be used during a XR session. + * + * @param {string} value - The reference space type. + */ + this.setReferenceSpaceType = function ( value ) { + + referenceSpaceType = value; + + if ( scope.isPresenting === true ) { + + warn( 'WebXRManager: Cannot change reference space type while presenting.' ); + + } + + }; + + /** + * Returns the XR reference space. + * + * @return {XRReferenceSpace} The XR reference space. + */ + this.getReferenceSpace = function () { + + return customReferenceSpace || referenceSpace; + + }; + + /** + * Sets a custom XR reference space. + * + * @param {XRReferenceSpace} space - The XR reference space. + */ + this.setReferenceSpace = function ( space ) { + + customReferenceSpace = space; + + }; + + /** + * Returns the current base layer. + * + * This is an `XRProjectionLayer` when the targeted XR device supports the + * WebXR Layers API, or an `XRWebGLLayer` otherwise. + * + * @return {?(XRWebGLLayer|XRProjectionLayer)} The XR base layer. + */ + this.getBaseLayer = function () { + + return glProjLayer !== null ? glProjLayer : glBaseLayer; + + }; + + /** + * Returns the current XR binding. + * + * Creates a new binding if needed and the browser is + * capable of doing so. + * + * @return {?XRWebGLBinding} The XR binding. Returns `null` if one cannot be created. + */ + this.getBinding = function () { + + if ( glBinding === null && supportsGlBinding ) { + + glBinding = new XRWebGLBinding( session, gl ); + + } + + return glBinding; + + }; + + /** + * Returns the current XR frame. + * + * @return {?XRFrame} The XR frame. Returns `null` when used outside a XR session. + */ + this.getFrame = function () { + + return xrFrame; + + }; + + /** + * Returns the current XR session. + * + * @return {?XRSession} The XR session. Returns `null` when used outside a XR session. + */ + this.getSession = function () { + + return session; + + }; + + /** + * After a XR session has been requested usually with one of the `*Button` modules, it + * is injected into the renderer with this method. This method triggers the start of + * the actual XR rendering. + * + * @async + * @param {XRSession} value - The XR session to set. + * @return {Promise} A Promise that resolves when the session has been set. + */ + this.setSession = async function ( value ) { + + session = value; + + if ( session !== null ) { + + initialRenderTarget = renderer.getRenderTarget(); + + session.addEventListener( 'select', onSessionEvent ); + session.addEventListener( 'selectstart', onSessionEvent ); + session.addEventListener( 'selectend', onSessionEvent ); + session.addEventListener( 'squeeze', onSessionEvent ); + session.addEventListener( 'squeezestart', onSessionEvent ); + session.addEventListener( 'squeezeend', onSessionEvent ); + session.addEventListener( 'end', onSessionEnd ); + session.addEventListener( 'inputsourceschange', onInputSourcesChange ); + + if ( attributes.xrCompatible !== true ) { + + await gl.makeXRCompatible(); + + } + + currentPixelRatio = renderer.getPixelRatio(); + renderer.getSize( currentSize ); + + + // Check that the browser implements the necessary APIs to use an + // XRProjectionLayer rather than an XRWebGLLayer + const supportsLayers = supportsGlBinding && 'createProjectionLayer' in XRWebGLBinding.prototype; + + if ( ! supportsLayers ) { + + const layerInit = { + antialias: attributes.antialias, + alpha: true, + depth: attributes.depth, + stencil: attributes.stencil, + framebufferScaleFactor: framebufferScaleFactor + }; + + glBaseLayer = new XRWebGLLayer( session, gl, layerInit ); + + session.updateRenderState( { baseLayer: glBaseLayer } ); + + renderer.setPixelRatio( 1 ); + renderer.setSize( glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight, false ); + + newRenderTarget = new WebGLRenderTarget( + glBaseLayer.framebufferWidth, + glBaseLayer.framebufferHeight, + { + format: RGBAFormat, + type: UnsignedByteType, + colorSpace: renderer.outputColorSpace, + stencilBuffer: attributes.stencil, + resolveDepthBuffer: ( glBaseLayer.ignoreDepthValues === false ), + resolveStencilBuffer: ( glBaseLayer.ignoreDepthValues === false ), + storeMultisampledDepthBuffer: ( glBaseLayer.ignoreDepthValues === false ), + storeMultisampledStencilBuffer: ( glBaseLayer.ignoreDepthValues === false ) + + } + ); + + } else { + + let depthFormat = null; + let depthType = null; + let glDepthFormat = null; + + if ( attributes.depth ) { + + glDepthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24; + depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat; + depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType; + + } + + const projectionlayerInit = { + colorFormat: gl.RGBA8, + depthFormat: glDepthFormat, + scaleFactor: framebufferScaleFactor + }; + + glBinding = this.getBinding(); + + glProjLayer = glBinding.createProjectionLayer( projectionlayerInit ); + + session.updateRenderState( { layers: [ glProjLayer ] } ); + + renderer.setPixelRatio( 1 ); + renderer.setSize( glProjLayer.textureWidth, glProjLayer.textureHeight, false ); + + newRenderTarget = new WebGLRenderTarget( + glProjLayer.textureWidth, + glProjLayer.textureHeight, + { + format: RGBAFormat, + type: UnsignedByteType, + depthTexture: new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat ), + stencilBuffer: attributes.stencil, + colorSpace: renderer.outputColorSpace, + samples: attributes.antialias ? 4 : 0, + resolveDepthBuffer: ( glProjLayer.ignoreDepthValues === false ), + resolveStencilBuffer: ( glProjLayer.ignoreDepthValues === false ), + storeMultisampledDepthBuffer: ( glProjLayer.ignoreDepthValues === false ), + storeMultisampledStencilBuffer: ( glProjLayer.ignoreDepthValues === false ) + } ); + + } + + newRenderTarget.isXRRenderTarget = true; // TODO Remove this when possible, see #23278 + + this.setFoveation( foveation ); + + customReferenceSpace = null; + referenceSpace = await session.requestReferenceSpace( referenceSpaceType ); + + animation.setContext( session ); + animation.start(); + + scope.isPresenting = true; + + scope.dispatchEvent( { type: 'sessionstart' } ); + + } + + }; + + /** + * Returns the environment blend mode from the current XR session. + * + * @return {'opaque'|'additive'|'alpha-blend'|undefined} The environment blend mode. Returns `undefined` when used outside of a XR session. + */ + this.getEnvironmentBlendMode = function () { + + if ( session !== null ) { + + return session.environmentBlendMode; + + } + + }; + + /** + * Returns the current depth texture computed via depth sensing. + * + * See {@link WebXRDepthSensing#getDepthTexture}. + * + * @return {?Texture} The depth texture. + */ + this.getDepthTexture = function () { + + return depthSensing.getDepthTexture(); + + }; + + function onInputSourcesChange( event ) { + + // Notify disconnected + + for ( let i = 0; i < event.removed.length; i ++ ) { + + const inputSource = event.removed[ i ]; + const index = controllerInputSources.indexOf( inputSource ); + + if ( index >= 0 ) { + + controllerInputSources[ index ] = null; + controllers[ index ].disconnect( inputSource ); + + } + + } + + // Notify connected + + for ( let i = 0; i < event.added.length; i ++ ) { + + const inputSource = event.added[ i ]; + + let controllerIndex = controllerInputSources.indexOf( inputSource ); + + if ( controllerIndex === -1 ) { + + // Assign input source a controller that currently has no input source + + for ( let i = 0; i < controllers.length; i ++ ) { + + if ( i >= controllerInputSources.length ) { + + controllerInputSources.push( inputSource ); + controllerIndex = i; + break; + + } else if ( controllerInputSources[ i ] === null ) { + + controllerInputSources[ i ] = inputSource; + controllerIndex = i; + break; + + } + + } + + // If all controllers do currently receive input we ignore new ones + + if ( controllerIndex === -1 ) break; + + } + + const controller = controllers[ controllerIndex ]; + + if ( controller ) { + + controller.connect( inputSource ); + + } + + } + + } + + // + + const cameraLPos = new Vector3(); + const cameraRPos = new Vector3(); + + /** + * Assumes 2 cameras that are parallel and share an X-axis, and that + * the cameras' projection and world matrices have already been set. + * And that near and far planes are identical for both cameras. + * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765 + * + * @param {ArrayCamera} camera - The camera to update. + * @param {PerspectiveCamera} cameraL - The left camera. + * @param {PerspectiveCamera} cameraR - The right camera. + */ + function setProjectionFromUnion( camera, cameraL, cameraR ) { + + cameraLPos.setFromMatrixPosition( cameraL.matrixWorld ); + cameraRPos.setFromMatrixPosition( cameraR.matrixWorld ); + + const ipd = cameraLPos.distanceTo( cameraRPos ); + + const projL = cameraL.projectionMatrix.elements; + const projR = cameraR.projectionMatrix.elements; + + // VR systems will have identical far and near planes, and + // most likely identical top and bottom frustum extents. + // Use the left camera for these values. + const near = projL[ 14 ] / ( projL[ 10 ] - 1 ); + const far = projL[ 14 ] / ( projL[ 10 ] + 1 ); + const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ]; + const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ]; + + const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ]; + const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ]; + const left = near * leftFov; + const right = near * rightFov; + + // Calculate the new camera's position offset from the + // left camera. xOffset should be roughly half `ipd`. + const zOffset = ipd / ( - leftFov + rightFov ); + const xOffset = zOffset * - leftFov; + + // TODO: Better way to apply this offset? + cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale ); + camera.translateX( xOffset ); + camera.translateZ( zOffset ); + camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale ); + camera.matrixWorldInverse.copy( camera.matrixWorld ).invert(); + + // Check if the projection uses an infinite far plane. + if ( projL[ 10 ] === -1 ) { + + // Use the projection matrix from the left eye. + // The camera offset is sufficient to include the view volumes + // of both eyes (assuming symmetric projections). + camera.projectionMatrix.copy( cameraL.projectionMatrix ); + camera.projectionMatrixInverse.copy( cameraL.projectionMatrixInverse ); + + } else { + + // Find the union of the frustum values of the cameras and scale + // the values so that the near plane's position does not change in world space, + // although must now be relative to the new union camera. + const near2 = near + zOffset; + const far2 = far + zOffset; + const left2 = left - xOffset; + const right2 = right + ( ipd - xOffset ); + const top2 = topFov * far / far2 * near2; + const bottom2 = bottomFov * far / far2 * near2; + + camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 ); + camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert(); + + } + + } + + function updateCamera( camera, parent ) { + + if ( parent === null ) { + + camera.matrixWorld.copy( camera.matrix ); + + } else { + + camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix ); + + } + + camera.matrixWorldInverse.copy( camera.matrixWorld ).invert(); + + } + + /** + * Updates the state of the XR camera. Use this method on app level if you + * set `cameraAutoUpdate` to `false`. The method requires the non-XR + * camera of the scene as a parameter. The passed in camera's transformation + * is automatically adjusted to the position of the XR camera when calling + * this method. + * + * @param {Camera} camera - The camera. + */ + this.updateCamera = function ( camera ) { + + if ( session === null ) return; + + let depthNear = camera.near; + let depthFar = camera.far; + + if ( depthSensing.texture !== null ) { + + if ( depthSensing.depthNear > 0 ) depthNear = depthSensing.depthNear; + if ( depthSensing.depthFar > 0 ) depthFar = depthSensing.depthFar; + + } + + cameraXR.near = cameraR.near = cameraL.near = depthNear; + cameraXR.far = cameraR.far = cameraL.far = depthFar; + + if ( _currentDepthNear !== cameraXR.near || _currentDepthFar !== cameraXR.far ) { + + // Note that the new renderState won't apply until the next frame. See #18320 + + session.updateRenderState( { + depthNear: cameraXR.near, + depthFar: cameraXR.far + } ); + + _currentDepthNear = cameraXR.near; + _currentDepthFar = cameraXR.far; + + } + + // inherit camera layers and enable eye layers (1 = left, 2 = right) + cameraXR.layers.mask = camera.layers.mask | 0b110; + cameraL.layers.mask = cameraXR.layers.mask & -5; + cameraR.layers.mask = cameraXR.layers.mask & -3; + + const parent = camera.parent; + const cameras = cameraXR.cameras; + + updateCamera( cameraXR, parent ); + + for ( let i = 0; i < cameras.length; i ++ ) { + + updateCamera( cameras[ i ], parent ); + + } + + // update projection matrix for proper view frustum culling + + if ( cameras.length === 2 ) { + + setProjectionFromUnion( cameraXR, cameraL, cameraR ); + + } else { + + // assume single camera setup (AR) + + cameraXR.projectionMatrix.copy( cameraL.projectionMatrix ); + + } + + // update user camera and its children + + if ( currentCameraSettings === null && camera.isPerspectiveCamera ) { + + currentCameraSettings = { camera: camera, fov: camera.fov, zoom: camera.zoom }; + + } + + updateUserCamera( camera, cameraXR, parent ); + + }; + + function updateUserCamera( camera, cameraXR, parent ) { + + if ( parent === null ) { + + camera.matrix.copy( cameraXR.matrixWorld ); + + } else { + + camera.matrix.copy( parent.matrixWorld ); + camera.matrix.invert(); + camera.matrix.multiply( cameraXR.matrixWorld ); + + } + + camera.matrix.decompose( camera.position, camera.quaternion, camera.scale ); + camera.updateMatrixWorld( true ); + + camera.projectionMatrix.copy( cameraXR.projectionMatrix ); + camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse ); + + if ( camera.isPerspectiveCamera ) { + + camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] ); + camera.zoom = 1; + + } + + } + + /** + * Returns an instance of {@link ArrayCamera} which represents the XR camera + * of the active XR session. For each view it holds a separate camera object. + * + * The camera's `fov` is currently not used and does not reflect the fov of + * the XR camera. If you need the fov on app level, you have to compute in + * manually from the XR camera's projection matrices. + * + * @return {ArrayCamera} The XR camera. + */ + this.getCamera = function () { + + return cameraXR; + + }; + + /** + * Returns the amount of foveation used by the XR compositor for the projection layer. + * + * @return {number|undefined} The amount of foveation. + */ + this.getFoveation = function () { + + if ( glProjLayer === null && glBaseLayer === null ) { + + return undefined; + + } + + return foveation; + + }; + + /** + * Sets the foveation value. + * + * @param {number} value - A number in the range `[0,1]` where `0` means no foveation (full resolution) + * and `1` means maximum foveation (the edges render at lower resolution). + */ + this.setFoveation = function ( value ) { + + // 0 = no foveation = full resolution + // 1 = maximum foveation = the edges render at lower resolution + + foveation = value; + + if ( glProjLayer !== null ) { + + glProjLayer.fixedFoveation = value; + + } + + if ( glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined ) { + + glBaseLayer.fixedFoveation = value; + + } + + }; + + /** + * Returns `true` if depth sensing is supported. + * + * @return {boolean} Whether depth sensing is supported or not. + */ + this.hasDepthSensing = function () { + + return depthSensing.texture !== null; + + }; + + /** + * Returns the depth sensing mesh. + * + * See {@link WebXRDepthSensing#getMesh}. + * + * @return {Mesh} The depth sensing mesh. + */ + this.getDepthSensingMesh = function () { + + return depthSensing.getMesh( cameraXR ); + + }; + + /** + * Retrieves an opaque texture from the view-aligned {@link XRCamera}. + * Only available during the current animation loop. + * + * @param {XRCamera} xrCamera - The camera to query. + * @return {?Texture} An opaque texture representing the current raw camera frame. + */ + this.getCameraTexture = function ( xrCamera ) { + + return cameraAccessTextures[ xrCamera ]; + + }; + + // Animation Loop + + let onAnimationFrameCallback = null; + + function onAnimationFrame( time, frame ) { + + pose = frame.getViewerPose( customReferenceSpace || referenceSpace ); + xrFrame = frame; + + if ( pose !== null ) { + + const views = pose.views; + + if ( glBaseLayer !== null ) { + + renderer.setRenderTargetFramebuffer( newRenderTarget, glBaseLayer.framebuffer ); + renderer.setRenderTarget( newRenderTarget ); + + } + + let cameraXRNeedsUpdate = false; + + // check if it's necessary to rebuild cameraXR's camera list + + if ( views.length !== cameraXR.cameras.length ) { + + cameraXR.cameras.length = 0; + cameraXRNeedsUpdate = true; + + } + + for ( let i = 0; i < views.length; i ++ ) { + + const view = views[ i ]; + + let viewport = null; + + if ( glBaseLayer !== null ) { + + viewport = glBaseLayer.getViewport( view ); + + } else { + + const glSubImage = glBinding.getViewSubImage( glProjLayer, view ); + viewport = glSubImage.viewport; + + // For side-by-side projection, we only produce a single texture for both eyes. + if ( i === 0 ) { + + renderer.setRenderTargetTextures( + newRenderTarget, + glSubImage.colorTexture, + glSubImage.depthStencilTexture ); + + renderer.setRenderTarget( newRenderTarget ); + + } + + } + + let camera = cameras[ i ]; + + if ( camera === undefined ) { + + camera = new PerspectiveCamera(); + camera.layers.enable( i ); + camera.viewport = new Vector4(); + cameras[ i ] = camera; + + } + + camera.matrix.fromArray( view.transform.matrix ); + camera.matrix.decompose( camera.position, camera.quaternion, camera.scale ); + camera.projectionMatrix.fromArray( view.projectionMatrix ); + camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert(); + camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height ); + + if ( i === 0 ) { + + cameraXR.matrix.copy( camera.matrix ); + cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale ); + + } + + if ( cameraXRNeedsUpdate === true ) { + + cameraXR.cameras.push( camera ); + + } + + } + + // + + const enabledFeatures = session.enabledFeatures; + const gpuDepthSensingEnabled = enabledFeatures && + enabledFeatures.includes( 'depth-sensing' ) && + session.depthUsage == 'gpu-optimized'; + + if ( gpuDepthSensingEnabled && supportsGlBinding ) { + + glBinding = scope.getBinding(); + + const depthData = glBinding.getDepthInformation( views[ 0 ] ); + + if ( depthData && depthData.isValid && depthData.texture ) { + + depthSensing.init( depthData, session.renderState ); + + } + + } + + const cameraAccessEnabled = enabledFeatures && + enabledFeatures.includes( 'camera-access' ); + + if ( cameraAccessEnabled && supportsGlBinding ) { + + renderer.state.unbindTexture(); + + glBinding = scope.getBinding(); + + for ( let i = 0; i < views.length; i ++ ) { + + const camera = views[ i ].camera; + + if ( camera ) { + + let cameraTex = cameraAccessTextures[ camera ]; + + if ( ! cameraTex ) { + + cameraTex = new ExternalTexture(); + cameraAccessTextures[ camera ] = cameraTex; + + } + + const glTexture = glBinding.getCameraImage( camera ); + cameraTex.sourceTexture = glTexture; + + } + + } + + } + + } + + // + + for ( let i = 0; i < controllers.length; i ++ ) { + + const inputSource = controllerInputSources[ i ]; + const controller = controllers[ i ]; + + if ( inputSource !== null && controller !== undefined ) { + + controller.update( inputSource, frame, customReferenceSpace || referenceSpace ); + + } + + } + + if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame ); + + if ( frame.detectedPlanes ) { + + scope.dispatchEvent( { type: 'planesdetected', data: frame } ); + + } + + xrFrame = null; + + } + + const animation = new WebGLAnimation(); + + animation.setAnimationLoop( onAnimationFrame ); + + this.setAnimationLoop = function ( callback ) { + + onAnimationFrameCallback = callback; + + }; + + this.dispose = function () {}; + + } + +} + +const _m1 = /*@__PURE__*/ new Matrix4(); +const _m = /*@__PURE__*/ new Matrix3(); + +_m.set( -1, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0 ); + +function WebGLMaterials( renderer, properties ) { + + function refreshTransformUniform( map, uniform ) { + + if ( map.matrixAutoUpdate === true ) { + + map.updateMatrix(); + + } + + uniform.value.copy( map.matrix ); + + } + + function refreshFogUniforms( uniforms, fog ) { + + fog.color.getRGB( uniforms.fogColor.value, getUnlitUniformColorSpace( renderer ) ); + + if ( fog.isFog ) { + + uniforms.fogNear.value = fog.near; + uniforms.fogFar.value = fog.far; + + } else if ( fog.isFogExp2 ) { + + uniforms.fogDensity.value = fog.density; + + } + + } + + function refreshMaterialUniforms( uniforms, material, pixelRatio, height, transmissionRenderTarget ) { + + if ( material.isNodeMaterial ) { + + material.uniformsNeedUpdate = false; + + } else if ( material.isMeshBasicMaterial ) { + + refreshUniformsCommon( uniforms, material ); + + } else if ( material.isMeshLambertMaterial ) { + + refreshUniformsCommon( uniforms, material ); + + if ( material.envMap ) { + + uniforms.envMapIntensity.value = material.envMapIntensity; + + } + + } else if ( material.isMeshToonMaterial ) { + + refreshUniformsCommon( uniforms, material ); + refreshUniformsToon( uniforms, material ); + + } else if ( material.isMeshPhongMaterial ) { + + refreshUniformsCommon( uniforms, material ); + refreshUniformsPhong( uniforms, material ); + + if ( material.envMap ) { + + uniforms.envMapIntensity.value = material.envMapIntensity; + + } + + } else if ( material.isMeshStandardMaterial ) { + + refreshUniformsCommon( uniforms, material ); + refreshUniformsStandard( uniforms, material ); + + if ( material.isMeshPhysicalMaterial ) { + + refreshUniformsPhysical( uniforms, material, transmissionRenderTarget ); + + } + + } else if ( material.isMeshMatcapMaterial ) { + + refreshUniformsCommon( uniforms, material ); + refreshUniformsMatcap( uniforms, material ); + + } else if ( material.isMeshDepthMaterial ) { + + refreshUniformsCommon( uniforms, material ); + + } else if ( material.isMeshDistanceMaterial ) { + + refreshUniformsCommon( uniforms, material ); + refreshUniformsDistance( uniforms, material ); + + } else if ( material.isMeshNormalMaterial ) { + + refreshUniformsCommon( uniforms, material ); + + } else if ( material.isLineBasicMaterial ) { + + refreshUniformsLine( uniforms, material ); + + if ( material.isLineDashedMaterial ) { + + refreshUniformsDash( uniforms, material ); + + } + + } else if ( material.isPointsMaterial ) { + + refreshUniformsPoints( uniforms, material, pixelRatio, height ); + + } else if ( material.isSpriteMaterial ) { + + refreshUniformsSprites( uniforms, material ); + + } else if ( material.isShadowMaterial ) { + + uniforms.color.value.copy( material.color ); + uniforms.opacity.value = material.opacity; + + } else if ( material.isShaderMaterial ) { + + material.uniformsNeedUpdate = false; // #15581 + + } + + } + + function refreshUniformsCommon( uniforms, material ) { + + uniforms.opacity.value = material.opacity; + + if ( material.color ) { + + uniforms.diffuse.value.copy( material.color ); + + } + + if ( material.emissive ) { + + uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity ); + + } + + if ( material.map ) { + + uniforms.map.value = material.map; + + refreshTransformUniform( material.map, uniforms.mapTransform ); + + } + + if ( material.alphaMap ) { + + uniforms.alphaMap.value = material.alphaMap; + + refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform ); + + } + + if ( material.bumpMap ) { + + uniforms.bumpMap.value = material.bumpMap; + + refreshTransformUniform( material.bumpMap, uniforms.bumpMapTransform ); + + uniforms.bumpScale.value = material.bumpScale; + + if ( material.side === BackSide ) { + + uniforms.bumpScale.value *= -1; + + } + + } + + if ( material.normalMap ) { + + uniforms.normalMap.value = material.normalMap; + + refreshTransformUniform( material.normalMap, uniforms.normalMapTransform ); + + uniforms.normalScale.value.copy( material.normalScale ); + + if ( material.side === BackSide ) { + + uniforms.normalScale.value.negate(); + + } + + } + + if ( material.displacementMap ) { + + uniforms.displacementMap.value = material.displacementMap; + + refreshTransformUniform( material.displacementMap, uniforms.displacementMapTransform ); + + uniforms.displacementScale.value = material.displacementScale; + uniforms.displacementBias.value = material.displacementBias; + + } + + if ( material.emissiveMap ) { + + uniforms.emissiveMap.value = material.emissiveMap; + + refreshTransformUniform( material.emissiveMap, uniforms.emissiveMapTransform ); + + } + + if ( material.specularMap ) { + + uniforms.specularMap.value = material.specularMap; + + refreshTransformUniform( material.specularMap, uniforms.specularMapTransform ); + + } + + if ( material.alphaTest > 0 ) { + + uniforms.alphaTest.value = material.alphaTest; + + } + + const materialProperties = properties.get( material ); + + const envMap = materialProperties.envMap; + const envMapRotation = materialProperties.envMapRotation; + + if ( envMap ) { + + uniforms.envMap.value = envMap; + + // note: since the matrix is orthonormal, we can use the more-efficient transpose() in lieu of invert() + uniforms.envMapRotation.value.setFromMatrix4( _m1.makeRotationFromEuler( envMapRotation ) ).transpose(); + + + if ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) { + + uniforms.envMapRotation.value.premultiply( _m ); + + } + + uniforms.reflectivity.value = material.reflectivity; + uniforms.ior.value = material.ior; + uniforms.refractionRatio.value = material.refractionRatio; + + } + + if ( material.lightMap ) { + + uniforms.lightMap.value = material.lightMap; + uniforms.lightMapIntensity.value = material.lightMapIntensity; + + refreshTransformUniform( material.lightMap, uniforms.lightMapTransform ); + + } + + if ( material.aoMap ) { + + uniforms.aoMap.value = material.aoMap; + uniforms.aoMapIntensity.value = material.aoMapIntensity; + + refreshTransformUniform( material.aoMap, uniforms.aoMapTransform ); + + } + + } + + function refreshUniformsLine( uniforms, material ) { + + uniforms.diffuse.value.copy( material.color ); + uniforms.opacity.value = material.opacity; + + if ( material.map ) { + + uniforms.map.value = material.map; + + refreshTransformUniform( material.map, uniforms.mapTransform ); + + } + + } + + function refreshUniformsDash( uniforms, material ) { + + uniforms.dashSize.value = material.dashSize; + uniforms.totalSize.value = material.dashSize + material.gapSize; + uniforms.scale.value = material.scale; + + } + + function refreshUniformsPoints( uniforms, material, pixelRatio, height ) { + + uniforms.diffuse.value.copy( material.color ); + uniforms.opacity.value = material.opacity; + uniforms.size.value = material.size * pixelRatio; + uniforms.scale.value = height * 0.5; + + if ( material.map ) { + + uniforms.map.value = material.map; + + refreshTransformUniform( material.map, uniforms.uvTransform ); + + } + + if ( material.alphaMap ) { + + uniforms.alphaMap.value = material.alphaMap; + + refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform ); + + } + + if ( material.alphaTest > 0 ) { + + uniforms.alphaTest.value = material.alphaTest; + + } + + } + + function refreshUniformsSprites( uniforms, material ) { + + uniforms.diffuse.value.copy( material.color ); + uniforms.opacity.value = material.opacity; + uniforms.rotation.value = material.rotation; + + if ( material.map ) { + + uniforms.map.value = material.map; + + refreshTransformUniform( material.map, uniforms.mapTransform ); + + } + + if ( material.alphaMap ) { + + uniforms.alphaMap.value = material.alphaMap; + + refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform ); + + } + + if ( material.alphaTest > 0 ) { + + uniforms.alphaTest.value = material.alphaTest; + + } + + } + + function refreshUniformsPhong( uniforms, material ) { + + uniforms.specular.value.copy( material.specular ); + uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 ) + + } + + function refreshUniformsToon( uniforms, material ) { + + if ( material.gradientMap ) { + + uniforms.gradientMap.value = material.gradientMap; + + } + + } + + function refreshUniformsStandard( uniforms, material ) { + + uniforms.metalness.value = material.metalness; + + if ( material.metalnessMap ) { + + uniforms.metalnessMap.value = material.metalnessMap; + + refreshTransformUniform( material.metalnessMap, uniforms.metalnessMapTransform ); + + } + + uniforms.roughness.value = material.roughness; + + if ( material.roughnessMap ) { + + uniforms.roughnessMap.value = material.roughnessMap; + + refreshTransformUniform( material.roughnessMap, uniforms.roughnessMapTransform ); + + } + + if ( material.envMap ) { + + //uniforms.envMap.value = material.envMap; // part of uniforms common + + uniforms.envMapIntensity.value = material.envMapIntensity; + + } + + } + + function refreshUniformsPhysical( uniforms, material, transmissionRenderTarget ) { + + uniforms.ior.value = material.ior; // also part of uniforms common + + if ( material.sheen > 0 ) { + + uniforms.sheenColor.value.copy( material.sheenColor ).multiplyScalar( material.sheen ); + + uniforms.sheenRoughness.value = material.sheenRoughness; + + if ( material.sheenColorMap ) { + + uniforms.sheenColorMap.value = material.sheenColorMap; + + refreshTransformUniform( material.sheenColorMap, uniforms.sheenColorMapTransform ); + + } + + if ( material.sheenRoughnessMap ) { + + uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap; + + refreshTransformUniform( material.sheenRoughnessMap, uniforms.sheenRoughnessMapTransform ); + + } + + } + + if ( material.clearcoat > 0 ) { + + uniforms.clearcoat.value = material.clearcoat; + uniforms.clearcoatRoughness.value = material.clearcoatRoughness; + + if ( material.clearcoatMap ) { + + uniforms.clearcoatMap.value = material.clearcoatMap; + + refreshTransformUniform( material.clearcoatMap, uniforms.clearcoatMapTransform ); + + } + + if ( material.clearcoatRoughnessMap ) { + + uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap; + + refreshTransformUniform( material.clearcoatRoughnessMap, uniforms.clearcoatRoughnessMapTransform ); + + } + + if ( material.clearcoatNormalMap ) { + + uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap; + + refreshTransformUniform( material.clearcoatNormalMap, uniforms.clearcoatNormalMapTransform ); + + uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale ); + + if ( material.side === BackSide ) { + + uniforms.clearcoatNormalScale.value.negate(); + + } + + } + + } + + if ( material.dispersion > 0 ) { + + uniforms.dispersion.value = material.dispersion; + + } + + if ( material.retroreflectivity > 0 ) { + + uniforms.retroreflectivity.value = material.retroreflectivity; + + } + + if ( material.iridescence > 0 ) { + + uniforms.iridescence.value = material.iridescence; + uniforms.iridescenceIOR.value = material.iridescenceIOR; + uniforms.iridescenceThicknessMinimum.value = material.iridescenceThicknessRange[ 0 ]; + uniforms.iridescenceThicknessMaximum.value = material.iridescenceThicknessRange[ 1 ]; + + if ( material.iridescenceMap ) { + + uniforms.iridescenceMap.value = material.iridescenceMap; + + refreshTransformUniform( material.iridescenceMap, uniforms.iridescenceMapTransform ); + + } + + if ( material.iridescenceThicknessMap ) { + + uniforms.iridescenceThicknessMap.value = material.iridescenceThicknessMap; + + refreshTransformUniform( material.iridescenceThicknessMap, uniforms.iridescenceThicknessMapTransform ); + + } + + } + + if ( material.transmission > 0 ) { + + uniforms.transmission.value = material.transmission; + uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture; + uniforms.transmissionSamplerSize.value.set( transmissionRenderTarget.width, transmissionRenderTarget.height ); + + if ( material.transmissionMap ) { + + uniforms.transmissionMap.value = material.transmissionMap; + + refreshTransformUniform( material.transmissionMap, uniforms.transmissionMapTransform ); + + } + + uniforms.thickness.value = material.thickness; + + if ( material.thicknessMap ) { + + uniforms.thicknessMap.value = material.thicknessMap; + + refreshTransformUniform( material.thicknessMap, uniforms.thicknessMapTransform ); + + } + + uniforms.attenuationDistance.value = material.attenuationDistance; + uniforms.attenuationColor.value.copy( material.attenuationColor ); + + } + + if ( material.anisotropy > 0 ) { + + uniforms.anisotropyVector.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) ); + + if ( material.anisotropyMap ) { + + uniforms.anisotropyMap.value = material.anisotropyMap; + + refreshTransformUniform( material.anisotropyMap, uniforms.anisotropyMapTransform ); + + } + + } + + uniforms.specularIntensity.value = material.specularIntensity; + uniforms.specularColor.value.copy( material.specularColor ); + + if ( material.specularColorMap ) { + + uniforms.specularColorMap.value = material.specularColorMap; + + refreshTransformUniform( material.specularColorMap, uniforms.specularColorMapTransform ); + + } + + if ( material.specularIntensityMap ) { + + uniforms.specularIntensityMap.value = material.specularIntensityMap; + + refreshTransformUniform( material.specularIntensityMap, uniforms.specularIntensityMapTransform ); + + } + + } + + function refreshUniformsMatcap( uniforms, material ) { + + if ( material.matcap ) { + + uniforms.matcap.value = material.matcap; + + } + + } + + function refreshUniformsDistance( uniforms, material ) { + + const light = properties.get( material ).light; + + uniforms.referencePosition.value.setFromMatrixPosition( light.matrixWorld ); + uniforms.nearDistance.value = light.shadow.camera.near; + uniforms.farDistance.value = light.shadow.camera.far; + + } + + return { + refreshFogUniforms: refreshFogUniforms, + refreshMaterialUniforms: refreshMaterialUniforms + }; + +} + +function WebGLUniformsGroups( gl, info, capabilities, state ) { + + let buffers = {}; + let updateList = {}; + let allocatedBindingPoints = []; + + const maxBindingPoints = gl.getParameter( gl.MAX_UNIFORM_BUFFER_BINDINGS ); // binding points are global whereas block indices are per shader program + + function bind( uniformsGroup, program ) { + + const webglProgram = program.program; + state.uniformBlockBinding( uniformsGroup, webglProgram ); + + } + + function update( uniformsGroup, program ) { + + let buffer = buffers[ uniformsGroup.id ]; + + if ( buffer === undefined ) { + + prepareUniformsGroup( uniformsGroup ); + + buffer = createBuffer( uniformsGroup ); + buffers[ uniformsGroup.id ] = buffer; + + uniformsGroup.addEventListener( 'dispose', onUniformsGroupsDispose ); + + } + + // ensure to update the binding points/block indices mapping for this program + + const webglProgram = program.program; + state.updateUBOMapping( uniformsGroup, webglProgram ); + + // update UBO once per frame + + const frame = info.render.frame; + + if ( updateList[ uniformsGroup.id ] !== frame ) { + + updateBufferData( uniformsGroup ); + + updateList[ uniformsGroup.id ] = frame; + + } + + } + + function createBuffer( uniformsGroup ) { + + // the setup of an UBO is independent of a particular shader program but global + + const bindingPointIndex = allocateBindingPointIndex(); + uniformsGroup.__bindingPointIndex = bindingPointIndex; + + const buffer = gl.createBuffer(); + const size = uniformsGroup.__size; + const usage = uniformsGroup.usage; + + gl.bindBuffer( gl.UNIFORM_BUFFER, buffer ); + gl.bufferData( gl.UNIFORM_BUFFER, size, usage ); + gl.bindBuffer( gl.UNIFORM_BUFFER, null ); + gl.bindBufferBase( gl.UNIFORM_BUFFER, bindingPointIndex, buffer ); + + return buffer; + + } + + function allocateBindingPointIndex() { + + for ( let i = 0; i < maxBindingPoints; i ++ ) { + + if ( allocatedBindingPoints.indexOf( i ) === -1 ) { + + allocatedBindingPoints.push( i ); + return i; + + } + + } + + error( 'WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached.' ); + + return 0; + + } + + function updateBufferData( uniformsGroup ) { + + const buffer = buffers[ uniformsGroup.id ]; + const uniforms = uniformsGroup.uniforms; + const cache = uniformsGroup.__cache; + + gl.bindBuffer( gl.UNIFORM_BUFFER, buffer ); + + for ( let i = 0, il = uniforms.length; i < il; i ++ ) { + + const uniformItem = uniforms[ i ]; + + if ( Array.isArray( uniformItem ) ) { + + for ( let j = 0, jl = uniformItem.length; j < jl; j ++ ) { + + updateUniform( uniformItem[ j ], i, j, cache ); + + } + + } else { + + updateUniform( uniformItem, i, 0, cache ); + + } + + } + + gl.bindBuffer( gl.UNIFORM_BUFFER, null ); + + } + + function updateUniform( uniform, index, indexArray, cache ) { + + if ( hasUniformChanged( uniform, index, indexArray, cache ) === true ) { + + const offset = uniform.__offset; + const value = uniform.value; + + if ( Array.isArray( value ) ) { + + let arrayOffset = 0; + + for ( let k = 0; k < value.length; k ++ ) { + + const val = value[ k ]; + const info = getUniformSize( val ); + + writeUniformValue( val, uniform.__data, arrayOffset ); + + // only toArray() values advance arrayOffset + if ( typeof val !== 'number' && typeof val !== 'boolean' && ! val.isMatrix3 && ! ArrayBuffer.isView( val ) ) { + + arrayOffset += info.storage / Float32Array.BYTES_PER_ELEMENT; + + } + + } + + } else { + + writeUniformValue( value, uniform.__data, 0 ); + + } + + gl.bufferSubData( gl.UNIFORM_BUFFER, offset, uniform.__data ); + + } + + } + + function writeUniformValue( value, data, offset ) { + + // TODO add integer and struct support + if ( typeof value === 'number' || typeof value === 'boolean' ) { + + data[ 0 ] = value; + + } else if ( value.isMatrix3 ) { + + // manually converting 3x3 to 3x4 + + data[ 0 ] = value.elements[ 0 ]; + data[ 1 ] = value.elements[ 1 ]; + data[ 2 ] = value.elements[ 2 ]; + data[ 3 ] = 0; + data[ 4 ] = value.elements[ 3 ]; + data[ 5 ] = value.elements[ 4 ]; + data[ 6 ] = value.elements[ 5 ]; + data[ 7 ] = 0; + data[ 8 ] = value.elements[ 6 ]; + data[ 9 ] = value.elements[ 7 ]; + data[ 10 ] = value.elements[ 8 ]; + data[ 11 ] = 0; + + } else if ( ArrayBuffer.isView( value ) ) { + + // copy the buffer data using "set" + data.set( new value.constructor( value.buffer, value.byteOffset, data.length ) ); + + } else { + + value.toArray( data, offset ); + + } + + } + + function hasUniformChanged( uniform, index, indexArray, cache ) { + + const value = uniform.value; + const indexString = index + '_' + indexArray; + + if ( cache[ indexString ] === undefined ) { + + // cache entry does not exist so far + + if ( typeof value === 'number' || typeof value === 'boolean' ) { + + cache[ indexString ] = value; + + } else if ( ArrayBuffer.isView( value ) ) { + + cache[ indexString ] = value.slice(); + + } else { + + cache[ indexString ] = value.clone(); + + } + + return true; + + } else { + + const cachedObject = cache[ indexString ]; + + // compare current value with cached entry + + if ( typeof value === 'number' || typeof value === 'boolean' ) { + + if ( cachedObject !== value ) { + + cache[ indexString ] = value; + return true; + + } + + } else if ( ArrayBuffer.isView( value ) ) { + + // always update the array buffers + return true; + + } else { + + if ( cachedObject.equals( value ) === false ) { + + cachedObject.copy( value ); + return true; + + } + + } + + } + + return false; + + } + + function prepareUniformsGroup( uniformsGroup ) { + + // determine total buffer size according to the STD140 layout + // Hint: STD140 is the only supported layout in WebGL 2 + + const uniforms = uniformsGroup.uniforms; + + let offset = 0; // global buffer offset in bytes + const chunkSize = 16; // size of a chunk in bytes + + for ( let i = 0, l = uniforms.length; i < l; i ++ ) { + + const uniformArray = Array.isArray( uniforms[ i ] ) ? uniforms[ i ] : [ uniforms[ i ] ]; + + for ( let j = 0, jl = uniformArray.length; j < jl; j ++ ) { + + const uniform = uniformArray[ j ]; + + const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ]; + + for ( let k = 0, kl = values.length; k < kl; k ++ ) { + + const value = values[ k ]; + + const info = getUniformSize( value ); + + const chunkOffset = offset % chunkSize; // offset in the current chunk + const chunkPadding = chunkOffset % info.boundary; // required padding to match boundary + const chunkStart = chunkOffset + chunkPadding; // the start position in the current chunk for the data + + offset += chunkPadding; + + // Check for chunk overflow + if ( chunkStart !== 0 && ( chunkSize - chunkStart ) < info.storage ) { + + // Add padding and adjust offset + offset += ( chunkSize - chunkStart ); + + } + + // the following two properties will be used for partial buffer updates + uniform.__data = new Float32Array( info.storage / Float32Array.BYTES_PER_ELEMENT ); + uniform.__offset = offset; + + // Update the global offset + offset += info.storage; + + } + + } + + } + + // ensure correct final padding + + const chunkOffset = offset % chunkSize; + + if ( chunkOffset > 0 ) offset += ( chunkSize - chunkOffset ); + + // + + uniformsGroup.__size = offset; + uniformsGroup.__cache = {}; + + return this; + + } + + function getUniformSize( value ) { + + const info = { + boundary: 0, // bytes + storage: 0 // bytes + }; + + // determine sizes according to STD140 + + if ( typeof value === 'number' || typeof value === 'boolean' ) { + + // float/int/bool + + info.boundary = 4; + info.storage = 4; + + } else if ( value.isVector2 ) { + + // vec2 + + info.boundary = 8; + info.storage = 8; + + } else if ( value.isVector3 || value.isColor ) { + + // vec3 + + info.boundary = 16; + info.storage = 12; // evil: vec3 must start on a 16-byte boundary but it only consumes 12 bytes + + } else if ( value.isVector4 ) { + + // vec4 + + info.boundary = 16; + info.storage = 16; + + } else if ( value.isMatrix3 ) { + + // mat3 (in STD140 a 3x3 matrix is represented as 3x4) + + info.boundary = 48; + info.storage = 48; + + } else if ( value.isMatrix4 ) { + + // mat4 + + info.boundary = 64; + info.storage = 64; + + } else if ( value.isTexture ) { + + warn( 'WebGLRenderer: Texture samplers can not be part of an uniforms group.' ); + + } else if ( ArrayBuffer.isView( value ) ) { + + info.boundary = 16; + info.storage = value.byteLength; + + } else { + + warn( 'WebGLRenderer: Unsupported uniform value type.', value ); + + } + + return info; + + } + + function onUniformsGroupsDispose( event ) { + + const uniformsGroup = event.target; + + uniformsGroup.removeEventListener( 'dispose', onUniformsGroupsDispose ); + + const index = allocatedBindingPoints.indexOf( uniformsGroup.__bindingPointIndex ); + allocatedBindingPoints.splice( index, 1 ); + + gl.deleteBuffer( buffers[ uniformsGroup.id ] ); + + delete buffers[ uniformsGroup.id ]; + delete updateList[ uniformsGroup.id ]; + + } + + function dispose() { + + for ( const id in buffers ) { + + gl.deleteBuffer( buffers[ id ] ); + + } + + allocatedBindingPoints = []; + buffers = {}; + updateList = {}; + + } + + return { + + bind: bind, + update: update, + + dispose: dispose + + }; + +} + +/** + * Precomputed DFG LUT for physically based specular lighting, used by both + * image-based lighting and direct-light multi-scattering energy compensation + * Resolution: 16x16 + * Samples: 4096 per texel + * Format: RG16F (2 half floats per texel: scale, bias) + */ + + +const DATA = new Uint16Array( [ + 0x30b5, 0x3ad1, 0x314c, 0x3a4d, 0x33d2, 0x391c, 0x35ef, 0x3828, 0x37f3, 0x36a6, 0x38d1, 0x3539, 0x3979, 0x3410, 0x39f8, 0x3252, 0x3a53, 0x30f0, 0x3a94, 0x2fc9, 0x3abf, 0x2e35, 0x3ada, 0x2d05, 0x3ae8, 0x2c1f, 0x3aed, 0x2ae0, 0x3aea, 0x29d1, 0x3ae1, 0x28ff, + 0x3638, 0x38e4, 0x364a, 0x38ce, 0x3699, 0x385e, 0x374e, 0x372c, 0x3839, 0x35a4, 0x38dc, 0x3462, 0x396e, 0x32c4, 0x39de, 0x3134, 0x3a2b, 0x3003, 0x3a59, 0x2e3a, 0x3a6d, 0x2ce1, 0x3a6e, 0x2bba, 0x3a5f, 0x2a33, 0x3a49, 0x290a, 0x3a2d, 0x2826, 0x3a0a, 0x26e8, + 0x3894, 0x36d7, 0x3897, 0x36c9, 0x38a3, 0x3675, 0x38bc, 0x35ac, 0x38ee, 0x349c, 0x393e, 0x3332, 0x3997, 0x3186, 0x39e2, 0x3038, 0x3a13, 0x2e75, 0x3a29, 0x2cf5, 0x3a2d, 0x2bac, 0x3a21, 0x29ff, 0x3a04, 0x28bc, 0x39dc, 0x2790, 0x39ad, 0x261a, 0x3978, 0x24fa, + 0x39ac, 0x34a8, 0x39ac, 0x34a3, 0x39ae, 0x3480, 0x39ae, 0x3423, 0x39b1, 0x330e, 0x39c2, 0x31a9, 0x39e0, 0x3063, 0x39fc, 0x2eb5, 0x3a0c, 0x2d1d, 0x3a14, 0x2bcf, 0x3a07, 0x29ff, 0x39e9, 0x28a3, 0x39be, 0x273c, 0x3989, 0x25b3, 0x394a, 0x2488, 0x3907, 0x2345, + 0x3a77, 0x3223, 0x3a76, 0x321f, 0x3a73, 0x3204, 0x3a6a, 0x31b3, 0x3a58, 0x3114, 0x3a45, 0x303b, 0x3a34, 0x2eb6, 0x3a26, 0x2d31, 0x3a1e, 0x2bef, 0x3a0b, 0x2a0d, 0x39ec, 0x28a1, 0x39c0, 0x271b, 0x3987, 0x2580, 0x3944, 0x2449, 0x38fa, 0x22bd, 0x38ac, 0x2155, + 0x3b07, 0x2fca, 0x3b06, 0x2fca, 0x3b00, 0x2fb8, 0x3af4, 0x2f7c, 0x3adb, 0x2eea, 0x3ab4, 0x2e00, 0x3a85, 0x2cec, 0x3a5e, 0x2bc5, 0x3a36, 0x2a00, 0x3a0d, 0x2899, 0x39dc, 0x2707, 0x39a0, 0x2562, 0x395a, 0x2424, 0x390b, 0x2268, 0x38b7, 0x20fd, 0x385f, 0x1fd1, + 0x3b69, 0x2cb9, 0x3b68, 0x2cbb, 0x3b62, 0x2cbb, 0x3b56, 0x2cae, 0x3b3b, 0x2c78, 0x3b0d, 0x2c0a, 0x3acf, 0x2ae3, 0x3a92, 0x2998, 0x3a54, 0x2867, 0x3a17, 0x26d0, 0x39d3, 0x253c, 0x3989, 0x2402, 0x3935, 0x2226, 0x38dc, 0x20bd, 0x387d, 0x1f54, 0x381d, 0x1db3, + 0x3ba9, 0x296b, 0x3ba8, 0x296f, 0x3ba3, 0x297b, 0x3b98, 0x2987, 0x3b7f, 0x2976, 0x3b4e, 0x2927, 0x3b0e, 0x2895, 0x3ac2, 0x27b7, 0x3a73, 0x263b, 0x3a23, 0x24e7, 0x39d0, 0x239b, 0x3976, 0x21d9, 0x3917, 0x207e, 0x38b2, 0x1ee7, 0x384b, 0x1d53, 0x37c7, 0x1c1e, + 0x3bd2, 0x25cb, 0x3bd1, 0x25d3, 0x3bcd, 0x25f0, 0x3bc2, 0x261f, 0x3bad, 0x2645, 0x3b7d, 0x262d, 0x3b3e, 0x25c4, 0x3aec, 0x250f, 0x3a93, 0x243a, 0x3a32, 0x22ce, 0x39d0, 0x215b, 0x3969, 0x202a, 0x38fe, 0x1e6e, 0x388f, 0x1cf1, 0x381f, 0x1b9b, 0x3762, 0x19dd, + 0x3be9, 0x21ab, 0x3be9, 0x21b7, 0x3be5, 0x21e5, 0x3bdd, 0x2241, 0x3bc9, 0x22a7, 0x3ba0, 0x22ec, 0x3b62, 0x22cd, 0x3b0f, 0x2247, 0x3aae, 0x2175, 0x3a44, 0x2088, 0x39d4, 0x1f49, 0x3960, 0x1dbe, 0x38e9, 0x1c77, 0x3870, 0x1ae8, 0x37f1, 0x1953, 0x3708, 0x181b, + 0x3bf6, 0x1cea, 0x3bf6, 0x1cfb, 0x3bf3, 0x1d38, 0x3bec, 0x1dbd, 0x3bda, 0x1e7c, 0x3bb7, 0x1f25, 0x3b7d, 0x1f79, 0x3b2c, 0x1f4c, 0x3ac6, 0x1ea6, 0x3a55, 0x1dbb, 0x39da, 0x1cbd, 0x395a, 0x1b9d, 0x38d8, 0x1a00, 0x3855, 0x18ac, 0x37ab, 0x173c, 0x36b7, 0x1598, + 0x3bfc, 0x1736, 0x3bfc, 0x1759, 0x3bf9, 0x17e7, 0x3bf4, 0x1896, 0x3be4, 0x1997, 0x3bc6, 0x1aa8, 0x3b91, 0x1b84, 0x3b43, 0x1bd2, 0x3ade, 0x1b8a, 0x3a65, 0x1acd, 0x39e2, 0x19d3, 0x3957, 0x18cd, 0x38ca, 0x17b3, 0x383e, 0x1613, 0x376d, 0x14bf, 0x366f, 0x135e, + 0x3bff, 0x101b, 0x3bff, 0x1039, 0x3bfc, 0x10c8, 0x3bf9, 0x1226, 0x3bea, 0x1428, 0x3bcf, 0x1584, 0x3b9f, 0x16c5, 0x3b54, 0x179a, 0x3af0, 0x17ce, 0x3a76, 0x1771, 0x39ea, 0x16a4, 0x3956, 0x15a7, 0x38bf, 0x14a7, 0x3829, 0x1379, 0x3735, 0x11ea, 0x362d, 0x10a1, + 0x3c00, 0x061b, 0x3c00, 0x066a, 0x3bfe, 0x081c, 0x3bfa, 0x0a4c, 0x3bed, 0x0d16, 0x3bd5, 0x0fb3, 0x3ba9, 0x114d, 0x3b63, 0x127c, 0x3b01, 0x132f, 0x3a85, 0x1344, 0x39f4, 0x12d2, 0x3957, 0x120d, 0x38b5, 0x1122, 0x3817, 0x103c, 0x3703, 0x0ed3, 0x35f0, 0x0d6d, + 0x3c00, 0x007a, 0x3c00, 0x0089, 0x3bfe, 0x011d, 0x3bfb, 0x027c, 0x3bf0, 0x04fa, 0x3bda, 0x0881, 0x3bb1, 0x0acd, 0x3b6f, 0x0c97, 0x3b10, 0x0d7b, 0x3a93, 0x0df1, 0x39fe, 0x0def, 0x3959, 0x0d8a, 0x38af, 0x0ce9, 0x3808, 0x0c31, 0x36d5, 0x0af0, 0x35b9, 0x09a3, + 0x3c00, 0x0000, 0x3c00, 0x0001, 0x3bff, 0x0015, 0x3bfb, 0x0059, 0x3bf2, 0x00fd, 0x3bdd, 0x01df, 0x3bb7, 0x031c, 0x3b79, 0x047c, 0x3b1d, 0x05d4, 0x3aa0, 0x06d5, 0x3a08, 0x075a, 0x395d, 0x075e, 0x38aa, 0x06f7, 0x37f4, 0x0648, 0x36ac, 0x0576, 0x3586, 0x049f +] ); + +let lut = null; + +function getDFGLUT() { + + if ( lut === null ) { + + lut = new DataTexture( DATA, 16, 16, RGFormat, HalfFloatType ); + lut.name = 'DFG_LUT'; + lut.minFilter = LinearFilter; + lut.magFilter = LinearFilter; + lut.wrapS = ClampToEdgeWrapping; + lut.wrapT = ClampToEdgeWrapping; + lut.generateMipmaps = false; + lut.needsUpdate = true; + + } + + return lut; + +} + +/** + * This renderer uses WebGL 2 to display scenes. + * + * WebGL 1 is not supported since `r163`. + */ +class WebGLRenderer { + + /** + * Constructs a new WebGL renderer. + * + * @param {WebGLRenderer~Options} [parameters] - The configuration parameter. + */ + constructor( parameters = {} ) { + + const { + canvas = createCanvasElement(), + context = null, + depth = true, + stencil = false, + alpha = false, + antialias = false, + premultipliedAlpha = true, + preserveDrawingBuffer = false, + powerPreference = 'default', + failIfMajorPerformanceCaveat = false, + reversedDepthBuffer = false, + outputBufferType = UnsignedByteType, + } = parameters; + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isWebGLRenderer = true; + + let _alpha; + + if ( context !== null ) { + + if ( typeof WebGLRenderingContext !== 'undefined' && context instanceof WebGLRenderingContext ) { + + throw new Error( 'THREE.WebGLRenderer: WebGL 1 is not supported since r163.' ); + + } + + _alpha = context.getContextAttributes().alpha; + + } else { + + _alpha = alpha; + + } + + const _outputBufferType = outputBufferType; + + const INTEGER_FORMATS = new Set( [ + RGBAIntegerFormat, + RGIntegerFormat, + RedIntegerFormat + ] ); + + const UNSIGNED_TYPES = new Set( [ + UnsignedByteType, + UnsignedIntType, + UnsignedShortType, + UnsignedInt248Type, + UnsignedShort4444Type, + UnsignedShort5551Type + ] ); + + const uintClearColor = new Uint32Array( 4 ); + const intClearColor = new Int32Array( 4 ); + const objectPosition = new Vector3(); + + let currentRenderList = null; + let currentRenderState = null; + + // render() can be called from within a callback triggered by another render. + // We track this so that the nested render call gets its list and state isolated from the parent render call. + + const renderListStack = []; + const renderStateStack = []; + + // internal render target for non-UnsignedByteType color buffer + + let output = null; + + // public properties + + /** + * A canvas where the renderer draws its output. This is automatically created by the renderer + * in the constructor (if not provided already); you just need to add it to your page like so: + * ```js + * document.body.appendChild( renderer.domElement ); + * ``` + * + * @type {HTMLCanvasElement|OffscreenCanvas} + */ + this.domElement = canvas; + + /** + * A object with debug configuration settings. + * + * - `checkShaderErrors`: If it is `true`, defines whether material shader programs are + * checked for errors during compilation and linkage process. It may be useful to disable + * this check in production for performance gain. It is strongly recommended to keep these + * checks enabled during development. If the shader does not compile and link, it will not + * work and associated material will not render. + * - `onShaderError(gl, program, glVertexShader,glFragmentShader)`: A callback function that + * can be used for custom error reporting. The callback receives the WebGL context, an instance + * of WebGLProgram as well two instances of WebGLShader representing the vertex and fragment shader. + * Assigning a custom function disables the default error reporting. + * + * @type {Object} + */ + this.debug = { + + /** + * Enables error checking and reporting when shader programs are being compiled. + * @type {boolean} + */ + checkShaderErrors: true, + /** + * Diagnostics configuration for the shader generation. Only relevant for TSL. + * @type {Object} + * @property {boolean} keywords - Whether declaration names that collide with reserved keywords of the shading language should be renamed or not. + */ + diagnostics: { + keywords: false + }, + /** + * Callback for custom error reporting. + * @type {?Function} + */ + onShaderError: null + }; + + // clearing + + /** + * Whether the renderer should automatically clear its output before rendering a frame or not. + * + * @type {boolean} + * @default true + */ + this.autoClear = true; + + /** + * If {@link WebGLRenderer#autoClear} set to `true`, whether the renderer should clear + * the color buffer or not. + * + * @type {boolean} + * @default true + */ + this.autoClearColor = true; + + /** + * If {@link WebGLRenderer#autoClear} set to `true`, whether the renderer should clear + * the depth buffer or not. + * + * @type {boolean} + * @default true + */ + this.autoClearDepth = true; + + /** + * If {@link WebGLRenderer#autoClear} set to `true`, whether the renderer should clear + * the stencil buffer or not. + * + * @type {boolean} + * @default true + */ + this.autoClearStencil = true; + + // scene graph + + /** + * Whether the renderer should sort objects or not. + * + * Note: Sorting is used to attempt to properly render objects that have some + * degree of transparency. By definition, sorting objects may not work in all + * cases. Depending on the needs of application, it may be necessary to turn + * off sorting and use other methods to deal with transparency rendering e.g. + * manually determining each object's rendering order. + * + * @type {boolean} + * @default true + */ + this.sortObjects = true; + + // user-defined clipping + + /** + * User-defined clipping planes specified in world space. These planes apply globally. + * Points in space whose dot product with the plane is negative are cut away. + * + * @type {Array} + */ + this.clippingPlanes = []; + + /** + * Whether the renderer respects object-level clipping planes or not. + * + * @type {boolean} + * @default false + */ + this.localClippingEnabled = false; + + // tone mapping + + /** + * The tone mapping technique of the renderer. + * + * @type {(NoToneMapping|LinearToneMapping|ReinhardToneMapping|CineonToneMapping|ACESFilmicToneMapping|CustomToneMapping|AgXToneMapping|NeutralToneMapping)} + * @default NoToneMapping + */ + this.toneMapping = NoToneMapping; + + /** + * Exposure level of tone mapping. + * + * @type {number} + * @default 1 + */ + this.toneMappingExposure = 1.0; + + // transmission + + /** + * The normalized resolution scale for the transmission render target, measured in percentage + * of viewport dimensions. Lowering this value can result in significant performance improvements + * when using {@link MeshPhysicalMaterial#transmission}. + * + * @type {number} + * @default 1 + */ + this.transmissionResolutionScale = 1.0; + + // internal properties + + const _this = this; + + let _isContextLost = false; + let _nodesHandler = null; + + let _scratchFramebuffer = null; + let _srcFramebuffer = null; + let _dstFramebuffer = null; + + // internal state cache + + this._outputColorSpace = SRGBColorSpace; + + let _currentActiveCubeFace = 0; + let _currentActiveMipmapLevel = 0; + let _currentRenderTarget = null; + let _currentMaterialId = -1; + + let _currentCamera = null; + + const _currentViewport = new Vector4(); + const _currentScissor = new Vector4(); + let _currentScissorTest = null; + + const _currentClearColor = new Color( 0x000000 ); + let _currentClearAlpha = 0; + + // + + let _width = canvas.width; + let _height = canvas.height; + + let _pixelRatio = 1; + let _opaqueSort = null; + let _transparentSort = null; + + const _viewport = new Vector4( 0, 0, _width, _height ); + const _scissor = new Vector4( 0, 0, _width, _height ); + let _scissorTest = false; + + // frustum + + const _frustum = new Frustum(); + + // clipping + + let _clippingEnabled = false; + let _localClippingEnabled = false; + + // camera matrices cache + + const _projScreenMatrix = new Matrix4(); + + const _vector3 = new Vector3(); + + const _vector4 = new Vector4(); + + const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true }; + + let _renderBackground = false; + + function getTargetPixelRatio() { + + return _currentRenderTarget === null ? _pixelRatio : 1; + + } + + // initialize + + let _gl = context; + + function getContext( contextName, contextAttributes ) { + + return canvas.getContext( contextName, contextAttributes ); + + } + + let extensions, capabilities, state, info; + let properties, textures, environments, attributes, geometries, objects; + let programCache, materials, renderLists, renderStates, clipping, shadowMap; + + let background, morphtargets, bufferRenderer, indexedBufferRenderer; + + let utils, bindingStates, uniformsGroups; + + try { + + const contextAttributes = { + alpha: true, + depth, + stencil, + antialias, + premultipliedAlpha, + preserveDrawingBuffer, + powerPreference, + failIfMajorPerformanceCaveat, + }; + + // OffscreenCanvas does not have setAttribute, see #22811 + if ( 'setAttribute' in canvas ) canvas.setAttribute( 'data-engine', `three.js r${REVISION}` ); + + // event listeners must be registered before WebGL context is created, see #12753 + canvas.addEventListener( 'webglcontextlost', onContextLost, false ); + canvas.addEventListener( 'webglcontextrestored', onContextRestore, false ); + canvas.addEventListener( 'webglcontextcreationerror', onContextCreationError, false ); + + if ( _gl === null ) { + + const contextName = 'webgl2'; + + _gl = getContext( contextName, contextAttributes ); + + if ( _gl === null ) { + + if ( getContext( contextName ) ) { + + throw new Error( 'THREE.WebGLRenderer: Error creating WebGL context with your selected attributes.' ); + + } else { + + throw new Error( 'THREE.WebGLRenderer: Error creating WebGL context.' ); + + } + + } + + } + + initGLContext(); + + } catch ( e ) { + + canvas.removeEventListener( 'webglcontextlost', onContextLost, false ); + canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false ); + canvas.removeEventListener( 'webglcontextcreationerror', onContextCreationError, false ); + + error( 'WebGLRenderer: ' + e.message ); + throw e; + + } + + function initGLContext() { + + extensions = new WebGLExtensions( _gl ); + extensions.init(); + + utils = new WebGLUtils( _gl, extensions ); + + capabilities = new WebGLCapabilities( _gl, extensions, parameters, utils ); + + state = new WebGLState( _gl, extensions ); + + if ( capabilities.reversedDepthBuffer && reversedDepthBuffer ) { + + state.buffers.depth.setReversed( true ); + + } + + _scratchFramebuffer = _gl.createFramebuffer(); + _srcFramebuffer = _gl.createFramebuffer(); + _dstFramebuffer = _gl.createFramebuffer(); + + info = new WebGLInfo( _gl ); + properties = new WebGLProperties(); + textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ); + environments = new WebGLEnvironments( _this ); + attributes = new WebGLAttributes( _gl ); + bindingStates = new WebGLBindingStates( _gl, attributes ); + geometries = new WebGLGeometries( _gl, attributes, info, bindingStates ); + objects = new WebGLObjects( _gl, geometries, attributes, bindingStates, info ); + morphtargets = new WebGLMorphtargets( _gl, capabilities, textures ); + clipping = new WebGLClipping( properties ); + programCache = new WebGLPrograms( _this, environments, extensions, capabilities, bindingStates, clipping ); + materials = new WebGLMaterials( _this, properties ); + renderLists = new WebGLRenderLists(); + renderStates = new WebGLRenderStates( extensions ); + background = new WebGLBackground( _this, environments, state, objects, _alpha, premultipliedAlpha ); + shadowMap = new WebGLShadowMap( _this, objects, capabilities ); + uniformsGroups = new WebGLUniformsGroups( _gl, info, capabilities, state ); + + bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info ); + indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info ); + + info.programs = programCache.programs; + + /** + * Holds details about the capabilities of the current rendering context. + * + * @name WebGLRenderer#capabilities + * @type {WebGLRenderer~Capabilities} + */ + _this.capabilities = capabilities; + + /** + * Provides methods for retrieving and testing WebGL extensions. + * + * - `get(extensionName:string)`: Used to check whether a WebGL extension is supported + * and return the extension object if available. + * - `has(extensionName:string)`: returns `true` if the extension is supported. + * + * @name WebGLRenderer#extensions + * @type {Object} + */ + _this.extensions = extensions; + + /** + * Used to track properties of other objects like native WebGL objects. + * + * @name WebGLRenderer#properties + * @type {Object} + */ + _this.properties = properties; + + /** + * Manages the render lists of the renderer. + * + * @name WebGLRenderer#renderLists + * @type {Object} + */ + _this.renderLists = renderLists; + + + + /** + * Interface for managing shadows. + * + * @name WebGLRenderer#shadowMap + * @type {WebGLRenderer~ShadowMap} + */ + _this.shadowMap = shadowMap; + + /** + * Interface for managing the WebGL state. + * + * @name WebGLRenderer#state + * @type {Object} + */ + _this.state = state; + + /** + * Holds a series of statistical information about the GPU memory + * and the rendering process. Useful for debugging and monitoring. + * + * By default these data are reset at each render call but when having + * multiple render passes per frame (e.g. when using post processing) it can + * be preferred to reset with a custom pattern. First, set `autoReset` to + * `false`. + * ```js + * renderer.info.autoReset = false; + * ``` + * Call `reset()` whenever you have finished to render a single frame. + * ```js + * renderer.info.reset(); + * ``` + * + * @name WebGLRenderer#info + * @type {WebGLRenderer~Info} + */ + _this.info = info; + + } + + // initialize internal render target for non-UnsignedByteType color buffer + + if ( _outputBufferType !== UnsignedByteType ) { + + output = new WebGLOutput( _outputBufferType, canvas.width, canvas.height, antialias, depth, stencil ); + + } + + // xr + + const xr = new WebXRManager( _this, _gl ); + + /** + * A reference to the XR manager. + * + * @type {WebXRManager} + */ + this.xr = xr; + + /** + * Returns the rendering context. + * + * @return {WebGL2RenderingContext} The rendering context. + */ + this.getContext = function () { + + return _gl; + + }; + + /** + * Returns the rendering context attributes. + * + * @return {WebGLContextAttributes} The rendering context attributes. + */ + this.getContextAttributes = function () { + + return _gl.getContextAttributes(); + + }; + + /** + * Simulates a loss of the WebGL context. This requires support for the `WEBGL_lose_context` extension. + */ + this.forceContextLoss = function () { + + const extension = extensions.get( 'WEBGL_lose_context' ); + if ( extension ) extension.loseContext(); + + }; + + /** + * Simulates a restore of the WebGL context. This requires support for the `WEBGL_lose_context` extension. + */ + this.forceContextRestore = function () { + + const extension = extensions.get( 'WEBGL_lose_context' ); + if ( extension ) extension.restoreContext(); + + }; + + /** + * Returns the pixel ratio. + * + * @return {number} The pixel ratio. + */ + this.getPixelRatio = function () { + + return _pixelRatio; + + }; + + /** + * Sets the given pixel ratio and resizes the canvas if necessary. + * + * @param {number} value - The pixel ratio. + */ + this.setPixelRatio = function ( value ) { + + if ( value === undefined ) return; + + _pixelRatio = value; + + this.setSize( _width, _height, false ); + + }; + + /** + * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio. + * + * @param {Vector2} target - The method writes the result in this target object. + * @return {Vector2} The renderer's size in logical pixels. + */ + this.getSize = function ( target ) { + + return target.set( _width, _height ); + + }; + + /** + * Resizes the output canvas to (width, height) with device pixel ratio taken + * into account, and also sets the viewport to fit that size, starting in (0, + * 0). Setting `updateStyle` to false prevents any style changes to the output canvas. + * + * @param {number} width - The width in logical pixels. + * @param {number} height - The height in logical pixels. + * @param {boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not. + */ + this.setSize = function ( width, height, updateStyle = true ) { + + if ( xr.isPresenting ) { + + warn( 'WebGLRenderer: Can\'t change size while VR device is presenting.' ); + return; + + } + + _width = width; + _height = height; + + canvas.width = Math.floor( width * _pixelRatio ); + canvas.height = Math.floor( height * _pixelRatio ); + + if ( updateStyle === true ) { + + canvas.style.width = width + 'px'; + canvas.style.height = height + 'px'; + + } + + if ( output !== null ) { + + output.setSize( canvas.width, canvas.height ); + + } + + this.setViewport( 0, 0, width, height ); + + }; + + /** + * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio. + * + * @param {Vector2} target - The method writes the result in this target object. + * @return {Vector2} The drawing buffer size. + */ + this.getDrawingBufferSize = function ( target ) { + + return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor(); + + }; + + /** + * This method allows to define the drawing buffer size by specifying + * width, height and pixel ratio all at once. The size of the drawing + * buffer is computed with this formula: + * ```js + * size.x = width * pixelRatio; + * size.y = height * pixelRatio; + * ``` + * + * @param {number} width - The width in logical pixels. + * @param {number} height - The height in logical pixels. + * @param {number} pixelRatio - The pixel ratio. + */ + this.setDrawingBufferSize = function ( width, height, pixelRatio ) { + + _width = width; + _height = height; + + _pixelRatio = pixelRatio; + + canvas.width = Math.floor( width * pixelRatio ); + canvas.height = Math.floor( height * pixelRatio ); + + this.setViewport( 0, 0, width, height ); + + }; + + /** + * Sets the post-processing effects to be applied after rendering. + * + * @param {Array} effects - An array of post-processing effects. + */ + this.setEffects = function ( effects ) { + + if ( _outputBufferType === UnsignedByteType ) { + + error( 'WebGLRenderer: setEffects() requires outputBufferType set to HalfFloatType or FloatType.' ); + return; + + } + + if ( effects ) { + + for ( let i = 0; i < effects.length; i ++ ) { + + if ( effects[ i ].isOutputPass === true ) { + + warn( 'WebGLRenderer: OutputPass is not needed in setEffects(). Tone mapping and color space conversion are applied automatically.' ); + break; + + } + + } + + } + + output.setEffects( effects || [] ); + + }; + + /** + * Returns the current viewport definition. + * + * @param {Vector2} target - The method writes the result in this target object. + * @return {Vector2} The current viewport definition. + */ + this.getCurrentViewport = function ( target ) { + + return target.copy( _currentViewport ); + + }; + + /** + * Returns the viewport definition. + * + * @param {Vector4} target - The method writes the result in this target object. + * @return {Vector4} The viewport definition. + */ + this.getViewport = function ( target ) { + + return target.copy( _viewport ); + + }; + + /** + * Sets the viewport to render from `(x, y)` to `(x + width, y + height)`. + * + * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit. + * Or alternatively a four-component vector specifying all the parameters of the viewport. + * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit. + * @param {number} width - The width of the viewport in logical pixel unit. + * @param {number} height - The height of the viewport in logical pixel unit. + */ + this.setViewport = function ( x, y, width, height ) { + + if ( x.isVector4 ) { + + _viewport.set( x.x, x.y, x.z, x.w ); + + } else { + + _viewport.set( x, y, width, height ); + + } + + state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).round() ); + + }; + + /** + * Returns the scissor region. + * + * @param {Vector4} target - The method writes the result in this target object. + * @return {Vector4} The scissor region. + */ + this.getScissor = function ( target ) { + + return target.copy( _scissor ); + + }; + + /** + * Sets the scissor region to render from `(x, y)` to `(x + width, y + height)`. + * + * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the scissor region origin in logical pixel unit. + * Or alternatively a four-component vector specifying all the parameters of the scissor region. + * @param {number} y - The vertical coordinate for the lower left corner of the scissor region origin in logical pixel unit. + * @param {number} width - The width of the scissor region in logical pixel unit. + * @param {number} height - The height of the scissor region in logical pixel unit. + */ + this.setScissor = function ( x, y, width, height ) { + + if ( x.isVector4 ) { + + _scissor.set( x.x, x.y, x.z, x.w ); + + } else { + + _scissor.set( x, y, width, height ); + + } + + state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).round() ); + + }; + + /** + * Returns `true` if the scissor test is enabled. + * + * @return {boolean} Whether the scissor test is enabled or not. + */ + this.getScissorTest = function () { + + return _scissorTest; + + }; + + /** + * Enable or disable the scissor test. When this is enabled, only the pixels + * within the defined scissor area will be affected by further renderer + * actions. + * + * @param {boolean} boolean - Whether the scissor test is enabled or not. + */ + this.setScissorTest = function ( boolean ) { + + state.setScissorTest( _scissorTest = boolean ); + + }; + + /** + * Sets a custom opaque sort function for the render lists. Pass `null` + * to use the default `painterSortStable` function. + * + * @param {?Function} method - The opaque sort function. + */ + this.setOpaqueSort = function ( method ) { + + _opaqueSort = method; + + }; + + /** + * Sets a custom transparent sort function for the render lists. Pass `null` + * to use the default `reversePainterSortStable` function. + * + * @param {?Function} method - The opaque sort function. + */ + this.setTransparentSort = function ( method ) { + + _transparentSort = method; + + }; + + // Clearing + + /** + * Returns the clear color. + * + * @param {Color} target - The method writes the result in this target object. + * @return {Color} The clear color. + */ + this.getClearColor = function ( target ) { + + return target.copy( background.getClearColor() ); + + }; + + /** + * Sets the clear color and alpha. + * + * @param {Color} color - The clear color. + * @param {number} [alpha=1] - The clear alpha. + */ + this.setClearColor = function () { + + background.setClearColor( ...arguments ); + + }; + + /** + * Returns the clear alpha. Ranges within `[0,1]`. + * + * @return {number} The clear alpha. + */ + this.getClearAlpha = function () { + + return background.getClearAlpha(); + + }; + + /** + * Sets the clear alpha. + * + * @param {number} alpha - The clear alpha. + */ + this.setClearAlpha = function () { + + background.setClearAlpha( ...arguments ); + + }; + + /** + * Tells the renderer to clear its color, depth or stencil drawing buffer(s). + * This method initializes the buffers to the current clear color values. + * + * @param {boolean} [color=true] - Whether the color buffer should be cleared or not. + * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not. + * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not. + */ + this.clear = function ( color = true, depth = true, stencil = true ) { + + let bits = 0; + + if ( color ) { + + // check if we're trying to clear an integer target + let isIntegerFormat = false; + if ( _currentRenderTarget !== null ) { + + const targetFormat = _currentRenderTarget.texture.format; + isIntegerFormat = INTEGER_FORMATS.has( targetFormat ); + + } + + // use the appropriate clear functions to clear the target if it's a signed + // or unsigned integer target + if ( isIntegerFormat ) { + + const targetType = _currentRenderTarget.texture.type; + const isUnsignedType = UNSIGNED_TYPES.has( targetType ); + + const clearColor = background.getClearColor(); + const a = background.getClearAlpha(); + const r = clearColor.r; + const g = clearColor.g; + const b = clearColor.b; + + if ( isUnsignedType ) { + + uintClearColor[ 0 ] = r; + uintClearColor[ 1 ] = g; + uintClearColor[ 2 ] = b; + uintClearColor[ 3 ] = a; + _gl.clearBufferuiv( _gl.COLOR, 0, uintClearColor ); + + } else { + + intClearColor[ 0 ] = r; + intClearColor[ 1 ] = g; + intClearColor[ 2 ] = b; + intClearColor[ 3 ] = a; + _gl.clearBufferiv( _gl.COLOR, 0, intClearColor ); + + } + + } else { + + bits |= _gl.COLOR_BUFFER_BIT; + + } + + } + + if ( depth ) { + + bits |= _gl.DEPTH_BUFFER_BIT; + this.state.buffers.depth.setMask( true ); + + } + + if ( stencil ) { + + bits |= _gl.STENCIL_BUFFER_BIT; + this.state.buffers.stencil.setMask( 0xffffffff ); + + } + + if ( bits !== 0 ) { + + _gl.clear( bits ); + + } + + }; + + /** + * Clears the color buffer. Equivalent to calling `renderer.clear( true, false, false )`. + */ + this.clearColor = function () { + + this.clear( true, false, false ); + + }; + + /** + * Clears the depth buffer. Equivalent to calling `renderer.clear( false, true, false )`. + */ + this.clearDepth = function () { + + this.clear( false, true, false ); + + }; + + /** + * Clears the stencil buffer. Equivalent to calling `renderer.clear( false, false, true )`. + */ + this.clearStencil = function () { + + this.clear( false, false, true ); + + }; + + /** + * Sets a compatibility node builder for rendering node materials with WebGLRenderer. + * This enables using TSL (Three.js Shading Language) node materials to prepare + * for migration to WebGPURenderer. + * + * @param {WebGLNodesHandler} nodesHandler - The node builder instance. + */ + this.setNodesHandler = function ( nodesHandler ) { + + nodesHandler.setRenderer( this ); + _nodesHandler = nodesHandler; + + }; + + /** + * Frees the GPU-related resources allocated by this instance. Call this + * method whenever this instance is no longer used in your app. + */ + this.dispose = function () { + + canvas.removeEventListener( 'webglcontextlost', onContextLost, false ); + canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false ); + canvas.removeEventListener( 'webglcontextcreationerror', onContextCreationError, false ); + + background.dispose(); + renderLists.dispose(); + renderStates.dispose(); + properties.dispose(); + environments.dispose(); + objects.dispose(); + bindingStates.dispose(); + uniformsGroups.dispose(); + programCache.dispose(); + + xr.dispose(); + + xr.removeEventListener( 'sessionstart', onXRSessionStart ); + xr.removeEventListener( 'sessionend', onXRSessionEnd ); + + animation.stop(); + + }; + + // Events + + function onContextLost( event ) { + + event.preventDefault(); + + log( 'WebGLRenderer: Context Lost.' ); + + _isContextLost = true; + + } + + function onContextRestore( /* event */ ) { + + log( 'WebGLRenderer: Context Restored.' ); + + _isContextLost = false; + + const infoAutoReset = info.autoReset; + const shadowMapEnabled = shadowMap.enabled; + const shadowMapAutoUpdate = shadowMap.autoUpdate; + const shadowMapNeedsUpdate = shadowMap.needsUpdate; + const shadowMapType = shadowMap.type; + + initGLContext(); + + info.autoReset = infoAutoReset; + shadowMap.enabled = shadowMapEnabled; + shadowMap.autoUpdate = shadowMapAutoUpdate; + shadowMap.needsUpdate = shadowMapNeedsUpdate; + shadowMap.type = shadowMapType; + + } + + function onContextCreationError( event ) { + + error( 'WebGLRenderer: A WebGL context could not be created. Reason: ', event.statusMessage ); + + } + + function onMaterialDispose( event ) { + + const material = event.target; + + material.removeEventListener( 'dispose', onMaterialDispose ); + + deallocateMaterial( material ); + + } + + // Buffer deallocation + + function deallocateMaterial( material ) { + + releaseMaterialProgramReferences( material ); + + properties.remove( material ); + + } + + + function releaseMaterialProgramReferences( material ) { + + const programs = properties.get( material ).programs; + + if ( programs !== undefined ) { + + programs.forEach( function ( program ) { + + programCache.releaseProgram( program ); + + } ); + + if ( material.isShaderMaterial ) { + + programCache.releaseShaderCache( material ); + + } + + } + + } + + // Buffer rendering + + this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) { + + if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null) + + const frontFaceCW = ( object.isMesh && object.matrixWorld.determinantAffine() < 0 ); + + const program = setProgram( camera, scene, geometry, material, object ); + + state.setMaterial( material, frontFaceCW ); + + // + + let index = geometry.index; + let rangeFactor = 1; + + if ( material.wireframe === true ) { + + index = geometries.getWireframeAttribute( geometry ); + + if ( index === undefined ) return; + + rangeFactor = 2; + + } + + // + + const drawRange = geometry.drawRange; + const position = geometry.attributes.position; + + let drawStart = drawRange.start * rangeFactor; + let drawEnd = ( drawRange.start + drawRange.count ) * rangeFactor; + + if ( group !== null ) { + + drawStart = Math.max( drawStart, group.start * rangeFactor ); + drawEnd = Math.min( drawEnd, ( group.start + group.count ) * rangeFactor ); + + } + + if ( index !== null ) { + + drawStart = Math.max( drawStart, 0 ); + drawEnd = Math.min( drawEnd, index.count ); + + } else if ( position !== undefined && position !== null ) { + + drawStart = Math.max( drawStart, 0 ); + drawEnd = Math.min( drawEnd, position.count ); + + } + + const drawCount = drawEnd - drawStart; + + if ( drawCount < 0 || drawCount === Infinity ) return; + + // + + bindingStates.setup( object, material, program, geometry, index ); + + let attribute; + let renderer = bufferRenderer; + + if ( index !== null ) { + + attribute = attributes.get( index ); + + renderer = indexedBufferRenderer; + renderer.setIndex( attribute ); + + } + + // + + if ( object.isMesh ) { + + if ( material.wireframe === true ) { + + state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() ); + renderer.setMode( _gl.LINES ); + + } else { + + renderer.setMode( _gl.TRIANGLES ); + + } + + } else if ( object.isLine ) { + + let lineWidth = material.linewidth; + + if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material + + state.setLineWidth( lineWidth * getTargetPixelRatio() ); + + if ( object.isLineSegments ) { + + renderer.setMode( _gl.LINES ); + + } else if ( object.isLineLoop ) { + + renderer.setMode( _gl.LINE_LOOP ); + + } else { + + renderer.setMode( _gl.LINE_STRIP ); + + } + + } else if ( object.isPoints ) { + + renderer.setMode( _gl.POINTS ); + + } else if ( object.isSprite ) { + + renderer.setMode( _gl.TRIANGLES ); + + } + + if ( object.isBatchedMesh ) { + + if ( ! extensions.get( 'WEBGL_multi_draw' ) ) { + + const starts = object._multiDrawStarts; + const counts = object._multiDrawCounts; + const drawCount = object._multiDrawCount; + const bytesPerElement = index ? attributes.get( index ).bytesPerElement : 1; + const uniforms = properties.get( material ).currentProgram.getUniforms(); + for ( let i = 0; i < drawCount; i ++ ) { + + uniforms.setValue( _gl, '_gl_DrawID', i ); + renderer.render( starts[ i ] / bytesPerElement, counts[ i ] ); + + } + + } else { + + renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount ); + + } + + } else if ( object.isInstancedMesh ) { + + renderer.renderInstances( drawStart, drawCount, object.count ); + + } else if ( geometry.isInstancedBufferGeometry ) { + + const maxInstanceCount = geometry._maxInstanceCount !== undefined ? geometry._maxInstanceCount : Infinity; + const instanceCount = Math.min( geometry.instanceCount, maxInstanceCount ); + + renderer.renderInstances( drawStart, drawCount, instanceCount ); + + } else { + + renderer.render( drawStart, drawCount ); + + } + + }; + + // Compile + + function prepareMaterial( material, scene, camera, object ) { + + if ( _nodesHandler !== null && material.isNodeMaterial ) _nodesHandler.setObject( object, material ); + + if ( _clippingEnabled === true ) clipping.setState( material, camera, false ); + + if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) { + + material.side = BackSide; + material.needsUpdate = true; + getProgram( material, scene, object ); + + material.side = FrontSide; + material.needsUpdate = true; + getProgram( material, scene, object ); + + material.side = DoubleSide; + + } else { + + getProgram( material, scene, object ); + + } + + } + + /** + * Compiles all materials in the scene with the camera. This is useful to precompile shaders + * before the first rendering. If you want to add a 3D object to an existing scene, use the third + * optional parameter for applying the target scene. + * + * Note that the (target) scene's lighting and environment must be configured before calling this method. + * + * @param {Object3D} scene - The scene or another type of 3D object to precompile. + * @param {Camera} camera - The camera. + * @param {?Scene} [targetScene=null] - The target scene. + * @return {Set} The precompiled materials. + */ + this.compile = function ( scene, camera, targetScene = null ) { + + if ( targetScene === null ) targetScene = scene; + if ( _nodesHandler !== null ) _nodesHandler.renderStart( scene, camera, targetScene ); + + currentRenderState = renderStates.get( targetScene ); + currentRenderState.init( camera ); + + renderStateStack.push( currentRenderState ); + + // gather lights from both the target scene and the new object that will be added to the scene. + + targetScene.traverseVisible( function ( object ) { + + if ( object.isLight && object.layers.test( camera.layers ) ) { + + currentRenderState.pushLight( object ); + + if ( object.castShadow ) { + + currentRenderState.pushShadow( object ); + + } + + } + + } ); + + if ( scene !== targetScene ) { + + scene.traverseVisible( function ( object ) { + + if ( object.isLight && object.layers.test( camera.layers ) ) { + + currentRenderState.pushLight( object ); + + if ( object.castShadow ) { + + currentRenderState.pushShadow( object ); + + } + + } + + } ); + + } + + currentRenderState.setupLights(); + if ( _nodesHandler !== null ) _nodesHandler.updateLights( currentRenderState.state.lightsArray ); + + _localClippingEnabled = this.localClippingEnabled; + _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled ); + + if ( _clippingEnabled === true ) clipping.setGlobalState( this.clippingPlanes, camera ); + + // node materials reference the shadow map when they are built, so it must exist by now + + if ( _nodesHandler !== null ) shadowMap.render( currentRenderState.state.shadowsArray, targetScene, camera ); + + // Only initialize materials in the new scene, not the targetScene. + + const materials = new Set(); + + scene.traverse( function ( object ) { + + if ( ! ( object.isMesh || object.isPoints || object.isLine || object.isSprite ) ) { + + return; + + } + + const material = object.material; + + if ( material ) { + + if ( Array.isArray( material ) ) { + + for ( let i = 0; i < material.length; i ++ ) { + + const material2 = material[ i ]; + + prepareMaterial( material2, targetScene, camera, object ); + materials.add( material2 ); + + } + + } else { + + prepareMaterial( material, targetScene, camera, object ); + materials.add( material ); + + } + + } + + } ); + + currentRenderState = renderStateStack.pop(); + if ( _nodesHandler !== null ) _nodesHandler.renderEnd(); + + return materials; + + }; + + // compileAsync + + /** + * Asynchronous version of {@link WebGLRenderer#compile}. + * + * This method makes use of the `KHR_parallel_shader_compile` WebGL extension. Hence, + * it is recommended to use this version of `compile()` whenever possible. + * + * @async + * @param {Object3D} scene - The scene or another type of 3D object to precompile. + * @param {Camera} camera - The camera. + * @param {?Scene} [targetScene=null] - The target scene. + * @return {Promise} A Promise that resolves when the given scene can be rendered without unnecessary stalling due to shader compilation. + */ + this.compileAsync = function ( scene, camera, targetScene = null ) { + + const materials = this.compile( scene, camera, targetScene ); + + // Wait for all the materials in the new object to indicate that they're + // ready to be used before resolving the promise. + + return new Promise( ( resolve ) => { + + function checkMaterialsReady() { + + materials.forEach( function ( material ) { + + const materialProperties = properties.get( material ); + const program = materialProperties.currentProgram; + + if ( program === undefined || program.isReady() ) { + + // stop waiting for materials that are ready to use or have been disposed + materials.delete( material ); + + } + + } ); + + // once the list of compiling materials is empty, call the callback + + if ( materials.size === 0 ) { + + resolve( scene ); + return; + + } + + // if some materials are still not ready, wait a bit and check again + + setTimeout( checkMaterialsReady, 10 ); + + } + + if ( extensions.get( 'KHR_parallel_shader_compile' ) !== null ) { + + // If we can check the compilation status of the materials without + // blocking then do so right away. + + checkMaterialsReady(); + + } else { + + // Otherwise start by waiting a bit to give the materials we just + // initialized a chance to finish. + + setTimeout( checkMaterialsReady, 10 ); + + } + + } ); + + }; + + // Animation Loop + + let onAnimationFrameCallback = null; + + function onAnimationFrame( time ) { + + if ( onAnimationFrameCallback ) onAnimationFrameCallback( time ); + + } + + function onXRSessionStart() { + + animation.stop(); + + } + + function onXRSessionEnd() { + + animation.start(); + + } + + const animation = new WebGLAnimation(); + animation.setAnimationLoop( onAnimationFrame ); + + if ( typeof self !== 'undefined' ) animation.setContext( self ); + + /** + * Applications are advised to always define the animation loop + * with this method and not manually with `requestAnimationFrame()` + * for best compatibility. + * + * @param {?onAnimationCallback} callback - The application's animation loop. + */ + this.setAnimationLoop = function ( callback ) { + + onAnimationFrameCallback = callback; + xr.setAnimationLoop( callback ); + + ( callback === null ) ? animation.stop() : animation.start(); + + }; + + xr.addEventListener( 'sessionstart', onXRSessionStart ); + xr.addEventListener( 'sessionend', onXRSessionEnd ); + + // Rendering + + /** + * Renders the given scene (or other type of 3D object) using the given camera. + * + * The render is done to a previously specified render target set by calling {@link WebGLRenderer#setRenderTarget} + * or to the canvas as usual. + * + * By default render buffers are cleared before rendering but you can prevent + * this by setting the property `autoClear` to `false`. If you want to prevent + * only certain buffers being cleared you can `autoClearColor`, `autoClearDepth` + * or `autoClearStencil` to `false`. To force a clear, use {@link WebGLRenderer#clear}. + * + * @param {Object3D} scene - The scene to render. + * @param {Camera} camera - The camera. + */ + this.render = function ( scene, camera ) { + + if ( camera !== undefined && camera.isCamera !== true ) { + + error( 'WebGLRenderer.render: camera is not an instance of THREE.Camera.' ); + return; + + } + + if ( _isContextLost === true ) return; + + // update node builder if available + if ( _nodesHandler !== null ) { + + _nodesHandler.renderStart( scene, camera ); + + } + + // use internal render target for HalfFloatType color buffer (only when tone mapping is enabled) + + const isXRPresenting = xr.enabled === true && xr.isPresenting === true; + + const useOutput = output !== null && ( _currentRenderTarget === null || isXRPresenting ) && output.begin( _this, _currentRenderTarget ); + + // update scene graph + + if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld(); + + // update camera matrices and frustum + + if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld(); + + if ( xr.enabled === true && xr.isPresenting === true && ( output === null || output.isCompositing() === false ) ) { + + if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera ); + + camera = xr.getCamera(); // use XR camera for rendering + + } + + // + if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, _currentRenderTarget ); + + currentRenderState = renderStates.get( scene, renderStateStack.length ); + currentRenderState.init( camera ); + + currentRenderState.state.textureUnits = textures.getTextureUnits(); + renderStateStack.push( currentRenderState ); + + _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse ); + _frustum.setFromProjectionMatrix( _projScreenMatrix, WebGLCoordinateSystem, camera.reversedDepth ); + + _localClippingEnabled = this.localClippingEnabled; + _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled ); + + currentRenderList = renderLists.get( scene, renderListStack.length ); + currentRenderList.init(); + + renderListStack.push( currentRenderList ); + + if ( xr.enabled === true && xr.isPresenting === true ) { + + const depthSensingMesh = _this.xr.getDepthSensingMesh(); + + if ( depthSensingMesh !== null ) { + + projectObject( depthSensingMesh, camera, - Infinity, _this.sortObjects ); + + } + + } + + projectObject( scene, camera, 0, _this.sortObjects ); + + currentRenderList.finish(); + if ( _nodesHandler !== null ) _nodesHandler.updateLights( currentRenderState.state.lightsArray ); + + if ( _this.sortObjects === true ) { + + currentRenderList.sort( _opaqueSort, _transparentSort ); + + } + + _renderBackground = xr.enabled === false || xr.isPresenting === false || xr.hasDepthSensing() === false; + if ( _renderBackground ) { + + background.addToRenderList( currentRenderList, scene ); + + } + + // + + this.info.render.frame ++; + + if ( this.info.autoReset === true ) this.info.reset(); + + if ( _clippingEnabled === true ) clipping.beginShadows(); + + const shadowsArray = currentRenderState.state.shadowsArray; + + shadowMap.render( shadowsArray, scene, camera ); + + if ( _clippingEnabled === true ) clipping.endShadows(); + + // + + // render scene (skip if first effect is a render pass - it will render the scene itself) + + const skipSceneRender = useOutput && output.hasRenderPass(); + + if ( skipSceneRender === false ) { + + const opaqueObjects = currentRenderList.opaque; + const transmissiveObjects = currentRenderList.transmissive; + + currentRenderState.setupLights(); + + if ( camera.isArrayCamera ) { + + const cameras = camera.cameras; + + if ( transmissiveObjects.length > 0 ) { + + for ( let i = 0, l = cameras.length; i < l; i ++ ) { + + const camera2 = cameras[ i ]; + + renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera2 ); + + } + + } + + if ( _renderBackground ) background.render( scene ); + + for ( let i = 0, l = cameras.length; i < l; i ++ ) { + + const camera2 = cameras[ i ]; + + renderScene( currentRenderList, scene, camera2, camera2.viewport ); + + } + + } else { + + if ( transmissiveObjects.length > 0 ) renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera ); + + if ( _renderBackground ) background.render( scene ); + + renderScene( currentRenderList, scene, camera ); + + } + + } + + // + + if ( _currentRenderTarget !== null && _currentActiveMipmapLevel === 0 ) { + + // resolve multisample renderbuffers to a single-sample texture if necessary + + textures.updateMultisampleRenderTarget( _currentRenderTarget ); + + // Generate mipmap if we're using any kind of mipmap filtering + + textures.updateRenderTargetMipmap( _currentRenderTarget ); + + } + + // copy from internal render target to canvas using fullscreen quad + + if ( useOutput ) { + + output.end( _this ); + + } + + // + + if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera ); + + // _gl.finish(); + + bindingStates.resetDefaultState(); + _currentMaterialId = -1; + _currentCamera = null; + + renderStateStack.pop(); + + if ( renderStateStack.length > 0 ) { + + currentRenderState = renderStateStack[ renderStateStack.length - 1 ]; + + textures.setTextureUnits( currentRenderState.state.textureUnits ); + + if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, currentRenderState.state.camera ); + + } else { + + currentRenderState = null; + + } + + renderListStack.pop(); + + if ( renderListStack.length > 0 ) { + + currentRenderList = renderListStack[ renderListStack.length - 1 ]; + + } else { + + currentRenderList = null; + + } + + if ( _nodesHandler !== null ) { + + _nodesHandler.renderEnd(); + + } + + }; + + function projectObject( object, camera, groupOrder, sortObjects ) { + + if ( object.visible === false ) return; + + const visible = object.layers.test( camera.layers ); + + if ( visible ) { + + if ( object.isGroup ) { + + groupOrder = object.renderOrder; + + } else if ( object.isLOD ) { + + if ( object.autoUpdate === true ) object.update( camera ); + + } else if ( object.isLightProbeGrid ) { + + currentRenderState.pushLightProbeGrid( object ); + + } else if ( object.isLight ) { + + currentRenderState.pushLight( object ); + + if ( object.castShadow ) { + + currentRenderState.pushShadow( object ); + + } + + } else if ( object.isSprite ) { + + if ( ! object.frustumCulled || object.intersectsFrustum( _frustum ) ) { + + if ( sortObjects ) { + + _vector4.setFromMatrixPosition( object.matrixWorld ) + .applyMatrix4( _projScreenMatrix ); + + } + + const geometry = objects.update( object ); + const material = object.material; + + if ( material.visible ) { + + currentRenderList.push( object, geometry, material, groupOrder, _vector4.z, null, camera ); + + } + + } + + } else if ( object.isMesh || object.isLine || object.isPoints ) { + + if ( ! object.frustumCulled || object.intersectsFrustum( _frustum ) ) { + + const geometry = objects.update( object ); + const material = object.material; + + if ( sortObjects ) { + + if ( object.boundingSphere !== undefined ) { + + if ( object.boundingSphere === null ) object.computeBoundingSphere(); + _vector4.copy( object.boundingSphere.center ); + + } else { + + if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); + _vector4.copy( geometry.boundingSphere.center ); + + } + + _vector4 + .applyMatrix4( object.matrixWorld ) + .applyMatrix4( _projScreenMatrix ); + + } + + if ( Array.isArray( material ) ) { + + const groups = geometry.groups; + + for ( let i = 0, l = groups.length; i < l; i ++ ) { + + const group = groups[ i ]; + const groupMaterial = material[ group.materialIndex ]; + + if ( groupMaterial && groupMaterial.visible ) { + + currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group, camera ); + + } + + } + + } else if ( material.visible ) { + + currentRenderList.push( object, geometry, material, groupOrder, _vector4.z, null, camera ); + + } + + } + + } + + } + + const children = object.children; + + for ( let i = 0, l = children.length; i < l; i ++ ) { + + projectObject( children[ i ], camera, groupOrder, sortObjects ); + + } + + } + + function renderScene( currentRenderList, scene, camera, viewport ) { + + const { opaque: opaqueObjects, transmissive: transmissiveObjects, transparent: transparentObjects } = currentRenderList; + + currentRenderState.setupLightsView( camera ); + + if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera ); + + if ( viewport ) state.viewport( _currentViewport.copy( viewport ) ); + + if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera ); + if ( transmissiveObjects.length > 0 ) renderObjects( transmissiveObjects, scene, camera ); + if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera ); + + // Ensure depth buffer writing is enabled so it can be cleared on next render + + state.buffers.depth.setTest( true ); + state.buffers.depth.setMask( true ); + state.buffers.color.setMask( true ); + + state.setPolygonOffset( false ); + + } + + function renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera ) { + + const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null; + + if ( overrideMaterial !== null ) { + + return; + + } + + if ( currentRenderState.state.transmissionRenderTarget[ camera.id ] === undefined ) { + + const hasHalfFloatSupport = extensions.has( 'EXT_color_buffer_half_float' ) || extensions.has( 'EXT_color_buffer_float' ); + + currentRenderState.state.transmissionRenderTarget[ camera.id ] = new WebGLRenderTarget( 1, 1, { + generateMipmaps: true, + type: hasHalfFloatSupport ? HalfFloatType : UnsignedByteType, + minFilter: LinearMipmapLinearFilter, + samples: Math.max( 4, capabilities.samples ), // to avoid feedback loops, the transmission render target requires a resolve, see #26177 + stencilBuffer: stencil, + resolveDepthBuffer: false, + resolveStencilBuffer: false, + storeMultisampledDepthBuffer: false, + storeMultisampledStencilBuffer: false, + colorSpace: ColorManagement.workingColorSpace, + } ); + + // debug + + /* + const geometry = new PlaneGeometry(); + const material = new MeshBasicMaterial( { map: _transmissionRenderTarget.texture } ); + + const mesh = new Mesh( geometry, material ); + scene.add( mesh ); + */ + + } + + const transmissionRenderTarget = currentRenderState.state.transmissionRenderTarget[ camera.id ]; + + const activeViewport = camera.viewport || _currentViewport; + transmissionRenderTarget.setSize( activeViewport.z * _this.transmissionResolutionScale, activeViewport.w * _this.transmissionResolutionScale ); + + // + + const currentRenderTarget = _this.getRenderTarget(); + const currentActiveCubeFace = _this.getActiveCubeFace(); + const currentActiveMipmapLevel = _this.getActiveMipmapLevel(); + + _this.setRenderTarget( transmissionRenderTarget ); + + _this.getClearColor( _currentClearColor ); + _currentClearAlpha = _this.getClearAlpha(); + if ( _currentClearAlpha < 1 ) _this.setClearColor( 0xffffff, 0.5 ); + + _this.clear(); + + if ( _renderBackground ) background.render( scene ); + + // Turn off the features which can affect the frag color for opaque objects pass. + // Otherwise they are applied twice in opaque objects pass and transmission objects pass. + const currentToneMapping = _this.toneMapping; + _this.toneMapping = NoToneMapping; + + // Remove viewport from camera to avoid nested render calls resetting viewport to it (e.g Reflector). + // Transmission render pass requires viewport to match the transmissionRenderTarget. + const currentCameraViewport = camera.viewport; + if ( camera.viewport !== undefined ) camera.viewport = undefined; + + currentRenderState.setupLightsView( camera ); + + if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera ); + + renderObjects( opaqueObjects, scene, camera ); + + textures.updateMultisampleRenderTarget( transmissionRenderTarget ); + textures.updateRenderTargetMipmap( transmissionRenderTarget ); + + if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === false ) { // see #28131 + + let renderTargetNeedsUpdate = false; + + for ( let i = 0, l = transmissiveObjects.length; i < l; i ++ ) { + + const renderItem = transmissiveObjects[ i ]; + + const { object, geometry, material, group } = renderItem; + + if ( material.side === DoubleSide && object.layers.test( camera.layers ) ) { + + const currentSide = material.side; + + material.side = BackSide; + material.needsUpdate = true; + + renderObject( object, scene, camera, geometry, material, group ); + + material.side = currentSide; + material.needsUpdate = true; + + renderTargetNeedsUpdate = true; + + } + + } + + if ( renderTargetNeedsUpdate === true ) { + + textures.updateMultisampleRenderTarget( transmissionRenderTarget ); + textures.updateRenderTargetMipmap( transmissionRenderTarget ); + + } + + } + + _this.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel ); + + _this.setClearColor( _currentClearColor, _currentClearAlpha ); + + if ( currentCameraViewport !== undefined ) camera.viewport = currentCameraViewport; + + _this.toneMapping = currentToneMapping; + + } + + function renderObjects( renderList, scene, camera ) { + + const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null; + + for ( let i = 0, l = renderList.length; i < l; i ++ ) { + + const renderItem = renderList[ i ]; + + const { object, geometry, group } = renderItem; + let material = renderItem.material; + + if ( material.allowOverride === true && overrideMaterial !== null ) { + + material = overrideMaterial; + + } + + if ( object.layers.test( camera.layers ) ) { + + renderObject( object, scene, camera, geometry, material, group ); + + } + + } + + } + + function renderObject( object, scene, camera, geometry, material, group ) { + + if ( _nodesHandler !== null && material.isNodeMaterial ) _nodesHandler.setObject( object, material ); + object.onBeforeRender( _this, scene, camera, geometry, material, group ); + + object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld ); + object.normalMatrix.getNormalMatrix( object.modelViewMatrix ); + + material.onBeforeRender( _this, scene, camera, geometry, object, group ); + + if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) { + + material.side = BackSide; + material.needsUpdate = true; + _this.renderBufferDirect( camera, scene, geometry, material, object, group ); + + material.side = FrontSide; + material.needsUpdate = true; + _this.renderBufferDirect( camera, scene, geometry, material, object, group ); + + material.side = DoubleSide; + + } else { + + _this.renderBufferDirect( camera, scene, geometry, material, object, group ); + + } + + object.onAfterRender( _this, scene, camera, geometry, material, group ); + + } + + function getProgram( material, scene, object ) { + + if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ... + + const materialProperties = properties.get( material ); + + const lights = currentRenderState.state.lights; + const shadowsArray = currentRenderState.state.shadowsArray; + + const lightsStateVersion = lights.state.version; + + const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object, currentRenderState.state.lightProbeGridArray ); + const programCacheKey = programCache.getProgramCacheKey( parameters ); + + let programs = materialProperties.programs; + + // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change + + materialProperties.environment = ( material.isMeshStandardMaterial || material.isMeshLambertMaterial || material.isMeshPhongMaterial ) ? scene.environment : null; + materialProperties.fog = scene.fog; + + const usePMREM = material.isMeshStandardMaterial || ( material.isMeshLambertMaterial && ! material.envMap ) || ( material.isMeshPhongMaterial && ! material.envMap ); + materialProperties.envMap = environments.get( material.envMap || materialProperties.environment, usePMREM ); + materialProperties.envMapRotation = ( materialProperties.environment !== null && material.envMap === null ) ? scene.environmentRotation : material.envMapRotation; + + if ( programs === undefined ) { + + // new material + + material.addEventListener( 'dispose', onMaterialDispose ); + + programs = new Map(); + materialProperties.programs = programs; + + } + + let program = programs.get( programCacheKey ); + + if ( program !== undefined ) { + + // early out if program and light state is identical + + if ( materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion ) { + + updateCommonMaterialProperties( material, parameters ); + + return program; + + } + + } else { + + parameters.uniforms = programCache.getUniforms( material ); + + // Use node builder for node materials if available + if ( _nodesHandler !== null && material.isNodeMaterial ) { + + _nodesHandler.build( material, object, parameters ); + + } + + material.onBeforeCompile( parameters, _this ); + + program = programCache.acquireProgram( parameters, programCacheKey ); + programs.set( programCacheKey, program ); + + materialProperties.uniforms = parameters.uniforms; + + } + + const uniforms = materialProperties.uniforms; + + if ( ( ! material.isShaderMaterial && ! material.isRawShaderMaterial ) || material.clipping === true ) { + + uniforms.clippingPlanes = clipping.uniform; + + } + + updateCommonMaterialProperties( material, parameters ); + + // store the light setup it was created for + + materialProperties.needsLights = materialNeedsLights( material ); + materialProperties.lightsStateVersion = lightsStateVersion; + + if ( materialProperties.needsLights ) { + + // wire up the material to this renderer's lighting state + + uniforms.ambientLightColor.value = lights.state.ambient; + uniforms.lightProbe.value = lights.state.probe; + uniforms.sunLights.value = lights.state.sun; + uniforms.sunLightShadows.value = lights.state.sunShadow; + uniforms.directionalLights.value = lights.state.directional; + uniforms.directionalLightShadows.value = lights.state.directionalShadow; + uniforms.spotLights.value = lights.state.spot; + uniforms.spotLightShadows.value = lights.state.spotShadow; + uniforms.rectAreaLights.value = lights.state.rectArea; + uniforms.ltc_1.value = lights.state.rectAreaLTC1; + uniforms.ltc_2.value = lights.state.rectAreaLTC2; + uniforms.pointLights.value = lights.state.point; + uniforms.pointLightShadows.value = lights.state.pointShadow; + uniforms.hemisphereLights.value = lights.state.hemi; + + uniforms.sunShadowMatrix.value = lights.state.sunShadowMatrix; + uniforms.sunShadowCascade.value = lights.state.sunShadowCascade; + uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix; + uniforms.spotLightMatrix.value = lights.state.spotLightMatrix; + uniforms.spotLightMap.value = lights.state.spotLightMap; + uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix; + // TODO (abelnation): add area lights shadow info to uniforms + + } + + materialProperties.lightProbeGrid = currentRenderState.state.lightProbeGridArray.length > 0; + + materialProperties.currentProgram = program; + materialProperties.uniformsList = null; + + return program; + + } + + function getUniformList( materialProperties ) { + + if ( materialProperties.uniformsList === null ) { + + const progUniforms = materialProperties.currentProgram.getUniforms(); + materialProperties.uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, materialProperties.uniforms ); + + } + + return materialProperties.uniformsList; + + } + + function updateCommonMaterialProperties( material, parameters ) { + + const materialProperties = properties.get( material ); + + materialProperties.outputColorSpace = parameters.outputColorSpace; + materialProperties.batching = parameters.batching; + materialProperties.batchingColor = parameters.batchingColor; + materialProperties.instancing = parameters.instancing; + materialProperties.instancingColor = parameters.instancingColor; + materialProperties.instancingMorph = parameters.instancingMorph; + materialProperties.skinning = parameters.skinning; + materialProperties.morphTargets = parameters.morphTargets; + materialProperties.morphNormals = parameters.morphNormals; + materialProperties.morphColors = parameters.morphColors; + materialProperties.morphTargetsCount = parameters.morphTargetsCount; + materialProperties.numClippingPlanes = parameters.numClippingPlanes; + materialProperties.numIntersection = parameters.numClipIntersection; + materialProperties.vertexAlphas = parameters.vertexAlphas; + materialProperties.vertexTangents = parameters.vertexTangents; + materialProperties.toneMapping = parameters.toneMapping; + + } + + function findLightProbeGrid( volumes, object ) { + + if ( volumes.length === 0 ) return null; + + if ( volumes.length === 1 ) { + + return volumes[ 0 ].texture !== null ? volumes[ 0 ] : null; + + } + + objectPosition.setFromMatrixPosition( object.matrixWorld ); + + for ( let i = 0, l = volumes.length; i < l; i ++ ) { + + const v = volumes[ i ]; + + if ( v.texture !== null && v.boundingBox.containsPoint( objectPosition ) ) return v; + + } + + return null; + + } + + function setProgram( camera, scene, geometry, material, object ) { + + if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ... + + textures.resetTextureUnits(); + + const fog = scene.fog; + const environment = ( material.isMeshStandardMaterial || material.isMeshLambertMaterial || material.isMeshPhongMaterial ) ? scene.environment : null; + const colorSpace = ( _currentRenderTarget === null ) ? _this.outputColorSpace : ( _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.colorSpace : ColorManagement.workingColorSpace ); + const usePMREM = material.isMeshStandardMaterial || ( material.isMeshLambertMaterial && ! material.envMap ) || ( material.isMeshPhongMaterial && ! material.envMap ); + const envMap = environments.get( material.envMap || environment, usePMREM ); + const vertexAlphas = material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4; + const vertexTangents = !! geometry.attributes.tangent && ( !! material.normalMap || material.anisotropy > 0 ); + const morphTargets = !! geometry.morphAttributes.position; + const morphNormals = !! geometry.morphAttributes.normal; + const morphColors = !! geometry.morphAttributes.color; + + let toneMapping = NoToneMapping; + + if ( material.toneMapped ) { + + if ( _currentRenderTarget === null || _currentRenderTarget.isXRRenderTarget === true ) { + + toneMapping = _this.toneMapping; + + } + + } + + const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color; + const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0; + + const materialProperties = properties.get( material ); + const lights = currentRenderState.state.lights; + + if ( _clippingEnabled === true ) { + + if ( _localClippingEnabled === true || camera !== _currentCamera ) { + + const useCache = + camera === _currentCamera && + material.id === _currentMaterialId; + + // we might want to call this function with some ClippingGroup + // object instead of the material, once it becomes feasible + // (#8465, #8379) + clipping.setState( material, camera, useCache ); + + } + + } + + // + + let needsProgramChange = false; + + if ( material.version === materialProperties.__version ) { + + if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) { + + needsProgramChange = true; + + } else if ( materialProperties.outputColorSpace !== colorSpace ) { + + needsProgramChange = true; + + } else if ( object.isBatchedMesh && materialProperties.batching === false ) { + + needsProgramChange = true; + + } else if ( ! object.isBatchedMesh && materialProperties.batching === true ) { + + needsProgramChange = true; + + } else if ( object.isBatchedMesh && materialProperties.batchingColor === true && object._colorsTexture === null ) { + + needsProgramChange = true; + + } else if ( object.isBatchedMesh && materialProperties.batchingColor === false && object._colorsTexture !== null ) { + + needsProgramChange = true; + + } else if ( object.isInstancedMesh && materialProperties.instancing === false ) { + + needsProgramChange = true; + + } else if ( ! object.isInstancedMesh && materialProperties.instancing === true ) { + + needsProgramChange = true; + + } else if ( object.isSkinnedMesh && materialProperties.skinning === false ) { + + needsProgramChange = true; + + } else if ( ! object.isSkinnedMesh && materialProperties.skinning === true ) { + + needsProgramChange = true; + + } else if ( object.isInstancedMesh && materialProperties.instancingColor === true && object.instanceColor === null ) { + + needsProgramChange = true; + + } else if ( object.isInstancedMesh && materialProperties.instancingColor === false && object.instanceColor !== null ) { + + needsProgramChange = true; + + } else if ( object.isInstancedMesh && materialProperties.instancingMorph === true && object.morphTexture === null ) { + + needsProgramChange = true; + + } else if ( object.isInstancedMesh && materialProperties.instancingMorph === false && object.morphTexture !== null ) { + + needsProgramChange = true; + + } else if ( materialProperties.envMap !== envMap ) { + + needsProgramChange = true; + + } else if ( material.fog === true && materialProperties.fog !== fog ) { + + needsProgramChange = true; + + } else if ( materialProperties.numClippingPlanes !== undefined && + ( materialProperties.numClippingPlanes !== clipping.numPlanes || + materialProperties.numIntersection !== clipping.numIntersection ) ) { + + needsProgramChange = true; + + } else if ( materialProperties.vertexAlphas !== vertexAlphas ) { + + needsProgramChange = true; + + } else if ( materialProperties.vertexTangents !== vertexTangents ) { + + needsProgramChange = true; + + } else if ( materialProperties.morphTargets !== morphTargets ) { + + needsProgramChange = true; + + } else if ( materialProperties.morphNormals !== morphNormals ) { + + needsProgramChange = true; + + } else if ( materialProperties.morphColors !== morphColors ) { + + needsProgramChange = true; + + } else if ( materialProperties.toneMapping !== toneMapping ) { + + needsProgramChange = true; + + } else if ( materialProperties.morphTargetsCount !== morphTargetsCount ) { + + needsProgramChange = true; + + } else if ( !! materialProperties.lightProbeGrid !== ( currentRenderState.state.lightProbeGridArray.length > 0 ) ) { + + needsProgramChange = true; + + } + + } else { + + needsProgramChange = true; + materialProperties.__version = material.version; + + } + + // + + let program = materialProperties.currentProgram; + + if ( needsProgramChange === true ) { + + program = getProgram( material, scene, object ); + + // notify the node builder that the program has changed so uniforms and update nodes can + // be cached and triggered. + if ( _nodesHandler && material.isNodeMaterial ) { + + _nodesHandler.onUpdateProgram( material, program, materialProperties ); + + } + + } + + let refreshProgram = false; + let refreshMaterial = false; + let refreshLights = false; + + const p_uniforms = program.getUniforms(), + m_uniforms = materialProperties.uniforms; + + if ( state.useProgram( program.program ) ) { + + refreshProgram = true; + refreshMaterial = true; + refreshLights = true; + + } + + if ( material.id !== _currentMaterialId ) { + + _currentMaterialId = material.id; + + refreshMaterial = true; + + } + + if ( materialProperties.needsLights ) { + + const objectVolume = findLightProbeGrid( currentRenderState.state.lightProbeGridArray, object ); + + if ( materialProperties.lightProbeGrid !== objectVolume ) { + + materialProperties.lightProbeGrid = objectVolume; + refreshMaterial = true; + + } + + } + + if ( refreshProgram || _currentCamera !== camera ) { + + // common camera uniforms + + const reversedDepthBuffer = state.buffers.depth.getReversed(); + + if ( reversedDepthBuffer && camera.reversedDepth !== true ) { + + camera._reversedDepth = true; + camera.updateProjectionMatrix(); + + } + + p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix ); + + p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse ); + + const uCamPos = p_uniforms.map.cameraPosition; + + if ( uCamPos !== undefined ) { + + uCamPos.setValue( _gl, _vector3.setFromMatrixPosition( camera.matrixWorld ) ); + + } + + if ( capabilities.logarithmicDepthBuffer ) { + + p_uniforms.setValue( _gl, 'logDepthBufFC', + 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) ); + + } + + // consider moving isOrthographic to UniformLib and WebGLMaterials, see https://github.com/mrdoob/three.js/pull/26467#issuecomment-1645185067 + + if ( material.isMeshPhongMaterial || + material.isMeshToonMaterial || + material.isMeshLambertMaterial || + material.isMeshBasicMaterial || + material.isMeshStandardMaterial || + material.isShaderMaterial ) { + + p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true ); + + } + + if ( _currentCamera !== camera ) { + + _currentCamera = camera; + + // lighting uniforms depend on the camera so enforce an update + // now, in case this material supports lights - or later, when + // the next material that does gets activated: + + refreshMaterial = true; // set to true on material change + refreshLights = true; // remains set until update done + + } + + } + + // Pre-allocate texture units for shadow samplers before setting data textures + if ( materialProperties.needsLights ) { + + // Set shadow map uniforms first to ensure they get the first texture units + if ( lights.state.sunShadowMap.length > 0 ) { + + p_uniforms.setValue( _gl, 'sunShadowMap', lights.state.sunShadowMap, textures ); + + } + + if ( lights.state.directionalShadowMap.length > 0 ) { + + p_uniforms.setValue( _gl, 'directionalShadowMap', lights.state.directionalShadowMap, textures ); + + } + + if ( lights.state.spotShadowMap.length > 0 ) { + + p_uniforms.setValue( _gl, 'spotShadowMap', lights.state.spotShadowMap, textures ); + + } + + if ( lights.state.pointShadowMap.length > 0 ) { + + p_uniforms.setValue( _gl, 'pointShadowMap', lights.state.pointShadowMap, textures ); + + } + + } + + // skinning and morph target uniforms must be set even if material didn't change + // auto-setting of texture unit for bone and morph texture must go before other textures + // otherwise textures used for skinning and morphing can take over texture units reserved for other material textures + + if ( object.isSkinnedMesh ) { + + p_uniforms.setOptional( _gl, object, 'bindMatrix' ); + p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' ); + + const skeleton = object.skeleton; + + if ( skeleton ) { + + if ( skeleton.boneTexture === null ) skeleton.computeBoneTexture(); + + p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures ); + + } + + } + + if ( object.isBatchedMesh ) { + + p_uniforms.setOptional( _gl, object, 'batchingTexture' ); + p_uniforms.setValue( _gl, 'batchingTexture', object._matricesTexture, textures ); + + p_uniforms.setOptional( _gl, object, 'batchingIdTexture' ); + p_uniforms.setValue( _gl, 'batchingIdTexture', object._indirectTexture, textures ); + + p_uniforms.setOptional( _gl, object, 'batchingColorTexture' ); + if ( object._colorsTexture !== null ) { + + p_uniforms.setValue( _gl, 'batchingColorTexture', object._colorsTexture, textures ); + + } + + } + + const morphAttributes = geometry.morphAttributes; + + if ( morphAttributes.position !== undefined || morphAttributes.normal !== undefined || ( morphAttributes.color !== undefined ) ) { + + morphtargets.update( object, geometry, program ); + + } + + if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) { + + materialProperties.receiveShadow = object.receiveShadow; + p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow ); + + } + + if ( ( material.isMeshStandardMaterial || material.isMeshLambertMaterial || material.isMeshPhongMaterial ) && material.envMap === null && scene.environment !== null ) { + + m_uniforms.envMapIntensity.value = scene.environmentIntensity; + + } + + // Set DFG LUT for physically-based materials + if ( m_uniforms.dfgLUT !== undefined ) { + + m_uniforms.dfgLUT.value = getDFGLUT(); + + } + + if ( refreshMaterial ) { + + p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure ); + + if ( materialProperties.needsLights ) { + + // the current material requires lighting info + + // note: all lighting uniforms are always set correctly + // they simply reference the renderer's state for their + // values + // + // use the current material's .needsUpdate flags to set + // the GL state when required + + markUniformsLightsNeedsUpdate( m_uniforms, refreshLights ); + + } + + // refresh uniforms common to several materials + + if ( fog && material.fog === true ) { + + materials.refreshFogUniforms( m_uniforms, fog ); + + } + + materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height, currentRenderState.state.transmissionRenderTarget[ camera.id ] ); + + // light probe volume + + if ( materialProperties.needsLights && materialProperties.lightProbeGrid ) { + + const volume = materialProperties.lightProbeGrid; + + m_uniforms.probesSH.value = volume.texture; + m_uniforms.probesMin.value.copy( volume.boundingBox.min ); + m_uniforms.probesMax.value.copy( volume.boundingBox.max ); + m_uniforms.probesResolution.value.copy( volume.resolution ); + + } + + WebGLUniforms.upload( _gl, getUniformList( materialProperties ), m_uniforms, textures ); + + } + + if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) { + + WebGLUniforms.upload( _gl, getUniformList( materialProperties ), m_uniforms, textures ); + material.uniformsNeedUpdate = false; + + } + + if ( material.isSpriteMaterial ) { + + p_uniforms.setValue( _gl, 'center', object.center ); + + } + + // common matrices + + p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix ); + p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix ); + p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld ); + + // UBOs + + if ( material.uniformsGroups !== undefined ) { + + const groups = material.uniformsGroups; + + for ( let i = 0, l = groups.length; i < l; i ++ ) { + + const group = groups[ i ]; + + uniformsGroups.update( group, program ); + uniformsGroups.bind( group, program ); + + } + + } + + return program; + + } + + // If uniforms are marked as clean, they don't need to be loaded to the GPU. + + function markUniformsLightsNeedsUpdate( uniforms, value ) { + + uniforms.ambientLightColor.needsUpdate = value; + uniforms.lightProbe.needsUpdate = value; + + uniforms.sunLights.needsUpdate = value; + uniforms.sunLightShadows.needsUpdate = value; + uniforms.directionalLights.needsUpdate = value; + uniforms.directionalLightShadows.needsUpdate = value; + uniforms.pointLights.needsUpdate = value; + uniforms.pointLightShadows.needsUpdate = value; + uniforms.spotLights.needsUpdate = value; + uniforms.spotLightShadows.needsUpdate = value; + uniforms.rectAreaLights.needsUpdate = value; + uniforms.hemisphereLights.needsUpdate = value; + + } + + function materialNeedsLights( material ) { + + return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial || + material.isMeshStandardMaterial || material.isShadowMaterial || + ( material.isShaderMaterial && material.lights === true ); + + } + + /** + * Returns the active cube face. + * + * @return {number} The active cube face. + */ + this.getActiveCubeFace = function () { + + return _currentActiveCubeFace; + + }; + + /** + * Returns the active mipmap level. + * + * @return {number} The active mipmap level. + */ + this.getActiveMipmapLevel = function () { + + return _currentActiveMipmapLevel; + + }; + + /** + * Returns the active render target. + * + * @return {?WebGLRenderTarget} The active render target. Returns `null` if no render target + * is currently set. + */ + this.getRenderTarget = function () { + + return _currentRenderTarget; + + }; + + this.setRenderTargetTextures = function ( renderTarget, colorTexture, depthTexture ) { + + const renderTargetProperties = properties.get( renderTarget ); + + renderTargetProperties.__autoAllocateDepthBuffer = renderTarget.resolveDepthBuffer === false; + if ( renderTargetProperties.__autoAllocateDepthBuffer === false ) { + + // The multisample_render_to_texture extension doesn't work properly if there + // are midframe flushes and an external depth buffer. Disable use of the extension. + renderTargetProperties.__useRenderToTexture = false; + + } + + properties.get( renderTarget.texture ).__webglTexture = colorTexture; + properties.get( renderTarget.depthTexture ).__webglTexture = renderTargetProperties.__autoAllocateDepthBuffer ? undefined : depthTexture; + + renderTargetProperties.__hasExternalTextures = true; + + }; + + this.setRenderTargetFramebuffer = function ( renderTarget, defaultFramebuffer ) { + + const renderTargetProperties = properties.get( renderTarget ); + renderTargetProperties.__webglFramebuffer = defaultFramebuffer; + renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined; + + }; + + /** + * Sets the active rendertarget. + * + * @param {?WebGLRenderTarget} renderTarget - The render target to set. When `null` is given, + * the canvas is set as the active render target instead. + * @param {number} [activeCubeFace=0] - The active cube face when using a cube render target. + * Indicates the z layer to render in to when using 3D or array render targets. + * @param {number} [activeMipmapLevel=0] - The active mipmap level. + */ + this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) { + + _currentRenderTarget = renderTarget; + _currentActiveCubeFace = activeCubeFace; + _currentActiveMipmapLevel = activeMipmapLevel; + + let framebuffer = null; + let isCube = false; + let isRenderTarget3D = false; + + if ( renderTarget ) { + + const renderTargetProperties = properties.get( renderTarget ); + + if ( renderTargetProperties.__useDefaultFramebuffer !== undefined ) { + + // Externally-managed framebuffer (e.g. XR) + // Bind to the stored framebuffer (may be null for default, or a WebGLFramebuffer) + state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer ); + + _currentViewport.copy( renderTarget.viewport ); + _currentScissor.copy( renderTarget.scissor ); + _currentScissorTest = renderTarget.scissorTest; + + state.viewport( _currentViewport ); + state.scissor( _currentScissor ); + state.setScissorTest( _currentScissorTest ); + + _currentMaterialId = -1; + + return; + + } else if ( renderTargetProperties.__webglFramebuffer === undefined ) { + + textures.setupRenderTarget( renderTarget ); + + } else if ( renderTargetProperties.__hasExternalTextures ) { + + // Color and depth texture must be rebound in order for the swapchain to update. + textures.rebindTextures( renderTarget, properties.get( renderTarget.texture ).__webglTexture, properties.get( renderTarget.depthTexture ).__webglTexture ); + + } else if ( renderTarget.depthBuffer ) { + + // check if the depth texture is already bound to the frame buffer and that it's been initialized + const depthTexture = renderTarget.depthTexture; + if ( renderTargetProperties.__boundDepthTexture !== depthTexture ) { + + // check if the depth texture is compatible + if ( + depthTexture !== null && + properties.has( depthTexture ) && + ( renderTarget.width !== depthTexture.image.width || renderTarget.height !== depthTexture.image.height ) + ) { + + throw new Error( 'THREE.WebGLRenderer: Attached DepthTexture is initialized to the incorrect size.' ); + + } + + // Swap the depth buffer to the currently attached one + textures.setupDepthRenderbuffer( renderTarget ); + + } + + } + + const texture = renderTarget.texture; + + if ( texture.isData3DTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) { + + isRenderTarget3D = true; + + } + + const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer; + + if ( renderTarget.isWebGLCubeRenderTarget ) { + + if ( Array.isArray( __webglFramebuffer[ activeCubeFace ] ) ) { + + framebuffer = __webglFramebuffer[ activeCubeFace ][ activeMipmapLevel ]; + + } else { + + framebuffer = __webglFramebuffer[ activeCubeFace ]; + + } + + isCube = true; + + } else if ( ( renderTarget.samples > 0 ) && textures.useMultisampledRTT( renderTarget ) === false ) { + + framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer; + + } else { + + if ( Array.isArray( __webglFramebuffer ) ) { + + framebuffer = __webglFramebuffer[ activeMipmapLevel ]; + + } else { + + framebuffer = __webglFramebuffer; + + } + + } + + _currentViewport.copy( renderTarget.viewport ); + _currentScissor.copy( renderTarget.scissor ); + _currentScissorTest = renderTarget.scissorTest; + + } else { + + _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor(); + _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor(); + _currentScissorTest = _scissorTest; + + } + + // Use a scratch frame buffer if rendering to a mip level to avoid depth buffers + // being bound that are different sizes. + if ( activeMipmapLevel !== 0 ) { + + framebuffer = _scratchFramebuffer; + + } + + const framebufferBound = state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); + + if ( framebufferBound ) { + + state.drawBuffers( renderTarget, framebuffer ); + + } + + state.viewport( _currentViewport ); + state.scissor( _currentScissor ); + state.setScissorTest( _currentScissorTest ); + + if ( isCube ) { + + const textureProperties = properties.get( renderTarget.texture ); + _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel ); + + } else if ( isRenderTarget3D ) { + + const layer = activeCubeFace; + + for ( let i = 0; i < renderTarget.textures.length; i ++ ) { + + const textureProperties = properties.get( renderTarget.textures[ i ] ); + + _gl.framebufferTextureLayer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, textureProperties.__webglTexture, activeMipmapLevel, layer ); + + } + + } else if ( renderTarget !== null && activeMipmapLevel !== 0 ) { + + // Only bind the frame buffer if we are using a scratch frame buffer to render to a mipmap. + // If we rebind the texture when using a multi sample buffer then an error about inconsistent samples will be thrown. + const textureProperties = properties.get( renderTarget.texture ); + _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, textureProperties.__webglTexture, activeMipmapLevel ); + + } + + _currentMaterialId = -1; // reset current material to ensure correct uniform bindings + + }; + + function getReadableState( texture ) { + + const textureProperties = properties.get( texture ); + + if ( textureProperties.__readFormat !== texture.format || textureProperties.__readType !== texture.type ) { + + textureProperties.__readFormat = texture.format; + textureProperties.__readType = texture.type; + textureProperties.__formatReadable = capabilities.textureFormatReadable( texture.format ); + textureProperties.__typeReadable = capabilities.textureTypeReadable( texture.type ); + + } + + return textureProperties; + + } + + /** + * Reads the pixel data from the given render target into the given buffer. + * + * @param {WebGLRenderTarget} renderTarget - The render target to read from. + * @param {number} x - The `x` coordinate of the copy region's origin. + * @param {number} y - The `y` coordinate of the copy region's origin. + * @param {number} width - The width of the copy region. + * @param {number} height - The height of the copy region. + * @param {TypedArray} buffer - The result buffer. + * @param {number} [activeCubeFaceIndex] - The active cube face index. + * @param {number} [textureIndex=0] - The texture index of an MRT render target. + */ + this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex, textureIndex = 0 ) { + + if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) { + + error( 'WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' ); + return; + + } + + let framebuffer = properties.get( renderTarget ).__webglFramebuffer; + + if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) { + + framebuffer = framebuffer[ activeCubeFaceIndex ]; + + } + + if ( framebuffer ) { + + state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); + + try { + + const texture = renderTarget.textures[ textureIndex ]; + const textureFormat = texture.format; + const textureType = texture.type; + + // when using MRT, select the correct color buffer for the subsequent read command + + if ( renderTarget.textures.length > 1 ) _gl.readBuffer( _gl.COLOR_ATTACHMENT0 + textureIndex ); + + const readableState = getReadableState( texture ); + + if ( readableState.__formatReadable === false ) { + + error( 'WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' ); + return; + + } + + if ( readableState.__typeReadable === false ) { + + error( 'WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' ); + return; + + } + + // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604) + + if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) { + + _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer ); + + } + + } finally { + + // restore framebuffer of current render target if necessary + + const framebuffer = ( _currentRenderTarget !== null ) ? properties.get( _currentRenderTarget ).__webglFramebuffer : null; + state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); + + } + + } + + }; + + /** + * Asynchronous, non-blocking version of {@link WebGLRenderer#readRenderTargetPixels}. + * + * It is recommended to use this version of `readRenderTargetPixels()` whenever possible. + * + * @async + * @param {WebGLRenderTarget} renderTarget - The render target to read from. + * @param {number} x - The `x` coordinate of the copy region's origin. + * @param {number} y - The `y` coordinate of the copy region's origin. + * @param {number} width - The width of the copy region. + * @param {number} height - The height of the copy region. + * @param {TypedArray} buffer - The result buffer. + * @param {number} [activeCubeFaceIndex] - The active cube face index. + * @param {number} [textureIndex=0] - The texture index of an MRT render target. + * @return {Promise} A Promise that resolves when the read has been finished. The resolve provides the read data as a typed array. + */ + this.readRenderTargetPixelsAsync = async function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex, textureIndex = 0 ) { + + if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) { + + throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' ); + + } + + let framebuffer = properties.get( renderTarget ).__webglFramebuffer; + if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) { + + framebuffer = framebuffer[ activeCubeFaceIndex ]; + + } + + if ( framebuffer ) { + + // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604) + if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) { + + // set the active frame buffer to the one we want to read + state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); + + const texture = renderTarget.textures[ textureIndex ]; + const textureFormat = texture.format; + const textureType = texture.type; + + // when using MRT, select the correct color buffer for the subsequent read command + + if ( renderTarget.textures.length > 1 ) _gl.readBuffer( _gl.COLOR_ATTACHMENT0 + textureIndex ); + + const readableState = getReadableState( texture ); + + if ( readableState.__formatReadable === false ) { + + throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.' ); + + } + + if ( readableState.__typeReadable === false ) { + + throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.' ); + + } + + const glBuffer = _gl.createBuffer(); + _gl.bindBuffer( _gl.PIXEL_PACK_BUFFER, glBuffer ); + _gl.bufferData( _gl.PIXEL_PACK_BUFFER, buffer.byteLength, _gl.STREAM_READ ); + + _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), 0 ); + _gl.bindBuffer( _gl.PIXEL_PACK_BUFFER, null ); + + // reset the frame buffer to the currently set buffer before waiting + const currFramebuffer = _currentRenderTarget !== null ? properties.get( _currentRenderTarget ).__webglFramebuffer : null; + state.bindFramebuffer( _gl.FRAMEBUFFER, currFramebuffer ); + + // check if the commands have finished every 8 ms + const sync = _gl.fenceSync( _gl.SYNC_GPU_COMMANDS_COMPLETE, 0 ); + + _gl.flush(); + + await probeAsync( _gl, sync, 4 ); + + // read the data and delete the buffer + _gl.bindBuffer( _gl.PIXEL_PACK_BUFFER, glBuffer ); + _gl.getBufferSubData( _gl.PIXEL_PACK_BUFFER, 0, buffer ); + _gl.bindBuffer( _gl.PIXEL_PACK_BUFFER, null ); + _gl.deleteBuffer( glBuffer ); + _gl.deleteSync( sync ); + + return buffer; + + } else { + + throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.' ); + + } + + } + + }; + + /** + * Copies pixels from the current bound framebuffer into the given texture. + * + * @param {FramebufferTexture} texture - The texture. + * @param {?Vector2} [position=null] - The start position of the copy operation. + * @param {number} [level=0] - The mip level. The default represents the base mip. + */ + this.copyFramebufferToTexture = function ( texture, position = null, level = 0 ) { + + const levelScale = Math.pow( 2, - level ); + const width = Math.floor( texture.image.width * levelScale ); + const height = Math.floor( texture.image.height * levelScale ); + + const x = position !== null ? position.x : 0; + const y = position !== null ? position.y : 0; + + textures.setTexture2D( texture, 0 ); + + _gl.copyTexSubImage2D( _gl.TEXTURE_2D, level, 0, 0, x, y, width, height ); + + state.unbindTexture(); + + }; + + + /** + * Copies data of the given source texture into a destination texture. + * + * When using render target textures as `srcTexture` and `dstTexture`, you must make sure both render targets are initialized + * {@link WebGLRenderer#initRenderTarget}. + * + * @param {Texture} srcTexture - The source texture. + * @param {Texture} dstTexture - The destination texture. + * @param {?(Box2|Box3)} [srcRegion=null] - A bounding box which describes the source region. Can be two or three-dimensional. + * @param {?(Vector2|Vector3)} [dstPosition=null] - A vector that represents the origin of the destination region. Can be two or three-dimensional. + * @param {number} [srcLevel=0] - The source mipmap level to copy. + * @param {?number} [dstLevel=0] - The destination mipmap level. + */ + this.copyTextureToTexture = function ( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) { + + // gather the necessary dimensions to copy + let width, height, depth, minX, minY, minZ; + let dstX, dstY, dstZ; + const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ dstLevel ] : srcTexture.image; + if ( srcRegion !== null ) { + + width = srcRegion.max.x - srcRegion.min.x; + height = srcRegion.max.y - srcRegion.min.y; + depth = srcRegion.isBox3 ? srcRegion.max.z - srcRegion.min.z : 1; + minX = srcRegion.min.x; + minY = srcRegion.min.y; + minZ = srcRegion.isBox3 ? srcRegion.min.z : 0; + + } else { + + const levelScale = Math.pow( 2, - srcLevel ); + width = Math.floor( image.width * levelScale ); + height = Math.floor( image.height * levelScale ); + if ( srcTexture.isDataArrayTexture ) { + + depth = image.depth; + + } else if ( srcTexture.isData3DTexture ) { + + depth = Math.floor( image.depth * levelScale ); + + } else { + + depth = 1; + + } + + minX = 0; + minY = 0; + minZ = 0; + + } + + if ( dstPosition !== null ) { + + dstX = dstPosition.x; + dstY = dstPosition.y; + dstZ = dstPosition.z; + + } else { + + dstX = 0; + dstY = 0; + dstZ = 0; + + } + + // Set up the destination target + const glFormat = utils.convert( dstTexture.format ); + const glType = utils.convert( dstTexture.type ); + let glTarget; + + if ( dstTexture.isData3DTexture ) { + + textures.setTexture3D( dstTexture, 0 ); + glTarget = _gl.TEXTURE_3D; + + } else if ( dstTexture.isDataArrayTexture || dstTexture.isCompressedArrayTexture ) { + + textures.setTexture2DArray( dstTexture, 0 ); + glTarget = _gl.TEXTURE_2D_ARRAY; + + } else { + + textures.setTexture2D( dstTexture, 0 ); + glTarget = _gl.TEXTURE_2D; + + } + + state.activeTexture( _gl.TEXTURE0 ); // see #33153 + + state.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY ); + state.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha ); + state.pixelStorei( _gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment ); + + // used for copying data from cpu + const currentUnpackRowLen = state.getParameter( _gl.UNPACK_ROW_LENGTH ); + const currentUnpackImageHeight = state.getParameter( _gl.UNPACK_IMAGE_HEIGHT ); + const currentUnpackSkipPixels = state.getParameter( _gl.UNPACK_SKIP_PIXELS ); + const currentUnpackSkipRows = state.getParameter( _gl.UNPACK_SKIP_ROWS ); + const currentUnpackSkipImages = state.getParameter( _gl.UNPACK_SKIP_IMAGES ); + + state.pixelStorei( _gl.UNPACK_ROW_LENGTH, image.width ); + state.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, image.height ); + state.pixelStorei( _gl.UNPACK_SKIP_PIXELS, minX ); + state.pixelStorei( _gl.UNPACK_SKIP_ROWS, minY ); + state.pixelStorei( _gl.UNPACK_SKIP_IMAGES, minZ ); + + // set up the src texture + const isSrc3D = srcTexture.isDataArrayTexture || srcTexture.isData3DTexture; + const isDst3D = dstTexture.isDataArrayTexture || dstTexture.isData3DTexture; + if ( srcTexture.isDepthTexture ) { + + const srcTextureProperties = properties.get( srcTexture ); + const dstTextureProperties = properties.get( dstTexture ); + const srcRenderTargetProperties = properties.get( srcTextureProperties.__renderTarget ); + const dstRenderTargetProperties = properties.get( dstTextureProperties.__renderTarget ); + state.bindFramebuffer( _gl.READ_FRAMEBUFFER, srcRenderTargetProperties.__webglFramebuffer ); + state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, dstRenderTargetProperties.__webglFramebuffer ); + + for ( let i = 0; i < depth; i ++ ) { + + // if the source or destination are a 3d target then a layer needs to be bound + if ( isSrc3D ) { + + _gl.framebufferTextureLayer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, properties.get( srcTexture ).__webglTexture, srcLevel, minZ + i ); + _gl.framebufferTextureLayer( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, properties.get( dstTexture ).__webglTexture, dstLevel, dstZ + i ); + + } + + _gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, _gl.DEPTH_BUFFER_BIT, _gl.NEAREST ); + + } + + state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null ); + state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null ); + + } else if ( srcLevel !== 0 || srcTexture.isRenderTargetTexture || properties.has( srcTexture ) ) { + + // get the appropriate frame buffers + const srcTextureProperties = properties.get( srcTexture ); + const dstTextureProperties = properties.get( dstTexture ); + + // bind the frame buffer targets + state.bindFramebuffer( _gl.READ_FRAMEBUFFER, _srcFramebuffer ); + state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, _dstFramebuffer ); + + for ( let i = 0; i < depth; i ++ ) { + + // assign the correct layers and mip maps to the frame buffers + if ( isSrc3D ) { + + _gl.framebufferTextureLayer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, srcTextureProperties.__webglTexture, srcLevel, minZ + i ); + + } else { + + _gl.framebufferTexture2D( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, srcTextureProperties.__webglTexture, srcLevel ); + + } + + if ( isDst3D ) { + + _gl.framebufferTextureLayer( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, dstTextureProperties.__webglTexture, dstLevel, dstZ + i ); + + } else { + + _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, dstTextureProperties.__webglTexture, dstLevel ); + + } + + // copy the data using the fastest function that can achieve the copy + if ( srcLevel !== 0 ) { + + _gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, _gl.COLOR_BUFFER_BIT, _gl.NEAREST ); + + } else if ( isDst3D ) { + + _gl.copyTexSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ + i, minX, minY, width, height ); + + } else { + + _gl.copyTexSubImage2D( glTarget, dstLevel, dstX, dstY, minX, minY, width, height ); + + } + + } + + // unbind read, draw buffers + state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null ); + state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null ); + + } else { + + if ( isDst3D ) { + + // copy data into the 3d texture + if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) { + + _gl.texSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image.data ); + + } else if ( dstTexture.isCompressedArrayTexture ) { + + _gl.compressedTexSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, image.data ); + + } else { + + _gl.texSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image ); + + } + + } else { + + // copy data into the 2d texture + if ( srcTexture.isDataTexture ) { + + _gl.texSubImage2D( _gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image.data ); + + } else if ( srcTexture.isCompressedTexture ) { + + _gl.compressedTexSubImage2D( _gl.TEXTURE_2D, dstLevel, dstX, dstY, image.width, image.height, glFormat, image.data ); + + } else { + + _gl.texSubImage2D( _gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image ); + + } + + } + + } + + // reset values + state.pixelStorei( _gl.UNPACK_ROW_LENGTH, currentUnpackRowLen ); + state.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight ); + state.pixelStorei( _gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels ); + state.pixelStorei( _gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows ); + state.pixelStorei( _gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages ); + + // Generate mipmaps only when copying level 0 + if ( dstLevel === 0 && dstTexture.generateMipmaps ) { + + _gl.generateMipmap( glTarget ); + + } + + state.unbindTexture(); + + }; + + /** + * Initializes the given WebGLRenderTarget memory. Useful for initializing a render target so data + * can be copied into it using {@link WebGLRenderer#copyTextureToTexture} before it has been + * rendered to. + * + * @param {WebGLRenderTarget} target - The render target. + */ + this.initRenderTarget = function ( target ) { + + if ( properties.get( target ).__webglFramebuffer === undefined ) { + + textures.setupRenderTarget( target ); + + } + + }; + + /** + * Initializes the given texture. Useful for preloading a texture rather than waiting until first + * render (which can cause noticeable lags due to decode and GPU upload overhead). + * + * @param {Texture} texture - The texture. + */ + this.initTexture = function ( texture ) { + + if ( texture.isCubeTexture ) { + + textures.setTextureCube( texture, 0 ); + + } else if ( texture.isData3DTexture ) { + + textures.setTexture3D( texture, 0 ); + + } else if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) { + + textures.setTexture2DArray( texture, 0 ); + + } else { + + textures.setTexture2D( texture, 0 ); + + } + + state.unbindTexture(); + + }; + + /** + * Can be used to reset the internal WebGL state. This method is mostly + * relevant for applications which share a single WebGL context across + * multiple WebGL libraries. + */ + this.resetState = function () { + + _currentActiveCubeFace = 0; + _currentActiveMipmapLevel = 0; + _currentRenderTarget = null; + + state.reset(); + bindingStates.reset(); + + }; + + if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) { + + __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) ); + + } + + } + + /** + * Defines the coordinate system of the renderer. + * + * In `WebGLRenderer`, the value is always `WebGLCoordinateSystem`. + * + * @type {WebGLCoordinateSystem|WebGPUCoordinateSystem} + * @default WebGLCoordinateSystem + * @readonly + */ + get coordinateSystem() { + + return WebGLCoordinateSystem; + + } + + /** + * Defines the output color space of the renderer. + * + * @type {SRGBColorSpace|LinearSRGBColorSpace} + * @default SRGBColorSpace + */ + get outputColorSpace() { + + return this._outputColorSpace; + + } + + set outputColorSpace( colorSpace ) { + + this._outputColorSpace = colorSpace; + + const gl = this.getContext(); + gl.drawingBufferColorSpace = ColorManagement._getDrawingBufferColorSpace( colorSpace ); + gl.unpackColorSpace = ColorManagement._getUnpackColorSpace(); + + } + +} + +export { ACESFilmicToneMapping, AddEquation, AddOperation, AdditiveBlending, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, ArrayCamera, BackSide, BoxGeometry, BufferAttribute, BufferGeometry, ByteType, CineonToneMapping, ClampToEdgeWrapping, Color, ColorManagement, ConstantAlphaFactor, ConstantColorFactor, CubeCamera, CubeDepthTexture, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeUVReflectionMapping, CullFaceBack, CullFaceFront, CullFaceNone, CustomBlending, CustomToneMapping, Data3DTexture, DataArrayTexture, DataTexture, DepthFormat, DepthStencilFormat, DepthTexture, DoubleSide, DstAlphaFactor, DstColorFactor, EqualCompare, EqualDepth, EquirectangularReflectionMapping, EquirectangularRefractionMapping, EventDispatcher, ExternalTexture, Float32BufferAttribute, FloatType, FrontSide, Frustum, GLSL3, GreaterCompare, GreaterDepth, GreaterEqualCompare, GreaterEqualDepth, HalfFloatType, IntType, Layers, LessCompare, LessDepth, LessEqualCompare, LessEqualDepth, LinearFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearSRGBColorSpace, LinearToneMapping, LinearTransfer, Matrix3, Matrix4, MaxEquation, Mesh, MeshBasicMaterial, MeshDepthMaterial, MeshDistanceMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeutralToneMapping, NeverCompare, NeverDepth, NoBlending, NoColorSpace, NoToneMapping, NormalBlending, NotEqualCompare, NotEqualDepth, ObjectSpaceNormalMap, OneFactor, OneMinusConstantAlphaFactor, OneMinusConstantColorFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OrthographicCamera, PCFShadowMap, PCFSoftShadowMap, PMREMGenerator, PerspectiveCamera, Plane, PlaneGeometry, R11_EAC_Format, RED_GREEN_RGTC2_Format, RED_RGTC1_Format, REVISION, RG11_EAC_Format, RGBAFormat, RGBAIntegerFormat, RGBA_ASTC_10x10_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_BPTC_Format, RGBA_ETC2_EAC_Format, RGBA_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGBFormat, RGB_BPTC_SIGNED_Format, RGB_BPTC_UNSIGNED_Format, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGFormat, RGIntegerFormat, RawShaderMaterial, RedFormat, RedIntegerFormat, ReinhardToneMapping, RepeatWrapping, ReverseSubtractEquation, SIGNED_R11_EAC_Format, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SIGNED_RG11_EAC_Format, SRGBColorSpace, SRGBTransfer, ShaderChunk, ShaderLib, ShaderMaterial, ShortType, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, SubtractEquation, SubtractiveBlending, TangentSpaceNormalMap, Texture, Uint16BufferAttribute, Uint32BufferAttribute, UniformsLib, UniformsUtils, UnsignedByteType, UnsignedInt101111Type, UnsignedInt248Type, UnsignedInt5999Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, VSMShadowMap, Vector2, Vector3, Vector4, WebGLCoordinateSystem, WebGLCubeRenderTarget, WebGLRenderTarget, WebGLRenderer, WebGLUtils, WebXRController, ZeroFactor, createCanvasElement, error, log, warn, warnOnce }; diff --git a/package-lock.json b/package-lock.json index d0b90183ff9..5a816a2ddb5 100644 --- a/package-lock.json +++ b/package-lock.json @@ -7,8 +7,10 @@ "": { "name": "openblock-gui", "version": "0.1.0", + "hasInstallScript": true, "license": "BSD-3-Clause", "dependencies": { + "@microsoft/clarity": "^1.0.2", "@ramonak/react-progress-bar": "^3.1.0", "ansi-to-react": "^6.0.8", "arraybuffer-loader": "^1.0.6", @@ -19,15 +21,18 @@ "computed-style-to-inline-style": "3.0.0", "copy-webpack-plugin": "^4.5.1", "core-js": "2.5.7", + "crypto-js": "^4.2.0", "css-loader": "^1.0.0", "enzyme": "^3.5.0", "enzyme-adapter-react-16": "1.3.0", "es6-object-assign": "1.1.0", + "esptool-js": "^0.5.7", "file-loader": "2.0.0", "get-float-time-domain-data": "0.1.0", "get-user-media-promise": "1.1.4", "immutable": "3.8.2", "intl": "1.2.5", + "jose": "^6.2.12", "js-base64": "2.4.9", "keymirror": "0.1.1", "lodash.bindall": "4.4.0", @@ -47,6 +52,7 @@ "postcss-loader": "^3.0.0", "postcss-simple-vars": "^5.0.1", "prop-types": "^15.5.10", + "qrcode-generator": "^1.5.2", "query-string": "^5.1.1", "raw-loader": "^0.5.1", "react": "^16.0.0", @@ -68,6 +74,7 @@ "react-virtualized": "9.20.1", "redux": "3.7.2", "redux-throttle": "0.1.1", + "regenerator-runtime": "^0.13.11", "scratch-audio": "0.1.0-prerelease.20200528195344", "scratch-paint": "0.2.0-prerelease.20211027080909", "scratch-render": "0.1.0-prerelease.20211028200436", @@ -77,6 +84,7 @@ "startaudiocontext": "1.2.1", "style-loader": "^0.23.0", "text-encoding": "0.7.0", + "three": "0.186.1", "to-style": "1.3.3", "wav-encoder": "1.3.0", "xhr": "2.5.0" @@ -84,7 +92,15 @@ "devDependencies": { "@babel/cli": "7.14.8", "@babel/core": "7.14.8", + "@babel/plugin-proposal-class-properties": "7.14.5", + "@babel/plugin-proposal-class-static-block": "7.14.5", + "@babel/plugin-proposal-logical-assignment-operators": "7.14.5", + "@babel/plugin-proposal-nullish-coalescing-operator": "7.14.5", + "@babel/plugin-proposal-numeric-separator": "7.14.5", "@babel/plugin-proposal-object-rest-spread": "7.14.7", + "@babel/plugin-proposal-optional-chaining": "7.14.5", + "@babel/plugin-proposal-private-methods": "7.14.5", + "@babel/plugin-proposal-private-property-in-object": "7.14.5", "@babel/plugin-syntax-dynamic-import": "7.2.0", "@babel/plugin-transform-async-to-generator": "7.14.5", "@babel/preset-env": "7.14.8", @@ -93,6 +109,7 @@ "babel-eslint": "10.0.3", "babel-loader": "8.2.2", "chromedriver": "^96.0.0", + "cross-env": "^10.1.0", "enzyme": "3.10.0", "enzyme-adapter-react-16": "1.3.0", "eslint": "5.16.0", @@ -106,11 +123,14 @@ "jest-junit": "7.0.0", "mkdirp": "1.0.3", "monaco-editor-webpack-plugin": "^1.7.0", + "patch-package": "^8.0.1", "raf": "3.4.1", "react-test-renderer": "16.2.0", "redux-mock-store": "1.5.3", "rimraf": "2.7.1", "selenium-webdriver": "3.6.0", + "sharp": "^0.33.5", + "terser-webpack-plugin": "1.4.5", "uglifyjs-webpack-plugin": "1.3.0", "web-audio-test-api": "0.5.2", "webpack": "4.46.0", @@ -1750,6 +1770,7 @@ "integrity": "sha512-q/PLpv5Ko4dVc1LYMpCY7RVAAO4uk55qPwrIuJ5QJ8c6cVuAmhu7I/49JOppXL6gXf7ZHzpRVEUZdYoPLM04Gg==", "deprecated": "This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-class-properties instead.", "dev": true, + "license": "MIT", "dependencies": { "@babel/helper-create-class-features-plugin": "^7.14.5", "@babel/helper-plugin-utils": "^7.14.5" @@ -1776,6 +1797,7 @@ "integrity": "sha512-KBAH5ksEnYHCegqseI5N9skTdxgJdmDoAOc0uXa+4QMYKeZD0w5IARh4FMlTNtaHhbB8v+KzMdTgxMMzsIy6Yg==", "deprecated": "This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-class-static-block instead.", "dev": true, + "license": "MIT", "dependencies": { "@babel/helper-create-class-features-plugin": "^7.14.5", "@babel/helper-plugin-utils": "^7.14.5", @@ -1893,6 +1915,7 @@ "integrity": "sha512-YGn2AvZAo9TwyhlLvCCWxD90Xq8xJ4aSgaX3G5D/8DW94L8aaT+dS5cSP+Z06+rCJERGSr9GxMBZ601xoc2taw==", "deprecated": "This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-logical-assignment-operators instead.", "dev": true, + "license": "MIT", "dependencies": { "@babel/helper-plugin-utils": "^7.14.5", "@babel/plugin-syntax-logical-assignment-operators": "^7.10.4" @@ -1919,6 +1942,7 @@ "integrity": "sha512-gun/SOnMqjSb98Nkaq2rTKMwervfdAoz6NphdY0vTfuzMfryj+tDGb2n6UkDKwez+Y8PZDhE3D143v6Gepp4Hg==", "deprecated": "This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-nullish-coalescing-operator instead.", "dev": true, + "license": "MIT", "dependencies": { "@babel/helper-plugin-utils": "^7.14.5", "@babel/plugin-syntax-nullish-coalescing-operator": "^7.8.3" @@ -1945,6 +1969,7 @@ "integrity": "sha512-yiclALKe0vyZRZE0pS6RXgjUOt87GWv6FYa5zqj15PvhOGFO69R5DusPlgK/1K5dVnCtegTiWu9UaBSrLLJJBg==", "deprecated": "This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-numeric-separator instead.", "dev": true, + "license": "MIT", "dependencies": { "@babel/helper-plugin-utils": "^7.14.5", "@babel/plugin-syntax-numeric-separator": "^7.10.4" @@ -2026,6 +2051,7 @@ "integrity": "sha512-ycz+VOzo2UbWNI1rQXxIuMOzrDdHGrI23fRiz/Si2R4kv2XZQ1BK8ccdHwehMKBlcH/joGW/tzrUmo67gbJHlQ==", "deprecated": "This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-optional-chaining instead.", "dev": true, + "license": "MIT", "dependencies": { "@babel/helper-plugin-utils": "^7.14.5", "@babel/helper-skip-transparent-expression-wrappers": "^7.14.5", @@ -2053,6 +2079,7 @@ "integrity": "sha512-838DkdUA1u+QTCplatfq4B7+1lnDa/+QMI89x5WZHBcnNv+47N8QEj2k9I2MUU9xIv8XJ4XvPCviM/Dj7Uwt9g==", "deprecated": "This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-private-methods instead.", "dev": true, + "license": "MIT", "dependencies": { "@babel/helper-create-class-features-plugin": "^7.14.5", "@babel/helper-plugin-utils": "^7.14.5" @@ -2079,6 +2106,7 @@ "integrity": "sha512-62EyfyA3WA0mZiF2e2IV9mc9Ghwxcg8YTu8BS4Wss4Y3PY725OmS9M0qLORbJwLqFtGh+jiE4wAmocK2CTUK2Q==", "deprecated": "This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-private-property-in-object instead.", "dev": true, + "license": "MIT", "dependencies": { "@babel/helper-annotate-as-pure": "^7.14.5", "@babel/helper-create-class-features-plugin": "^7.14.5", @@ -3867,11 +3895,6 @@ "regenerator-runtime": "^0.13.2" } }, - "node_modules/@babel/runtime/node_modules/regenerator-runtime": { - "version": "0.13.3", - "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.13.3.tgz", - "integrity": "sha512-naKIZz2GQ8JWh///G7L3X6LaQUAMp2lvb1rvwwsURe/VXwD6VMfr+/1NuNw3ag8v2kY1aQ/go5SNn79O9JU7yw==" - }, "node_modules/@babel/template": { "version": "7.6.0", "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.6.0.tgz", @@ -3928,6 +3951,412 @@ "node": ">=6.9.0" } }, + "node_modules/@emnapi/runtime": { + "version": "1.11.3", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz", + "integrity": "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@emnapi/runtime/node_modules/tslib": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "dev": true, + "license": "0BSD", + "optional": true + }, + "node_modules/@epic-web/invariant": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@epic-web/invariant/-/invariant-1.0.0.tgz", + "integrity": "sha512-lrTPqgvfFQtR/eY/qkIzp98OGdNJu0m5ji3q/nJI8v3SXkRKEnWiOxMmbvcSoAIzv/cGiuvRy57k4suKQSAdwA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@img/sharp-darwin-arm64": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.33.5.tgz", + "integrity": "sha512-UT4p+iz/2H4twwAoLCqfA9UH5pI6DggwKEGuaPy7nCVQ8ZsiY5PIcrRvD1DzuY3qYL07NtIQcWnBSY/heikIFQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-arm64": "1.0.4" + } + }, + "node_modules/@img/sharp-darwin-x64": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.33.5.tgz", + "integrity": "sha512-fyHac4jIc1ANYGRDxtiqelIbdWkIuQaI84Mv45KvGRRxSAa7o7d1ZKAOBaYbnepLC1WqxfpimdeWfvqqSGwR2Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-x64": "1.0.4" + } + }, + "node_modules/@img/sharp-libvips-darwin-arm64": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.0.4.tgz", + "integrity": "sha512-XblONe153h0O2zuFfTAbQYAX2JhYmDHeWikp1LM9Hul9gVPjFY427k6dFEcOL72O01QxQsWi761svJ/ev9xEDg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-darwin-x64": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.0.4.tgz", + "integrity": "sha512-xnGR8YuZYfJGmWPvmlunFaWJsb9T/AO2ykoP3Fz/0X5XV2aoYBPkX6xqCQvUTKKiLddarLaxpzNe+b1hjeWHAQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.0.5.tgz", + "integrity": "sha512-gvcC4ACAOPRNATg/ov8/MnbxFDJqf/pDePbBnuBDcjsI8PssmjoKMAz4LtLaVi+OnSb5FK/yIOamqDwGmXW32g==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm64": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.0.4.tgz", + "integrity": "sha512-9B+taZ8DlyyqzZQnoeIvDVR/2F4EbMepXMc/NdVbkzsJbzkUjhXv/70GQJ7tdLA4YJgNP25zukcxpX2/SueNrA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-s390x": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.0.4.tgz", + "integrity": "sha512-u7Wz6ntiSSgGSGcjZ55im6uvTrOxSIS8/dgoVMoiGE9I6JAfU50yH5BoDlYA1tcuGS7g/QNtetJnxA6QEsCVTA==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-x64": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.0.4.tgz", + "integrity": "sha512-MmWmQ3iPFZr0Iev+BAgVMb3ZyC4KeFc3jFxnNbEPas60e1cIfevbtuyf9nDGIzOaW9PdnDciJm+wFFaTlj5xYw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-arm64": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.0.4.tgz", + "integrity": "sha512-9Ti+BbTYDcsbp4wfYib8Ctm1ilkugkA/uscUn6UXK1ldpC1JjiXbLfFZtRlBhjPZ5o1NCLiDbg8fhUPKStHoTA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-x64": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.0.4.tgz", + "integrity": "sha512-viYN1KX9m+/hGkJtvYYp+CCLgnJXwiQB39damAO7WMdKWlIhmYTfHjwSbQeUK/20vY154mwezd9HflVFM1wVSw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-linux-arm": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.33.5.tgz", + "integrity": "sha512-JTS1eldqZbJxjvKaAkxhZmBqPRGmxgu+qFKSInv8moZ2AmT5Yib3EQ1c6gp493HvrvV8QgdOXdyaIBrhvFhBMQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm": "1.0.5" + } + }, + "node_modules/@img/sharp-linux-arm64": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.33.5.tgz", + "integrity": "sha512-JMVv+AMRyGOHtO1RFBiJy/MBsgz0x4AWrT6QoEVVTyh1E39TrCUpTRI7mx9VksGX4awWASxqCYLCV4wBZHAYxA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm64": "1.0.4" + } + }, + "node_modules/@img/sharp-linux-s390x": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.33.5.tgz", + "integrity": "sha512-y/5PCd+mP4CA/sPDKl2961b+C9d+vPAveS33s6Z3zfASk2j5upL6fXVPZi7ztePZ5CuH+1kW8JtvxgbuXHRa4Q==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-s390x": "1.0.4" + } + }, + "node_modules/@img/sharp-linux-x64": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.33.5.tgz", + "integrity": "sha512-opC+Ok5pRNAzuvq1AG0ar+1owsu842/Ab+4qvU879ippJBHvyY5n2mxF1izXqkPYlGuP/M556uh53jRLJmzTWA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-x64": "1.0.4" + } + }, + "node_modules/@img/sharp-linuxmusl-arm64": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.33.5.tgz", + "integrity": "sha512-XrHMZwGQGvJg2V/oRSUfSAfjfPxO+4DkiRh6p2AFjLQztWUuY/o8Mq0eMQVIY7HJ1CDQUJlxGGZRw1a5bqmd1g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-arm64": "1.0.4" + } + }, + "node_modules/@img/sharp-linuxmusl-x64": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.33.5.tgz", + "integrity": "sha512-WT+d/cgqKkkKySYmqoZ8y3pxx7lx9vVejxW/W4DOFMYVSkErR+w7mf2u8m/y4+xHe7yY9DAXQMWQhpnMuFfScw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-x64": "1.0.4" + } + }, + "node_modules/@img/sharp-wasm32": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.33.5.tgz", + "integrity": "sha512-ykUW4LVGaMcU9lu9thv85CbRMAwfeadCJHRsg2GmeRa/cJxsVY9Rbd57JcMxBkKHag5U/x7TSBpScF4U8ElVzg==", + "cpu": [ + "wasm32" + ], + "dev": true, + "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT", + "optional": true, + "dependencies": { + "@emnapi/runtime": "^1.2.0" + }, + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-ia32": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.33.5.tgz", + "integrity": "sha512-T36PblLaTwuVJ/zw/LaH0PdZkRz5rd3SmMHX8GSmR7vtNSP5Z6bQkExdSK7xGWyxLw4sUknBuugTelgw2faBbQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-x64": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.33.5.tgz", + "integrity": "sha512-MpY/o8/8kj+EcnxwvrP4aTJSWw/aZ7JIGR4aBeZkZw5B7/Jn+tY9/VNwtcoGmdT7GfggGIU4kygOMSbYnOrAbg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, "node_modules/@jest/types": { "version": "24.9.0", "resolved": "https://registry.npmjs.org/@jest/types/-/types-24.9.0.tgz", @@ -3942,6 +4371,12 @@ "node": ">= 6" } }, + "node_modules/@microsoft/clarity": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@microsoft/clarity/-/clarity-1.0.2.tgz", + "integrity": "sha512-9EZYROFpJxEGmQpHvUFqvD3ZJ7QQSqnibYSWmS+1xusoZfG1QQ1/Al9yVBBc11DWMbJrs1pe1hLT273it/skJg==", + "license": "MIT" + }, "node_modules/@nicolo-ribaudo/chokidar-2": { "version": "2.1.8-no-fsevents.2", "resolved": "https://registry.npmjs.org/@nicolo-ribaudo/chokidar-2/-/chokidar-2-2.1.8-no-fsevents.2.tgz", @@ -4413,6 +4848,13 @@ "resolved": "https://registry.npmjs.org/@xtuc/long/-/long-4.2.2.tgz", "integrity": "sha512-NuHqBY1PB/D8xU6s/thBgOAiAP7HOYDQ32+BFZILJ8ivkUkAHQnWfn6WhL79Owj1qmUnoN/YPhktdIoucipkAQ==" }, + "node_modules/@yarnpkg/lockfile": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@yarnpkg/lockfile/-/lockfile-1.1.0.tgz", + "integrity": "sha512-GpSwvyXOcOOlV70vbnzjj4fW5xW/FdUF6nQEt1ENy7m4ZCczi1+/buVUPAqmGfqznsORNFzUMjctTIp8a9tuCQ==", + "dev": true, + "license": "BSD-2-Clause" + }, "node_modules/abab": { "version": "1.0.4", "resolved": "https://registry.npmjs.org/abab/-/abab-1.0.4.tgz", @@ -4827,32 +5269,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/array-includes/node_modules/get-intrinsic": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.1.1.tgz", - "integrity": "sha512-kWZrnVM42QCiEA2Ig1bG8zjoIMOgxWwYCEeNdwY6Tv/cOSeGpcoX4pXHfKUxNKVoArnrEr2e9srnAxxGIraS9Q==", - "dev": true, - "dependencies": { - "function-bind": "^1.1.1", - "has": "^1.0.3", - "has-symbols": "^1.0.1" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/array-includes/node_modules/has-symbols": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.2.tgz", - "integrity": "sha512-chXa79rL/UC2KlX17jo3vRGz0azaWEx5tGqZg5pO3NUyEJVB17dMruQlzCCOfUvElghKcm5194+BCRvi2Rv/Gw==", - "dev": true, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, "node_modules/array-includes/node_modules/is-callable": { "version": "1.2.3", "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.3.tgz", @@ -5062,32 +5478,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/array.prototype.flatmap/node_modules/get-intrinsic": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.1.1.tgz", - "integrity": "sha512-kWZrnVM42QCiEA2Ig1bG8zjoIMOgxWwYCEeNdwY6Tv/cOSeGpcoX4pXHfKUxNKVoArnrEr2e9srnAxxGIraS9Q==", - "dev": true, - "dependencies": { - "function-bind": "^1.1.1", - "has": "^1.0.3", - "has-symbols": "^1.0.1" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/array.prototype.flatmap/node_modules/has-symbols": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.2.tgz", - "integrity": "sha512-chXa79rL/UC2KlX17jo3vRGz0azaWEx5tGqZg5pO3NUyEJVB17dMruQlzCCOfUvElghKcm5194+BCRvi2Rv/Gw==", - "dev": true, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, "node_modules/array.prototype.flatmap/node_modules/is-callable": { "version": "1.2.3", "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.3.tgz", @@ -5303,6 +5693,12 @@ "node": ">= 4.5.0" } }, + "node_modules/atob-lite": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/atob-lite/-/atob-lite-2.0.0.tgz", + "integrity": "sha512-LEeSAWeh2Gfa2FtlQE1shxQ8zi5F9GHarrGKz08TMdODD5T4eH6BMsvtnhbWZ+XQn+Gb6om/917ucvRu7l7ukw==", + "license": "MIT" + }, "node_modules/audio-context": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/audio-context/-/audio-context-1.0.1.tgz", @@ -6010,6 +6406,12 @@ "regenerator-runtime": "^0.11.0" } }, + "node_modules/babel-runtime/node_modules/regenerator-runtime": { + "version": "0.11.1", + "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.11.1.tgz", + "integrity": "sha512-MguG95oij0fC3QV3URf4V2SDYGJhJnJGqvIIgdECeODCT98wSWDAJ94SSuVpYQUoTcGUIL6L4yNB7j1DFFHSBg==", + "license": "MIT" + }, "node_modules/babel-template": { "version": "6.26.0", "resolved": "https://registry.npmjs.org/babel-template/-/babel-template-6.26.0.tgz", @@ -6622,13 +7024,50 @@ } }, "node_modules/call-bind": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.9.tgz", + "integrity": "sha512-a/hy+pNsFUTR+Iz8TCJvXudKVLAnz/DyeSUo10I5yvFDQJBFU2s9uqQpoSrJlroHUKoKqzg+epxyP9lqFdzfBQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "get-intrinsic": "^1.3.0", + "set-function-length": "^1.2.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/call-bind-apply-helpers": { "version": "1.0.2", - "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.2.tgz", - "integrity": "sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA==", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", "dev": true, + "license": "MIT", "dependencies": { - "function-bind": "^1.1.1", - "get-intrinsic": "^1.0.2" + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" }, "funding": { "url": "https://github.com/sponsors/ljharb" @@ -7113,6 +7552,20 @@ "node": ">=0.10.0" } }, + "node_modules/color": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/color/-/color-4.2.3.tgz", + "integrity": "sha512-1rXeuUUiGGrykh+CeBdu5Ie7OJwinCgQY0bc7GCRxy5xVHy+moaqkpL/jqQq0MtQOeYcrqEz4abc5f0KtU7W4A==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1", + "color-string": "^1.9.0" + }, + "engines": { + "node": ">=12.5.0" + } + }, "node_modules/color-convert": { "version": "1.9.3", "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", @@ -7126,6 +7579,37 @@ "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=" }, + "node_modules/color-string": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/color-string/-/color-string-1.9.1.tgz", + "integrity": "sha512-shrVawQFojnZv6xM40anx4CkoDP+fZsw/ZerEMsW/pyzsRbElpsL/DBVW7q3ExxwusdNXI3lXpuhEZkzs8p5Eg==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-name": "^1.0.0", + "simple-swizzle": "^0.2.2" + } + }, + "node_modules/color/node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color/node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true, + "license": "MIT" + }, "node_modules/colorette": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/colorette/-/colorette-1.2.1.tgz", @@ -7628,6 +8112,88 @@ "sha.js": "^2.4.8" } }, + "node_modules/cross-env": { + "version": "10.1.0", + "resolved": "https://registry.npmjs.org/cross-env/-/cross-env-10.1.0.tgz", + "integrity": "sha512-GsYosgnACZTADcmEyJctkJIoqAhHjttw7RsFrVoJNXbsWWqaq6Ym+7kZjq6mS45O0jij6vtiReppKQEtqWy6Dw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@epic-web/invariant": "^1.0.0", + "cross-spawn": "^7.0.6" + }, + "bin": { + "cross-env": "dist/bin/cross-env.js", + "cross-env-shell": "dist/bin/cross-env-shell.js" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/cross-env/node_modules/cross-spawn": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", + "dev": true, + "license": "MIT", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/cross-env/node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/cross-env/node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "dev": true, + "license": "MIT", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/cross-env/node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/cross-env/node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "dev": true, + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, "node_modules/cross-spawn": { "version": "6.0.5", "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-6.0.5.tgz", @@ -7665,6 +8231,13 @@ "node": "*" } }, + "node_modules/crypto-js": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/crypto-js/-/crypto-js-4.2.0.tgz", + "integrity": "sha512-KALDyEYgpY+Rlob/iriUtjV6d5Eq+Y191A5g4UqLAi8CyGP9N1+FdVbkc1SxKc2r4YAYqG8JzO2KGL+AizD70Q==", + "deprecated": "Active development of CryptoJS has been discontinued. This library is no longer maintained.", + "license": "MIT" + }, "node_modules/css-loader": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/css-loader/-/css-loader-1.0.1.tgz", @@ -8136,6 +8709,24 @@ "node": ">=0.10.0" } }, + "node_modules/define-data-property": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.4.tgz", + "integrity": "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "gopd": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/define-properties": { "version": "1.1.3", "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.1.3.tgz", @@ -8268,6 +8859,16 @@ "node": ">=0.10.0" } }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, "node_modules/detect-node": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/detect-node/-/detect-node-2.0.4.tgz", @@ -8455,6 +9056,21 @@ "once": "^1.3.1" } }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/duplexer2": { "version": "0.1.4", "resolved": "https://registry.npmjs.org/duplexer2/-/duplexer2-0.1.4.tgz", @@ -8695,6 +9311,39 @@ "node": ">= 0.4" } }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz", + "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/es-to-primitive": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/es-to-primitive/-/es-to-primitive-1.2.0.tgz", @@ -9130,32 +9779,6 @@ "node": ">=4" } }, - "node_modules/eslint-plugin-import/node_modules/get-intrinsic": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.1.1.tgz", - "integrity": "sha512-kWZrnVM42QCiEA2Ig1bG8zjoIMOgxWwYCEeNdwY6Tv/cOSeGpcoX4pXHfKUxNKVoArnrEr2e9srnAxxGIraS9Q==", - "dev": true, - "dependencies": { - "function-bind": "^1.1.1", - "has": "^1.0.3", - "has-symbols": "^1.0.1" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/eslint-plugin-import/node_modules/has-symbols": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.2.tgz", - "integrity": "sha512-chXa79rL/UC2KlX17jo3vRGz0azaWEx5tGqZg5pO3NUyEJVB17dMruQlzCCOfUvElghKcm5194+BCRvi2Rv/Gw==", - "dev": true, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, "node_modules/eslint-plugin-import/node_modules/is-callable": { "version": "1.2.3", "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.3.tgz", @@ -9489,32 +10112,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/eslint-plugin-react/node_modules/get-intrinsic": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.1.1.tgz", - "integrity": "sha512-kWZrnVM42QCiEA2Ig1bG8zjoIMOgxWwYCEeNdwY6Tv/cOSeGpcoX4pXHfKUxNKVoArnrEr2e9srnAxxGIraS9Q==", - "dev": true, - "dependencies": { - "function-bind": "^1.1.1", - "has": "^1.0.3", - "has-symbols": "^1.0.1" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/eslint-plugin-react/node_modules/has-symbols": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.2.tgz", - "integrity": "sha512-chXa79rL/UC2KlX17jo3vRGz0azaWEx5tGqZg5pO3NUyEJVB17dMruQlzCCOfUvElghKcm5194+BCRvi2Rv/Gw==", - "dev": true, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, "node_modules/eslint-plugin-react/node_modules/is-callable": { "version": "1.2.3", "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.3.tgz", @@ -9788,6 +10385,39 @@ "node": ">=4" } }, + "node_modules/esptool-js": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/esptool-js/-/esptool-js-0.5.7.tgz", + "integrity": "sha512-k3pkXU9OTySCd58OUDjuJWNnFjM+QpPWAghxyWPm3zNfaLiP4ex2jNd7Rj0jWPu3/fgvwau236tetsTZrh4x5g==", + "license": "Apache-2.0", + "dependencies": { + "atob-lite": "^2.0.0", + "pako": "^2.1.0", + "tslib": "^2.4.1" + } + }, + "node_modules/esptool-js/node_modules/pako": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/pako/-/pako-2.2.0.tgz", + "integrity": "sha512-zJq6RP/5q+TO2OpFV3FHzlPnFjmkb7Nc99a5SNjJE+uu/PkpChs+NIZSSzbBoD+6kjiISXjfYdwj1ZRQ81dz/w==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/puzrin" + }, + { + "type": "github", + "url": "https://github.com/sponsors/nodeca" + } + ], + "license": "(MIT AND Zlib)" + }, + "node_modules/esptool-js/node_modules/tslib": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "license": "0BSD" + }, "node_modules/esquery": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.0.1.tgz", @@ -10487,18 +11117,6 @@ "node": ">=8.6" } }, - "node_modules/fast-glob/node_modules/picomatch": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.0.tgz", - "integrity": "sha512-lY1Q/PiJGC2zOv/z391WOTD+Z02bCgsFfvxoXXf6h7kv9o+WmsmzYqrAwY63sNgOxE4xEdq0WyUnXfKeBrSvYw==", - "dev": true, - "engines": { - "node": ">=8.6" - }, - "funding": { - "url": "https://github.com/sponsors/jonschlinkert" - } - }, "node_modules/fast-glob/node_modules/to-regex-range": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", @@ -10757,6 +11375,79 @@ "node": ">=6" } }, + "node_modules/find-yarn-workspace-root": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/find-yarn-workspace-root/-/find-yarn-workspace-root-2.0.0.tgz", + "integrity": "sha512-1IMnbjt4KzsQfnhnzNd8wUEgXZ44IzZaZmnLYx7D5FZlaHt2gW20Cri8Q+E/t5tIj4+epTBub+2Zxu/vNILzqQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "micromatch": "^4.0.2" + } + }, + "node_modules/find-yarn-workspace-root/node_modules/braces": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", + "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", + "dev": true, + "license": "MIT", + "dependencies": { + "fill-range": "^7.1.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/find-yarn-workspace-root/node_modules/fill-range": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", + "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", + "dev": true, + "license": "MIT", + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/find-yarn-workspace-root/node_modules/is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/find-yarn-workspace-root/node_modules/micromatch": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", + "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", + "dev": true, + "license": "MIT", + "dependencies": { + "braces": "^3.0.3", + "picomatch": "^2.3.1" + }, + "engines": { + "node": ">=8.6" + } + }, + "node_modules/find-yarn-workspace-root/node_modules/to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-number": "^7.0.0" + }, + "engines": { + "node": ">=8.0" + } + }, "node_modules/findup": { "version": "0.1.5", "resolved": "https://registry.npmjs.org/findup/-/findup-0.1.5.tgz", @@ -11666,9 +12357,13 @@ "optional": true }, "node_modules/function-bind": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", - "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==" + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } }, "node_modules/function.prototype.name": { "version": "1.1.1", @@ -11717,29 +12412,42 @@ "integrity": "sha1-XYVZJKQwOITJY4qrEnzOTQBlljs=" }, "node_modules/get-intrinsic": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.0.2.tgz", - "integrity": "sha512-aeX0vrFm21ILl3+JpFFRNe9aUvp6VFZb2/CTbgLb8j75kOhvoNYjt9d8KA/tJG4gSo8nzEDedRl0h7vDmBYRVg==", + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", "dev": true, + "license": "MIT", "dependencies": { - "function-bind": "^1.1.1", - "has": "^1.0.3", - "has-symbols": "^1.0.1" + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" }, "funding": { "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/get-intrinsic/node_modules/has-symbols": { + "node_modules/get-proto": { "version": "1.0.1", - "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.1.tgz", - "integrity": "sha512-PLcsoqu++dmEIZB+6totNFKq/7Do+Z0u4oT0zKOJNl3lYK6vGwwu2hjHs+68OEZbTjiUE9bgOABXbP/GvrS0Kg==", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", "dev": true, + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, "engines": { "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" } }, "node_modules/get-stream": { @@ -11943,6 +12651,19 @@ "resolved": "https://registry.npmjs.org/google-closure-library/-/google-closure-library-20190301.0.0.tgz", "integrity": "sha512-mpeszbnXpRhXZ0sPqUxBgUmk0RtmzrJRy3KFygp0Ih9JuRUjQTCLhwYQeIlK2vB2lShhY/KUo9E1Z1gvxDFxOQ==" }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/got": { "version": "8.3.2", "resolved": "https://registry.npmjs.org/got/-/got-8.3.2.tgz", @@ -12110,6 +12831,19 @@ "node": ">=4" } }, + "node_modules/has-property-descriptors": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.2.tgz", + "integrity": "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-define-property": "^1.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/has-symbol-support-x": { "version": "1.4.2", "resolved": "https://registry.npmjs.org/has-symbol-support-x/-/has-symbol-support-x-1.4.2.tgz", @@ -12119,11 +12853,15 @@ } }, "node_modules/has-symbols": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.0.tgz", - "integrity": "sha1-uhqPGvKg/DllD1yFA2dwQSIGO0Q=", + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", "engines": { "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, "node_modules/has-to-string-tag-x": { @@ -12194,6 +12932,19 @@ "minimalistic-assert": "^1.0.1" } }, + "node_modules/hasown": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", + "dev": true, + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/he": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/he/-/he-1.2.0.tgz", @@ -12835,32 +13586,6 @@ "node": ">= 0.4" } }, - "node_modules/internal-slot/node_modules/get-intrinsic": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.1.1.tgz", - "integrity": "sha512-kWZrnVM42QCiEA2Ig1bG8zjoIMOgxWwYCEeNdwY6Tv/cOSeGpcoX4pXHfKUxNKVoArnrEr2e9srnAxxGIraS9Q==", - "dev": true, - "dependencies": { - "function-bind": "^1.1.1", - "has": "^1.0.3", - "has-symbols": "^1.0.1" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/internal-slot/node_modules/has-symbols": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.2.tgz", - "integrity": "sha512-chXa79rL/UC2KlX17jo3vRGz0azaWEx5tGqZg5pO3NUyEJVB17dMruQlzCCOfUvElghKcm5194+BCRvi2Rv/Gw==", - "dev": true, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, "node_modules/interpret": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/interpret/-/interpret-1.2.0.tgz", @@ -13147,6 +13872,22 @@ "node": ">=0.10.0" } }, + "node_modules/is-docker": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/is-docker/-/is-docker-2.2.1.tgz", + "integrity": "sha512-F+i2BKsFrH66iaUFc0woD8sLy8getkwTwtOBjvs56Cx4CgJDeKQeqfz8wAYiSb8JOprWhHH5p77PbmYCvvUuXQ==", + "dev": true, + "license": "MIT", + "bin": { + "is-docker": "cli.js" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/is-dotfile": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/is-dotfile/-/is-dotfile-1.0.3.tgz", @@ -14751,6 +15492,15 @@ "node": ">=4" } }, + "node_modules/jose": { + "version": "6.2.12", + "resolved": "https://registry.npmjs.org/jose/-/jose-6.2.12.tgz", + "integrity": "sha512-9NiFmJEex0sy2Dk58j2UGBSHgUs2ypF9eZSu4L6vjOX3Dp96Sw1F3uL+H+D1sx02jZZdzUT0HgvCy59CuvXcWw==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, "node_modules/js-base64": { "version": "2.4.9", "resolved": "https://registry.npmjs.org/js-base64/-/js-base64-2.4.9.tgz", @@ -14867,12 +15617,23 @@ "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==" }, "node_modules/json-stable-stringify": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/json-stable-stringify/-/json-stable-stringify-1.0.1.tgz", - "integrity": "sha1-mnWdOcXy/1A/1TAGRu1EX4jE+a8=", + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/json-stable-stringify/-/json-stable-stringify-1.3.0.tgz", + "integrity": "sha512-qtYiSSFlwot9XHtF9bD9c7rwKjr+RecWT//ZnPvSmEjpV5mmPOCN4j8UjY5hbjNkOwZ/jQv3J6R1/pL7RwgMsg==", "dev": true, + "license": "MIT", "dependencies": { - "jsonify": "~0.0.0" + "call-bind": "^1.0.8", + "call-bound": "^1.0.4", + "isarray": "^2.0.5", + "jsonify": "^0.0.1", + "object-keys": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, "node_modules/json-stable-stringify-without-jsonify": { @@ -14881,6 +15642,13 @@ "integrity": "sha1-nbe1lJatPzz+8wp1FC0tkwrXJlE=", "dev": true }, + "node_modules/json-stable-stringify/node_modules/isarray": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-2.0.5.tgz", + "integrity": "sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw==", + "dev": true, + "license": "MIT" + }, "node_modules/json-stringify-safe": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz", @@ -14921,12 +15689,13 @@ } }, "node_modules/jsonify": { - "version": "0.0.0", - "resolved": "https://registry.npmjs.org/jsonify/-/jsonify-0.0.0.tgz", - "integrity": "sha1-LHS27kHZPKUbe1qu6PUDYx0lKnM=", + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/jsonify/-/jsonify-0.0.1.tgz", + "integrity": "sha512-2/Ki0GcmuqSrgFyelQq9M05y7PS0mEwuIzrf3f1fPqkVDVRvZrPZtVSMHxdgo8Aq0sxAOb/cr2aqqA3LeWHVPg==", "dev": true, - "engines": { - "node": "*" + "license": "Public Domain", + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, "node_modules/jsprim": { @@ -14957,18 +15726,6 @@ "node": ">=4.0" } }, - "node_modules/jsx-ast-utils/node_modules/has-symbols": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.2.tgz", - "integrity": "sha512-chXa79rL/UC2KlX17jo3vRGz0azaWEx5tGqZg5pO3NUyEJVB17dMruQlzCCOfUvElghKcm5194+BCRvi2Rv/Gw==", - "dev": true, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, "node_modules/jsx-ast-utils/node_modules/object.assign": { "version": "4.1.2", "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.2.tgz", @@ -15025,6 +15782,16 @@ "node": ">=0.10.0" } }, + "node_modules/klaw-sync": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/klaw-sync/-/klaw-sync-6.0.0.tgz", + "integrity": "sha512-nIeuVSzdCCs6TDPTqI8w1Yre34sSq7AkZ4B3sfOBbI2CgVSB4Du4aLQijFU2+lhAFCwt9+42Hel6lQNIv6AntQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "graceful-fs": "^4.1.11" + } + }, "node_modules/lcid": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/lcid/-/lcid-1.0.0.tgz", @@ -15361,6 +16128,16 @@ "css-mediaquery": "^0.1.2" } }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, "node_modules/math-random": { "version": "1.0.4", "resolved": "https://registry.npmjs.org/math-random/-/math-random-1.0.4.tgz", @@ -16196,6 +16973,36 @@ "node": ">=4" } }, + "node_modules/open": { + "version": "7.4.2", + "resolved": "https://registry.npmjs.org/open/-/open-7.4.2.tgz", + "integrity": "sha512-MVHddDVweXZF3awtlAS+6pgKLlm/JgxZ90+/NBurBoQctVOOB/zDdVjcyPzQ+0laDGbsWgrRkflI65sQeOgT9Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-docker": "^2.0.0", + "is-wsl": "^2.1.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/open/node_modules/is-wsl": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/is-wsl/-/is-wsl-2.2.0.tgz", + "integrity": "sha512-fKzAra0rGJUUBwGBgNkHZuToZcn+TtXHpeCgmkMJMMYx1sQDYaCSyjJBSCa2nH1DGm7s3n1oBnohoVTBaN7Lww==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-docker": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/openblock-blocks": { "version": "0.1.0-prerelease.20250611095335", "resolved": "https://registry.npmjs.org/openblock-blocks/-/openblock-blocks-0.1.0-prerelease.20250611095335.tgz", @@ -16684,6 +17491,263 @@ "node": ">=0.10.0" } }, + "node_modules/patch-package": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/patch-package/-/patch-package-8.0.1.tgz", + "integrity": "sha512-VsKRIA8f5uqHQ7NGhwIna6Bx6D9s/1iXlA1hthBVBEbkq+t4kXD0HHt+rJhf/Z+Ci0F/HCB2hvn0qLdLG+Qxlw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@yarnpkg/lockfile": "^1.1.0", + "chalk": "^4.1.2", + "ci-info": "^3.7.0", + "cross-spawn": "^7.0.3", + "find-yarn-workspace-root": "^2.0.0", + "fs-extra": "^10.0.0", + "json-stable-stringify": "^1.0.2", + "klaw-sync": "^6.0.0", + "minimist": "^1.2.6", + "open": "^7.4.2", + "semver": "^7.5.3", + "slash": "^2.0.0", + "tmp": "^0.2.4", + "yaml": "^2.2.2" + }, + "bin": { + "patch-package": "index.js" + }, + "engines": { + "node": ">=14", + "npm": ">5" + } + }, + "node_modules/patch-package/node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/patch-package/node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/patch-package/node_modules/ci-info": { + "version": "3.9.0", + "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-3.9.0.tgz", + "integrity": "sha512-NIxF55hv4nSqQswkAeiOi1r83xy8JldOFDTWiug55KBu9Jnblncd2U6ViHmYgHf01TPZS77NJBhBMKdWj9HQMQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/sibiraj-s" + } + ], + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/patch-package/node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/patch-package/node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true, + "license": "MIT" + }, + "node_modules/patch-package/node_modules/cross-spawn": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", + "dev": true, + "license": "MIT", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/patch-package/node_modules/fs-extra": { + "version": "10.1.0", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-10.1.0.tgz", + "integrity": "sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "graceful-fs": "^4.2.0", + "jsonfile": "^6.0.1", + "universalify": "^2.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/patch-package/node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/patch-package/node_modules/jsonfile": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.1.tgz", + "integrity": "sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "universalify": "^2.0.0" + }, + "optionalDependencies": { + "graceful-fs": "^4.1.6" + } + }, + "node_modules/patch-package/node_modules/minimist": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", + "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/patch-package/node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/patch-package/node_modules/semver": { + "version": "7.8.5", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", + "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/patch-package/node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "dev": true, + "license": "MIT", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/patch-package/node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/patch-package/node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/patch-package/node_modules/tmp": { + "version": "0.2.7", + "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.2.7.tgz", + "integrity": "sha512-e0votIpp4Uo2AJYSzVHV6xCcawuiez3DzqDAbrTc3YxBkplN6e+dM13ZeIcZnDg/QpSuU2zfZ3rzwY8ukEnaXw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.14" + } + }, + "node_modules/patch-package/node_modules/universalify": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz", + "integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 10.0.0" + } + }, + "node_modules/patch-package/node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "dev": true, + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, "node_modules/path-browserify": { "version": "0.0.1", "resolved": "https://registry.npmjs.org/path-browserify/-/path-browserify-0.0.1.tgz", @@ -16783,10 +17847,11 @@ "dev": true }, "node_modules/picomatch": { - "version": "2.2.2", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.2.2.tgz", - "integrity": "sha512-q0M/9eZHzmr0AulXyPwNfZjtwZ/RBZlbN3K3CErVrk50T2ASYI7Bye0EvekFY3IP1Nt2DHu0re+V2ZHIpMkuWg==", - "optional": true, + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz", + "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==", + "devOptional": true, + "license": "MIT", "engines": { "node": ">=8.6" }, @@ -17369,6 +18434,12 @@ "node": ">=6" } }, + "node_modules/qrcode-generator": { + "version": "1.5.2", + "resolved": "https://registry.npmjs.org/qrcode-generator/-/qrcode-generator-1.5.2.tgz", + "integrity": "sha512-pItrW0Z9HnDBnFmgiNrY1uxRdri32Uh9EjNYLPVC2zZ3ZRIIEqBoDgm4DkvDwNNDHTK7FNkmr8zAa77BYc9xNw==", + "license": "MIT" + }, "node_modules/qs": { "version": "6.5.2", "resolved": "https://registry.npmjs.org/qs/-/qs-6.5.2.tgz", @@ -18064,9 +19135,10 @@ } }, "node_modules/regenerator-runtime": { - "version": "0.11.1", - "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.11.1.tgz", - "integrity": "sha512-MguG95oij0fC3QV3URf4V2SDYGJhJnJGqvIIgdECeODCT98wSWDAJ94SSuVpYQUoTcGUIL6L4yNB7j1DFFHSBg==" + "version": "0.13.11", + "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.13.11.tgz", + "integrity": "sha512-kY1AZVr2Ra+t+piVaJ4gxaFaReZVH40AKNo7UCX6W+dEwBo/2oZJzqfuN1qLq1oL45o56cPaTXELwrTh8Fpggg==", + "license": "MIT" }, "node_modules/regenerator-transform": { "version": "0.14.5", @@ -18089,12 +19161,6 @@ "node": ">=6.9.0" } }, - "node_modules/regenerator-transform/node_modules/regenerator-runtime": { - "version": "0.13.7", - "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.13.7.tgz", - "integrity": "sha512-a54FxoJDIr27pgf7IgeQGxmqUNYrcV338lf/6gH456HZ/PhX+5BcwHXG9ajESmwe6WRO0tAzRUrRmNONWgkrew==", - "dev": true - }, "node_modules/regex-cache": { "version": "0.4.4", "resolved": "https://registry.npmjs.org/regex-cache/-/regex-cache-0.4.4.tgz", @@ -18177,18 +19243,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/regexp.prototype.flags/node_modules/has-symbols": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.1.tgz", - "integrity": "sha512-PLcsoqu++dmEIZB+6totNFKq/7Do+Z0u4oT0zKOJNl3lYK6vGwwu2hjHs+68OEZbTjiUE9bgOABXbP/GvrS0Kg==", - "dev": true, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, "node_modules/regexp.prototype.flags/node_modules/is-callable": { "version": "1.1.5", "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.1.5.tgz", @@ -19087,6 +20141,24 @@ "integrity": "sha1-BF+XgtARrppoA93TgrJDkrPYkPc=", "dev": true }, + "node_modules/set-function-length": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.2.tgz", + "integrity": "sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==", + "dev": true, + "license": "MIT", + "dependencies": { + "define-data-property": "^1.1.4", + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "get-intrinsic": "^1.2.4", + "gopd": "^1.0.1", + "has-property-descriptors": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/set-immediate-shim": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/set-immediate-shim/-/set-immediate-shim-1.0.1.tgz", @@ -19148,6 +20220,59 @@ "resolved": "https://registry.npmjs.org/shallow-copy/-/shallow-copy-0.0.1.tgz", "integrity": "sha1-QV9CcC1z2BAzApLMXuhurhoRoXA=" }, + "node_modules/sharp": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.33.5.tgz", + "integrity": "sha512-haPVm1EkS9pgvHrQ/F3Xy+hgcuMV0Wm9vfIBSiwZ05k+xgb0PkBQpGsAA/oWdDobNaZTH5ppvHtzCFbnSEwHVw==", + "dev": true, + "hasInstallScript": true, + "license": "Apache-2.0", + "dependencies": { + "color": "^4.2.3", + "detect-libc": "^2.0.3", + "semver": "^7.6.3" + }, + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-darwin-arm64": "0.33.5", + "@img/sharp-darwin-x64": "0.33.5", + "@img/sharp-libvips-darwin-arm64": "1.0.4", + "@img/sharp-libvips-darwin-x64": "1.0.4", + "@img/sharp-libvips-linux-arm": "1.0.5", + "@img/sharp-libvips-linux-arm64": "1.0.4", + "@img/sharp-libvips-linux-s390x": "1.0.4", + "@img/sharp-libvips-linux-x64": "1.0.4", + "@img/sharp-libvips-linuxmusl-arm64": "1.0.4", + "@img/sharp-libvips-linuxmusl-x64": "1.0.4", + "@img/sharp-linux-arm": "0.33.5", + "@img/sharp-linux-arm64": "0.33.5", + "@img/sharp-linux-s390x": "0.33.5", + "@img/sharp-linux-x64": "0.33.5", + "@img/sharp-linuxmusl-arm64": "0.33.5", + "@img/sharp-linuxmusl-x64": "0.33.5", + "@img/sharp-wasm32": "0.33.5", + "@img/sharp-win32-ia32": "0.33.5", + "@img/sharp-win32-x64": "0.33.5" + } + }, + "node_modules/sharp/node_modules/semver": { + "version": "7.8.5", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", + "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, "node_modules/shebang-command": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-1.2.0.tgz", @@ -19204,6 +20329,23 @@ "integrity": "sha1-tf3AjxKH6hF4Yo5BXiUTK3NkbG0=", "dev": true }, + "node_modules/simple-swizzle": { + "version": "0.2.4", + "resolved": "https://registry.npmjs.org/simple-swizzle/-/simple-swizzle-0.2.4.tgz", + "integrity": "sha512-nAu1WFPQSMNr2Zn9PGSZK9AGn4t/y97lEm+MXTtUDwfP0ksAIX4nO+6ruD9Jwut4C49SB1Ws+fbXsm/yScWOHw==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-arrayish": "^0.3.1" + } + }, + "node_modules/simple-swizzle/node_modules/is-arrayish": { + "version": "0.3.4", + "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.3.4.tgz", + "integrity": "sha512-m6UrgzFVUYawGBh1dUsWR5M2Clqic9RVXC/9f8ceNlv2IcO9j9J/z8UoCLPqtsPBFNzEpfR3xftohbfqDx8EQA==", + "dev": true, + "license": "MIT" + }, "node_modules/slash": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/slash/-/slash-2.0.0.tgz", @@ -19938,32 +21080,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/string.prototype.matchall/node_modules/get-intrinsic": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.1.1.tgz", - "integrity": "sha512-kWZrnVM42QCiEA2Ig1bG8zjoIMOgxWwYCEeNdwY6Tv/cOSeGpcoX4pXHfKUxNKVoArnrEr2e9srnAxxGIraS9Q==", - "dev": true, - "dependencies": { - "function-bind": "^1.1.1", - "has": "^1.0.3", - "has-symbols": "^1.0.1" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/string.prototype.matchall/node_modules/has-symbols": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.2.tgz", - "integrity": "sha512-chXa79rL/UC2KlX17jo3vRGz0azaWEx5tGqZg5pO3NUyEJVB17dMruQlzCCOfUvElghKcm5194+BCRvi2Rv/Gw==", - "dev": true, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, "node_modules/string.prototype.matchall/node_modules/is-callable": { "version": "1.2.3", "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.3.tgz", @@ -20141,18 +21257,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/string.prototype.trimend/node_modules/has-symbols": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.1.tgz", - "integrity": "sha512-PLcsoqu++dmEIZB+6totNFKq/7Do+Z0u4oT0zKOJNl3lYK6vGwwu2hjHs+68OEZbTjiUE9bgOABXbP/GvrS0Kg==", - "dev": true, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, "node_modules/string.prototype.trimend/node_modules/is-callable": { "version": "1.1.5", "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.1.5.tgz", @@ -20302,18 +21406,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/string.prototype.trimstart/node_modules/has-symbols": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.1.tgz", - "integrity": "sha512-PLcsoqu++dmEIZB+6totNFKq/7Do+Z0u4oT0zKOJNl3lYK6vGwwu2hjHs+68OEZbTjiUE9bgOABXbP/GvrS0Kg==", - "dev": true, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, "node_modules/string.prototype.trimstart/node_modules/is-callable": { "version": "1.1.5", "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.1.5.tgz", @@ -20616,6 +21708,7 @@ "version": "1.4.5", "resolved": "https://registry.npmjs.org/terser-webpack-plugin/-/terser-webpack-plugin-1.4.5.tgz", "integrity": "sha512-04Rfe496lN8EYruwi6oPQkG0vo8C+HT49X687FZnpPF0qMAIHONI6HEXYPKDOE8e5HjXTyKfqRd/agHtH0kOtw==", + "license": "MIT", "dependencies": { "cacache": "^12.0.2", "find-cache-dir": "^2.1.0", @@ -21011,6 +22104,12 @@ "integrity": "sha1-f17oI66AUgfACvLfSoTsP8+lcLQ=", "dev": true }, + "node_modules/three": { + "version": "0.186.1", + "resolved": "https://registry.npmjs.org/three/-/three-0.186.1.tgz", + "integrity": "sha512-blFeqb49wRCSGUGj7gtpfnSGHy2lwDk94RhUmS1c/hTby70kvChbWpkJ4Pm1390LqzzvTmzgXKHPEafJwCb8jA==", + "license": "MIT" + }, "node_modules/throat": { "version": "4.1.0", "resolved": "https://registry.npmjs.org/throat/-/throat-4.1.0.tgz", @@ -21535,18 +22634,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/unbox-primitive/node_modules/has-symbols": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.2.tgz", - "integrity": "sha512-chXa79rL/UC2KlX17jo3vRGz0azaWEx5tGqZg5pO3NUyEJVB17dMruQlzCCOfUvElghKcm5194+BCRvi2Rv/Gw==", - "dev": true, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, "node_modules/unbzip2-stream": { "version": "1.4.3", "resolved": "https://registry.npmjs.org/unbzip2-stream/-/unbzip2-stream-1.4.3.tgz", @@ -22908,18 +23995,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/which-boxed-primitive/node_modules/has-symbols": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.2.tgz", - "integrity": "sha512-chXa79rL/UC2KlX17jo3vRGz0azaWEx5tGqZg5pO3NUyEJVB17dMruQlzCCOfUvElghKcm5194+BCRvi2Rv/Gw==", - "dev": true, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, "node_modules/which-boxed-primitive/node_modules/is-boolean-object": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/is-boolean-object/-/is-boolean-object-1.1.1.tgz", @@ -23190,6 +24265,22 @@ "resolved": "https://registry.npmjs.org/yallist/-/yallist-2.1.2.tgz", "integrity": "sha1-HBH5IY8HYImkfdUS+TxmmaaoHVI=" }, + "node_modules/yaml": { + "version": "2.9.0", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.0.tgz", + "integrity": "sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA==", + "dev": true, + "license": "ISC", + "bin": { + "yaml": "bin.mjs" + }, + "engines": { + "node": ">= 14.6" + }, + "funding": { + "url": "https://github.com/sponsors/eemeli" + } + }, "node_modules/yargs": { "version": "9.0.1", "resolved": "https://registry.npmjs.org/yargs/-/yargs-9.0.1.tgz", @@ -26047,13 +27138,6 @@ "integrity": "sha512-kq6anf9JGjW8Nt5rYfEuGRaEAaH1mkv3Bbu6rYvLOpPh/RusSJXuKPEAoZ7L7gybZkchE8+NV5g9vKF4AGAtsA==", "requires": { "regenerator-runtime": "^0.13.2" - }, - "dependencies": { - "regenerator-runtime": { - "version": "0.13.3", - "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.13.3.tgz", - "integrity": "sha512-naKIZz2GQ8JWh///G7L3X6LaQUAMp2lvb1rvwwsURe/VXwD6VMfr+/1NuNw3ag8v2kY1aQ/go5SNn79O9JU7yw==" - } } }, "@babel/template": { @@ -26110,6 +27194,191 @@ "@babel/helper-validator-identifier": "^7.25.9" } }, + "@emnapi/runtime": { + "version": "1.11.3", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz", + "integrity": "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==", + "dev": true, + "optional": true, + "requires": { + "tslib": "^2.4.0" + }, + "dependencies": { + "tslib": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "dev": true, + "optional": true + } + } + }, + "@epic-web/invariant": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@epic-web/invariant/-/invariant-1.0.0.tgz", + "integrity": "sha512-lrTPqgvfFQtR/eY/qkIzp98OGdNJu0m5ji3q/nJI8v3SXkRKEnWiOxMmbvcSoAIzv/cGiuvRy57k4suKQSAdwA==", + "dev": true + }, + "@img/sharp-darwin-arm64": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.33.5.tgz", + "integrity": "sha512-UT4p+iz/2H4twwAoLCqfA9UH5pI6DggwKEGuaPy7nCVQ8ZsiY5PIcrRvD1DzuY3qYL07NtIQcWnBSY/heikIFQ==", + "dev": true, + "optional": true, + "requires": { + "@img/sharp-libvips-darwin-arm64": "1.0.4" + } + }, + "@img/sharp-darwin-x64": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.33.5.tgz", + "integrity": "sha512-fyHac4jIc1ANYGRDxtiqelIbdWkIuQaI84Mv45KvGRRxSAa7o7d1ZKAOBaYbnepLC1WqxfpimdeWfvqqSGwR2Q==", + "dev": true, + "optional": true, + "requires": { + "@img/sharp-libvips-darwin-x64": "1.0.4" + } + }, + "@img/sharp-libvips-darwin-arm64": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.0.4.tgz", + "integrity": "sha512-XblONe153h0O2zuFfTAbQYAX2JhYmDHeWikp1LM9Hul9gVPjFY427k6dFEcOL72O01QxQsWi761svJ/ev9xEDg==", + "dev": true, + "optional": true + }, + "@img/sharp-libvips-darwin-x64": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.0.4.tgz", + "integrity": "sha512-xnGR8YuZYfJGmWPvmlunFaWJsb9T/AO2ykoP3Fz/0X5XV2aoYBPkX6xqCQvUTKKiLddarLaxpzNe+b1hjeWHAQ==", + "dev": true, + "optional": true + }, + "@img/sharp-libvips-linux-arm": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.0.5.tgz", + "integrity": "sha512-gvcC4ACAOPRNATg/ov8/MnbxFDJqf/pDePbBnuBDcjsI8PssmjoKMAz4LtLaVi+OnSb5FK/yIOamqDwGmXW32g==", + "dev": true, + "optional": true + }, + "@img/sharp-libvips-linux-arm64": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.0.4.tgz", + "integrity": "sha512-9B+taZ8DlyyqzZQnoeIvDVR/2F4EbMepXMc/NdVbkzsJbzkUjhXv/70GQJ7tdLA4YJgNP25zukcxpX2/SueNrA==", + "dev": true, + "optional": true + }, + "@img/sharp-libvips-linux-s390x": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.0.4.tgz", + "integrity": "sha512-u7Wz6ntiSSgGSGcjZ55im6uvTrOxSIS8/dgoVMoiGE9I6JAfU50yH5BoDlYA1tcuGS7g/QNtetJnxA6QEsCVTA==", + "dev": true, + "optional": true + }, + "@img/sharp-libvips-linux-x64": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.0.4.tgz", + "integrity": "sha512-MmWmQ3iPFZr0Iev+BAgVMb3ZyC4KeFc3jFxnNbEPas60e1cIfevbtuyf9nDGIzOaW9PdnDciJm+wFFaTlj5xYw==", + "dev": true, + "optional": true + }, + "@img/sharp-libvips-linuxmusl-arm64": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.0.4.tgz", + "integrity": "sha512-9Ti+BbTYDcsbp4wfYib8Ctm1ilkugkA/uscUn6UXK1ldpC1JjiXbLfFZtRlBhjPZ5o1NCLiDbg8fhUPKStHoTA==", + "dev": true, + "optional": true + }, + "@img/sharp-libvips-linuxmusl-x64": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.0.4.tgz", + "integrity": "sha512-viYN1KX9m+/hGkJtvYYp+CCLgnJXwiQB39damAO7WMdKWlIhmYTfHjwSbQeUK/20vY154mwezd9HflVFM1wVSw==", + "dev": true, + "optional": true + }, + "@img/sharp-linux-arm": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.33.5.tgz", + "integrity": "sha512-JTS1eldqZbJxjvKaAkxhZmBqPRGmxgu+qFKSInv8moZ2AmT5Yib3EQ1c6gp493HvrvV8QgdOXdyaIBrhvFhBMQ==", + "dev": true, + "optional": true, + "requires": { + "@img/sharp-libvips-linux-arm": "1.0.5" + } + }, + "@img/sharp-linux-arm64": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.33.5.tgz", + "integrity": "sha512-JMVv+AMRyGOHtO1RFBiJy/MBsgz0x4AWrT6QoEVVTyh1E39TrCUpTRI7mx9VksGX4awWASxqCYLCV4wBZHAYxA==", + "dev": true, + "optional": true, + "requires": { + "@img/sharp-libvips-linux-arm64": "1.0.4" + } + }, + "@img/sharp-linux-s390x": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.33.5.tgz", + "integrity": "sha512-y/5PCd+mP4CA/sPDKl2961b+C9d+vPAveS33s6Z3zfASk2j5upL6fXVPZi7ztePZ5CuH+1kW8JtvxgbuXHRa4Q==", + "dev": true, + "optional": true, + "requires": { + "@img/sharp-libvips-linux-s390x": "1.0.4" + } + }, + "@img/sharp-linux-x64": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.33.5.tgz", + "integrity": "sha512-opC+Ok5pRNAzuvq1AG0ar+1owsu842/Ab+4qvU879ippJBHvyY5n2mxF1izXqkPYlGuP/M556uh53jRLJmzTWA==", + "dev": true, + "optional": true, + "requires": { + "@img/sharp-libvips-linux-x64": "1.0.4" + } + }, + "@img/sharp-linuxmusl-arm64": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.33.5.tgz", + "integrity": "sha512-XrHMZwGQGvJg2V/oRSUfSAfjfPxO+4DkiRh6p2AFjLQztWUuY/o8Mq0eMQVIY7HJ1CDQUJlxGGZRw1a5bqmd1g==", + "dev": true, + "optional": true, + "requires": { + "@img/sharp-libvips-linuxmusl-arm64": "1.0.4" + } + }, + "@img/sharp-linuxmusl-x64": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.33.5.tgz", + "integrity": "sha512-WT+d/cgqKkkKySYmqoZ8y3pxx7lx9vVejxW/W4DOFMYVSkErR+w7mf2u8m/y4+xHe7yY9DAXQMWQhpnMuFfScw==", + "dev": true, + "optional": true, + "requires": { + "@img/sharp-libvips-linuxmusl-x64": "1.0.4" + } + }, + "@img/sharp-wasm32": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.33.5.tgz", + "integrity": "sha512-ykUW4LVGaMcU9lu9thv85CbRMAwfeadCJHRsg2GmeRa/cJxsVY9Rbd57JcMxBkKHag5U/x7TSBpScF4U8ElVzg==", + "dev": true, + "optional": true, + "requires": { + "@emnapi/runtime": "^1.2.0" + } + }, + "@img/sharp-win32-ia32": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.33.5.tgz", + "integrity": "sha512-T36PblLaTwuVJ/zw/LaH0PdZkRz5rd3SmMHX8GSmR7vtNSP5Z6bQkExdSK7xGWyxLw4sUknBuugTelgw2faBbQ==", + "dev": true, + "optional": true + }, + "@img/sharp-win32-x64": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.33.5.tgz", + "integrity": "sha512-MpY/o8/8kj+EcnxwvrP4aTJSWw/aZ7JIGR4aBeZkZw5B7/Jn+tY9/VNwtcoGmdT7GfggGIU4kygOMSbYnOrAbg==", + "dev": true, + "optional": true + }, "@jest/types": { "version": "24.9.0", "resolved": "https://registry.npmjs.org/@jest/types/-/types-24.9.0.tgz", @@ -26121,6 +27390,11 @@ "@types/yargs": "^13.0.0" } }, + "@microsoft/clarity": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@microsoft/clarity/-/clarity-1.0.2.tgz", + "integrity": "sha512-9EZYROFpJxEGmQpHvUFqvD3ZJ7QQSqnibYSWmS+1xusoZfG1QQ1/Al9yVBBc11DWMbJrs1pe1hLT273it/skJg==" + }, "@nicolo-ribaudo/chokidar-2": { "version": "2.1.8-no-fsevents.2", "resolved": "https://registry.npmjs.org/@nicolo-ribaudo/chokidar-2/-/chokidar-2-2.1.8-no-fsevents.2.tgz", @@ -26557,6 +27831,12 @@ "resolved": "https://registry.npmjs.org/@xtuc/long/-/long-4.2.2.tgz", "integrity": "sha512-NuHqBY1PB/D8xU6s/thBgOAiAP7HOYDQ32+BFZILJ8ivkUkAHQnWfn6WhL79Owj1qmUnoN/YPhktdIoucipkAQ==" }, + "@yarnpkg/lockfile": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@yarnpkg/lockfile/-/lockfile-1.1.0.tgz", + "integrity": "sha512-GpSwvyXOcOOlV70vbnzjj4fW5xW/FdUF6nQEt1ENy7m4ZCczi1+/buVUPAqmGfqznsORNFzUMjctTIp8a9tuCQ==", + "dev": true + }, "abab": { "version": "1.0.4", "resolved": "https://registry.npmjs.org/abab/-/abab-1.0.4.tgz", @@ -26875,23 +28155,6 @@ "is-symbol": "^1.0.2" } }, - "get-intrinsic": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.1.1.tgz", - "integrity": "sha512-kWZrnVM42QCiEA2Ig1bG8zjoIMOgxWwYCEeNdwY6Tv/cOSeGpcoX4pXHfKUxNKVoArnrEr2e9srnAxxGIraS9Q==", - "dev": true, - "requires": { - "function-bind": "^1.1.1", - "has": "^1.0.3", - "has-symbols": "^1.0.1" - } - }, - "has-symbols": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.2.tgz", - "integrity": "sha512-chXa79rL/UC2KlX17jo3vRGz0azaWEx5tGqZg5pO3NUyEJVB17dMruQlzCCOfUvElghKcm5194+BCRvi2Rv/Gw==", - "dev": true - }, "is-callable": { "version": "1.2.3", "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.3.tgz", @@ -27040,23 +28303,6 @@ "is-symbol": "^1.0.2" } }, - "get-intrinsic": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.1.1.tgz", - "integrity": "sha512-kWZrnVM42QCiEA2Ig1bG8zjoIMOgxWwYCEeNdwY6Tv/cOSeGpcoX4pXHfKUxNKVoArnrEr2e9srnAxxGIraS9Q==", - "dev": true, - "requires": { - "function-bind": "^1.1.1", - "has": "^1.0.3", - "has-symbols": "^1.0.1" - } - }, - "has-symbols": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.2.tgz", - "integrity": "sha512-chXa79rL/UC2KlX17jo3vRGz0azaWEx5tGqZg5pO3NUyEJVB17dMruQlzCCOfUvElghKcm5194+BCRvi2Rv/Gw==", - "dev": true - }, "is-callable": { "version": "1.2.3", "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.3.tgz", @@ -27222,6 +28468,11 @@ "resolved": "https://registry.npmjs.org/atob/-/atob-2.1.2.tgz", "integrity": "sha512-Wm6ukoaOGJi/73p/cl2GvLjTI5JM1k/O14isD73YML8StrH/7/lRFgmg8nICZgD3bZZvjwCGxtMOD3wWNAu8cg==" }, + "atob-lite": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/atob-lite/-/atob-lite-2.0.0.tgz", + "integrity": "sha512-LEeSAWeh2Gfa2FtlQE1shxQ8zi5F9GHarrGKz08TMdODD5T4eH6BMsvtnhbWZ+XQn+Gb6om/917ucvRu7l7ukw==" + }, "audio-context": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/audio-context/-/audio-context-1.0.1.tgz", @@ -27785,6 +29036,13 @@ "requires": { "core-js": "^2.4.0", "regenerator-runtime": "^0.11.0" + }, + "dependencies": { + "regenerator-runtime": { + "version": "0.11.1", + "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.11.1.tgz", + "integrity": "sha512-MguG95oij0fC3QV3URf4V2SDYGJhJnJGqvIIgdECeODCT98wSWDAJ94SSuVpYQUoTcGUIL6L4yNB7j1DFFHSBg==" + } } }, "babel-template": { @@ -28326,13 +29584,35 @@ } }, "call-bind": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.9.tgz", + "integrity": "sha512-a/hy+pNsFUTR+Iz8TCJvXudKVLAnz/DyeSUo10I5yvFDQJBFU2s9uqQpoSrJlroHUKoKqzg+epxyP9lqFdzfBQ==", + "dev": true, + "requires": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "get-intrinsic": "^1.3.0", + "set-function-length": "^1.2.2" + } + }, + "call-bind-apply-helpers": { "version": "1.0.2", - "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.2.tgz", - "integrity": "sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA==", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", "dev": true, "requires": { - "function-bind": "^1.1.1", - "get-intrinsic": "^1.0.2" + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + } + }, + "call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "dev": true, + "requires": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" } }, "caller-callsite": { @@ -28713,6 +29993,33 @@ "object-visit": "^1.0.0" } }, + "color": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/color/-/color-4.2.3.tgz", + "integrity": "sha512-1rXeuUUiGGrykh+CeBdu5Ie7OJwinCgQY0bc7GCRxy5xVHy+moaqkpL/jqQq0MtQOeYcrqEz4abc5f0KtU7W4A==", + "dev": true, + "requires": { + "color-convert": "^2.0.1", + "color-string": "^1.9.0" + }, + "dependencies": { + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + } + } + }, "color-convert": { "version": "1.9.3", "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", @@ -28726,6 +30033,16 @@ "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=" }, + "color-string": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/color-string/-/color-string-1.9.1.tgz", + "integrity": "sha512-shrVawQFojnZv6xM40anx4CkoDP+fZsw/ZerEMsW/pyzsRbElpsL/DBVW7q3ExxwusdNXI3lXpuhEZkzs8p5Eg==", + "dev": true, + "requires": { + "color-name": "^1.0.0", + "simple-swizzle": "^0.2.2" + } + }, "colorette": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/colorette/-/colorette-1.2.1.tgz", @@ -29133,6 +30450,59 @@ "sha.js": "^2.4.8" } }, + "cross-env": { + "version": "10.1.0", + "resolved": "https://registry.npmjs.org/cross-env/-/cross-env-10.1.0.tgz", + "integrity": "sha512-GsYosgnACZTADcmEyJctkJIoqAhHjttw7RsFrVoJNXbsWWqaq6Ym+7kZjq6mS45O0jij6vtiReppKQEtqWy6Dw==", + "dev": true, + "requires": { + "@epic-web/invariant": "^1.0.0", + "cross-spawn": "^7.0.6" + }, + "dependencies": { + "cross-spawn": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", + "dev": true, + "requires": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + } + }, + "path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "dev": true + }, + "shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "dev": true, + "requires": { + "shebang-regex": "^3.0.0" + } + }, + "shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "dev": true + }, + "which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "dev": true, + "requires": { + "isexe": "^2.0.0" + } + } + } + }, "cross-spawn": { "version": "6.0.5", "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-6.0.5.tgz", @@ -29164,6 +30534,11 @@ "randomfill": "^1.0.3" } }, + "crypto-js": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/crypto-js/-/crypto-js-4.2.0.tgz", + "integrity": "sha512-KALDyEYgpY+Rlob/iriUtjV6d5Eq+Y191A5g4UqLAi8CyGP9N1+FdVbkc1SxKc2r4YAYqG8JzO2KGL+AizD70Q==" + }, "css-loader": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/css-loader/-/css-loader-1.0.1.tgz", @@ -29559,6 +30934,17 @@ } } }, + "define-data-property": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.4.tgz", + "integrity": "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==", + "dev": true, + "requires": { + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "gopd": "^1.0.1" + } + }, "define-properties": { "version": "1.1.3", "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.1.3.tgz", @@ -29661,6 +31047,12 @@ "repeating": "^2.0.0" } }, + "detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "dev": true + }, "detect-node": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/detect-node/-/detect-node-2.0.4.tgz", @@ -29831,6 +31223,17 @@ } } }, + "dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "dev": true, + "requires": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + } + }, "duplexer2": { "version": "0.1.4", "resolved": "https://registry.npmjs.org/duplexer2/-/duplexer2-0.1.4.tgz", @@ -30049,6 +31452,27 @@ "string.prototype.trimright": "^2.1.0" } }, + "es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "dev": true + }, + "es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "dev": true + }, + "es-object-atoms": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz", + "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==", + "dev": true, + "requires": { + "es-errors": "^1.3.0" + } + }, "es-to-primitive": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/es-to-primitive/-/es-to-primitive-1.2.0.tgz", @@ -30425,287 +31849,253 @@ "is-symbol": "^1.0.2" } }, - "find-up": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-2.1.0.tgz", - "integrity": "sha1-RdG35QbHF93UgndaK3eSCjwMV6c=", - "dev": true, - "requires": { - "locate-path": "^2.0.0" - } - }, - "get-intrinsic": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.1.1.tgz", - "integrity": "sha512-kWZrnVM42QCiEA2Ig1bG8zjoIMOgxWwYCEeNdwY6Tv/cOSeGpcoX4pXHfKUxNKVoArnrEr2e9srnAxxGIraS9Q==", - "dev": true, - "requires": { - "function-bind": "^1.1.1", - "has": "^1.0.3", - "has-symbols": "^1.0.1" - } - }, - "has-symbols": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.2.tgz", - "integrity": "sha512-chXa79rL/UC2KlX17jo3vRGz0azaWEx5tGqZg5pO3NUyEJVB17dMruQlzCCOfUvElghKcm5194+BCRvi2Rv/Gw==", - "dev": true - }, - "is-callable": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.3.tgz", - "integrity": "sha512-J1DcMe8UYTBSrKezuIUTUwjXsho29693unXM2YhJUTR2txK/eG47bvNa/wipPFmZFgr/N6f1GA66dv0mEyTIyQ==", - "dev": true - }, - "is-regex": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.1.3.tgz", - "integrity": "sha512-qSVXFz28HM7y+IWX6vLCsexdlvzT1PJNFSBuaQLQ5o0IEw8UDYW6/2+eCMVyIsbM8CNLX2a/QWmSpyxYEHY7CQ==", - "dev": true, - "requires": { - "call-bind": "^1.0.2", - "has-symbols": "^1.0.2" - } - }, - "is-string": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/is-string/-/is-string-1.0.6.tgz", - "integrity": "sha512-2gdzbKUuqtQ3lYNrUTQYoClPhm7oQu4UdpSZMp1/DGgkHBT8E2Z1l0yMdb6D4zNAxwDiMv8MdulKROJGNl0Q0w==", - "dev": true - }, - "load-json-file": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/load-json-file/-/load-json-file-4.0.0.tgz", - "integrity": "sha1-L19Fq5HjMhYjT9U62rZo607AmTs=", - "dev": true, - "requires": { - "graceful-fs": "^4.1.2", - "parse-json": "^4.0.0", - "pify": "^3.0.0", - "strip-bom": "^3.0.0" - } - }, - "locate-path": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-2.0.0.tgz", - "integrity": "sha1-K1aLJl7slExtnA3pw9u7ygNUzY4=", - "dev": true, - "requires": { - "p-locate": "^2.0.0", - "path-exists": "^3.0.0" - } - }, - "object-inspect": { - "version": "1.10.3", - "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.10.3.tgz", - "integrity": "sha512-e5mCJlSH7poANfC8z8S9s9S2IN5/4Zb3aZ33f5s8YqoazCFzNLloLU8r5VCG+G7WoqLvAAZoVMcy3tp/3X0Plw==", - "dev": true - }, - "object.assign": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.2.tgz", - "integrity": "sha512-ixT2L5THXsApyiUPYKmW+2EHpXXe5Ii3M+f4e+aJFAHao5amFRW6J0OO6c/LU8Be47utCx2GL89hxGB6XSmKuQ==", - "dev": true, - "requires": { - "call-bind": "^1.0.0", - "define-properties": "^1.1.3", - "has-symbols": "^1.0.1", - "object-keys": "^1.1.1" - } - }, - "object.values": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/object.values/-/object.values-1.1.4.tgz", - "integrity": "sha512-TnGo7j4XSnKQoK3MfvkzqKCi0nVe/D9I9IjwTNYdb/fxYHpjrluHVOgw0AF6jrRFGMPHdfuidR09tIDiIvnaSg==", - "dev": true, - "requires": { - "call-bind": "^1.0.2", - "define-properties": "^1.1.3", - "es-abstract": "^1.18.2" - } - }, - "p-limit": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-1.3.0.tgz", - "integrity": "sha512-vvcXsLAJ9Dr5rQOPk7toZQZJApBl2K4J6dANSsEuh6QI41JYcsS/qhTGa9ErIUUgK3WNQoJYvylxvjqmiqEA9Q==", - "dev": true, - "requires": { - "p-try": "^1.0.0" - } - }, - "p-locate": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-2.0.0.tgz", - "integrity": "sha1-IKAQOyIqcMj9OcwuWAaA893l7EM=", - "dev": true, - "requires": { - "p-limit": "^1.1.0" - } - }, - "p-try": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/p-try/-/p-try-1.0.0.tgz", - "integrity": "sha1-y8ec26+P1CKOE/Yh8rGiN8GyB7M=", - "dev": true - }, - "parse-json": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-4.0.0.tgz", - "integrity": "sha1-vjX1Qlvh9/bHRxhPmKeIy5lHfuA=", - "dev": true, - "requires": { - "error-ex": "^1.3.1", - "json-parse-better-errors": "^1.0.1" - } - }, - "pify": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/pify/-/pify-3.0.0.tgz", - "integrity": "sha1-5aSs0sEB/fPZpNB/DbxNtJ3SgXY=", - "dev": true - }, - "read-pkg": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/read-pkg/-/read-pkg-3.0.0.tgz", - "integrity": "sha1-nLxoaXj+5l0WwA4rGcI3/Pbjg4k=", - "dev": true, - "requires": { - "load-json-file": "^4.0.0", - "normalize-package-data": "^2.3.2", - "path-type": "^3.0.0" - } - }, - "read-pkg-up": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/read-pkg-up/-/read-pkg-up-3.0.0.tgz", - "integrity": "sha1-PtSWaF26D4/hGNBpHcUfSh/5bwc=", - "dev": true, - "requires": { - "find-up": "^2.0.0", - "read-pkg": "^3.0.0" - } - }, - "resolve": { - "version": "1.20.0", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.20.0.tgz", - "integrity": "sha512-wENBPt4ySzg4ybFQW2TT1zMQucPK95HSh/nq2CFTZVOGut2+pQvSsgtda4d26YrYcr067wjbmzOG8byDPBX63A==", - "dev": true, - "requires": { - "is-core-module": "^2.2.0", - "path-parse": "^1.0.6" - } - }, - "string.prototype.trimend": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/string.prototype.trimend/-/string.prototype.trimend-1.0.4.tgz", - "integrity": "sha512-y9xCjw1P23Awk8EvTpcyL2NIr1j7wJ39f+k6lvRnSMz+mz9CGz9NYPelDk42kOz6+ql8xjfK8oYzy3jAP5QU5A==", - "dev": true, - "requires": { - "call-bind": "^1.0.2", - "define-properties": "^1.1.3" - } - }, - "string.prototype.trimstart": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/string.prototype.trimstart/-/string.prototype.trimstart-1.0.4.tgz", - "integrity": "sha512-jh6e984OBfvxS50tdY2nRZnoC5/mLFKOREQfw8t5yytkoUsJRNxvI/E39qu1sD0OtWI3OC0XgKSmcWwziwYuZw==", - "dev": true, - "requires": { - "call-bind": "^1.0.2", - "define-properties": "^1.1.3" - } - } - } - }, - "eslint-plugin-jest": { - "version": "22.17.0", - "resolved": "https://registry.npmjs.org/eslint-plugin-jest/-/eslint-plugin-jest-22.17.0.tgz", - "integrity": "sha512-WT4DP4RoGBhIQjv+5D0FM20fAdAUstfYAf/mkufLNTojsfgzc5/IYW22cIg/Q4QBavAZsROQlqppiWDpFZDS8Q==", - "dev": true, - "requires": { - "@typescript-eslint/experimental-utils": "^1.13.0" - } - }, - "eslint-plugin-react": { - "version": "7.24.0", - "resolved": "https://registry.npmjs.org/eslint-plugin-react/-/eslint-plugin-react-7.24.0.tgz", - "integrity": "sha512-KJJIx2SYx7PBx3ONe/mEeMz4YE0Lcr7feJTCMyyKb/341NcjuAgim3Acgan89GfPv7nxXK2+0slu0CWXYM4x+Q==", - "dev": true, - "requires": { - "array-includes": "^3.1.3", - "array.prototype.flatmap": "^1.2.4", - "doctrine": "^2.1.0", - "has": "^1.0.3", - "jsx-ast-utils": "^2.4.1 || ^3.0.0", - "minimatch": "^3.0.4", - "object.entries": "^1.1.4", - "object.fromentries": "^2.0.4", - "object.values": "^1.1.4", - "prop-types": "^15.7.2", - "resolve": "^2.0.0-next.3", - "string.prototype.matchall": "^4.0.5" - }, - "dependencies": { - "doctrine": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-2.1.0.tgz", - "integrity": "sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw==", - "dev": true, - "requires": { - "esutils": "^2.0.2" - } - }, - "es-abstract": { - "version": "1.18.3", - "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.18.3.tgz", - "integrity": "sha512-nQIr12dxV7SSxE6r6f1l3DtAeEYdsGpps13dR0TwJg1S8gyp4ZPgy3FZcHBgbiQqnoqSTb+oC+kO4UQ0C/J8vw==", - "dev": true, - "requires": { - "call-bind": "^1.0.2", - "es-to-primitive": "^1.2.1", - "function-bind": "^1.1.1", - "get-intrinsic": "^1.1.1", - "has": "^1.0.3", - "has-symbols": "^1.0.2", - "is-callable": "^1.2.3", - "is-negative-zero": "^2.0.1", - "is-regex": "^1.1.3", - "is-string": "^1.0.6", - "object-inspect": "^1.10.3", - "object-keys": "^1.1.1", - "object.assign": "^4.1.2", - "string.prototype.trimend": "^1.0.4", - "string.prototype.trimstart": "^1.0.4", - "unbox-primitive": "^1.0.1" - } - }, - "es-to-primitive": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/es-to-primitive/-/es-to-primitive-1.2.1.tgz", - "integrity": "sha512-QCOllgZJtaUo9miYBcLChTUaHNjJF3PYs1VidD7AwiEj1kYxKeQTctLAezAOH5ZKRH0g2IgPn6KwB4IT8iRpvA==", - "dev": true, - "requires": { - "is-callable": "^1.1.4", - "is-date-object": "^1.0.1", - "is-symbol": "^1.0.2" - } - }, - "get-intrinsic": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.1.1.tgz", - "integrity": "sha512-kWZrnVM42QCiEA2Ig1bG8zjoIMOgxWwYCEeNdwY6Tv/cOSeGpcoX4pXHfKUxNKVoArnrEr2e9srnAxxGIraS9Q==", + "find-up": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-2.1.0.tgz", + "integrity": "sha1-RdG35QbHF93UgndaK3eSCjwMV6c=", "dev": true, "requires": { + "locate-path": "^2.0.0" + } + }, + "is-callable": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.3.tgz", + "integrity": "sha512-J1DcMe8UYTBSrKezuIUTUwjXsho29693unXM2YhJUTR2txK/eG47bvNa/wipPFmZFgr/N6f1GA66dv0mEyTIyQ==", + "dev": true + }, + "is-regex": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.1.3.tgz", + "integrity": "sha512-qSVXFz28HM7y+IWX6vLCsexdlvzT1PJNFSBuaQLQ5o0IEw8UDYW6/2+eCMVyIsbM8CNLX2a/QWmSpyxYEHY7CQ==", + "dev": true, + "requires": { + "call-bind": "^1.0.2", + "has-symbols": "^1.0.2" + } + }, + "is-string": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/is-string/-/is-string-1.0.6.tgz", + "integrity": "sha512-2gdzbKUuqtQ3lYNrUTQYoClPhm7oQu4UdpSZMp1/DGgkHBT8E2Z1l0yMdb6D4zNAxwDiMv8MdulKROJGNl0Q0w==", + "dev": true + }, + "load-json-file": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/load-json-file/-/load-json-file-4.0.0.tgz", + "integrity": "sha1-L19Fq5HjMhYjT9U62rZo607AmTs=", + "dev": true, + "requires": { + "graceful-fs": "^4.1.2", + "parse-json": "^4.0.0", + "pify": "^3.0.0", + "strip-bom": "^3.0.0" + } + }, + "locate-path": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-2.0.0.tgz", + "integrity": "sha1-K1aLJl7slExtnA3pw9u7ygNUzY4=", + "dev": true, + "requires": { + "p-locate": "^2.0.0", + "path-exists": "^3.0.0" + } + }, + "object-inspect": { + "version": "1.10.3", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.10.3.tgz", + "integrity": "sha512-e5mCJlSH7poANfC8z8S9s9S2IN5/4Zb3aZ33f5s8YqoazCFzNLloLU8r5VCG+G7WoqLvAAZoVMcy3tp/3X0Plw==", + "dev": true + }, + "object.assign": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.2.tgz", + "integrity": "sha512-ixT2L5THXsApyiUPYKmW+2EHpXXe5Ii3M+f4e+aJFAHao5amFRW6J0OO6c/LU8Be47utCx2GL89hxGB6XSmKuQ==", + "dev": true, + "requires": { + "call-bind": "^1.0.0", + "define-properties": "^1.1.3", + "has-symbols": "^1.0.1", + "object-keys": "^1.1.1" + } + }, + "object.values": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/object.values/-/object.values-1.1.4.tgz", + "integrity": "sha512-TnGo7j4XSnKQoK3MfvkzqKCi0nVe/D9I9IjwTNYdb/fxYHpjrluHVOgw0AF6jrRFGMPHdfuidR09tIDiIvnaSg==", + "dev": true, + "requires": { + "call-bind": "^1.0.2", + "define-properties": "^1.1.3", + "es-abstract": "^1.18.2" + } + }, + "p-limit": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-1.3.0.tgz", + "integrity": "sha512-vvcXsLAJ9Dr5rQOPk7toZQZJApBl2K4J6dANSsEuh6QI41JYcsS/qhTGa9ErIUUgK3WNQoJYvylxvjqmiqEA9Q==", + "dev": true, + "requires": { + "p-try": "^1.0.0" + } + }, + "p-locate": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-2.0.0.tgz", + "integrity": "sha1-IKAQOyIqcMj9OcwuWAaA893l7EM=", + "dev": true, + "requires": { + "p-limit": "^1.1.0" + } + }, + "p-try": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/p-try/-/p-try-1.0.0.tgz", + "integrity": "sha1-y8ec26+P1CKOE/Yh8rGiN8GyB7M=", + "dev": true + }, + "parse-json": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-4.0.0.tgz", + "integrity": "sha1-vjX1Qlvh9/bHRxhPmKeIy5lHfuA=", + "dev": true, + "requires": { + "error-ex": "^1.3.1", + "json-parse-better-errors": "^1.0.1" + } + }, + "pify": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/pify/-/pify-3.0.0.tgz", + "integrity": "sha1-5aSs0sEB/fPZpNB/DbxNtJ3SgXY=", + "dev": true + }, + "read-pkg": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/read-pkg/-/read-pkg-3.0.0.tgz", + "integrity": "sha1-nLxoaXj+5l0WwA4rGcI3/Pbjg4k=", + "dev": true, + "requires": { + "load-json-file": "^4.0.0", + "normalize-package-data": "^2.3.2", + "path-type": "^3.0.0" + } + }, + "read-pkg-up": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/read-pkg-up/-/read-pkg-up-3.0.0.tgz", + "integrity": "sha1-PtSWaF26D4/hGNBpHcUfSh/5bwc=", + "dev": true, + "requires": { + "find-up": "^2.0.0", + "read-pkg": "^3.0.0" + } + }, + "resolve": { + "version": "1.20.0", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.20.0.tgz", + "integrity": "sha512-wENBPt4ySzg4ybFQW2TT1zMQucPK95HSh/nq2CFTZVOGut2+pQvSsgtda4d26YrYcr067wjbmzOG8byDPBX63A==", + "dev": true, + "requires": { + "is-core-module": "^2.2.0", + "path-parse": "^1.0.6" + } + }, + "string.prototype.trimend": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/string.prototype.trimend/-/string.prototype.trimend-1.0.4.tgz", + "integrity": "sha512-y9xCjw1P23Awk8EvTpcyL2NIr1j7wJ39f+k6lvRnSMz+mz9CGz9NYPelDk42kOz6+ql8xjfK8oYzy3jAP5QU5A==", + "dev": true, + "requires": { + "call-bind": "^1.0.2", + "define-properties": "^1.1.3" + } + }, + "string.prototype.trimstart": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/string.prototype.trimstart/-/string.prototype.trimstart-1.0.4.tgz", + "integrity": "sha512-jh6e984OBfvxS50tdY2nRZnoC5/mLFKOREQfw8t5yytkoUsJRNxvI/E39qu1sD0OtWI3OC0XgKSmcWwziwYuZw==", + "dev": true, + "requires": { + "call-bind": "^1.0.2", + "define-properties": "^1.1.3" + } + } + } + }, + "eslint-plugin-jest": { + "version": "22.17.0", + "resolved": "https://registry.npmjs.org/eslint-plugin-jest/-/eslint-plugin-jest-22.17.0.tgz", + "integrity": "sha512-WT4DP4RoGBhIQjv+5D0FM20fAdAUstfYAf/mkufLNTojsfgzc5/IYW22cIg/Q4QBavAZsROQlqppiWDpFZDS8Q==", + "dev": true, + "requires": { + "@typescript-eslint/experimental-utils": "^1.13.0" + } + }, + "eslint-plugin-react": { + "version": "7.24.0", + "resolved": "https://registry.npmjs.org/eslint-plugin-react/-/eslint-plugin-react-7.24.0.tgz", + "integrity": "sha512-KJJIx2SYx7PBx3ONe/mEeMz4YE0Lcr7feJTCMyyKb/341NcjuAgim3Acgan89GfPv7nxXK2+0slu0CWXYM4x+Q==", + "dev": true, + "requires": { + "array-includes": "^3.1.3", + "array.prototype.flatmap": "^1.2.4", + "doctrine": "^2.1.0", + "has": "^1.0.3", + "jsx-ast-utils": "^2.4.1 || ^3.0.0", + "minimatch": "^3.0.4", + "object.entries": "^1.1.4", + "object.fromentries": "^2.0.4", + "object.values": "^1.1.4", + "prop-types": "^15.7.2", + "resolve": "^2.0.0-next.3", + "string.prototype.matchall": "^4.0.5" + }, + "dependencies": { + "doctrine": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-2.1.0.tgz", + "integrity": "sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw==", + "dev": true, + "requires": { + "esutils": "^2.0.2" + } + }, + "es-abstract": { + "version": "1.18.3", + "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.18.3.tgz", + "integrity": "sha512-nQIr12dxV7SSxE6r6f1l3DtAeEYdsGpps13dR0TwJg1S8gyp4ZPgy3FZcHBgbiQqnoqSTb+oC+kO4UQ0C/J8vw==", + "dev": true, + "requires": { + "call-bind": "^1.0.2", + "es-to-primitive": "^1.2.1", "function-bind": "^1.1.1", + "get-intrinsic": "^1.1.1", "has": "^1.0.3", - "has-symbols": "^1.0.1" + "has-symbols": "^1.0.2", + "is-callable": "^1.2.3", + "is-negative-zero": "^2.0.1", + "is-regex": "^1.1.3", + "is-string": "^1.0.6", + "object-inspect": "^1.10.3", + "object-keys": "^1.1.1", + "object.assign": "^4.1.2", + "string.prototype.trimend": "^1.0.4", + "string.prototype.trimstart": "^1.0.4", + "unbox-primitive": "^1.0.1" } }, - "has-symbols": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.2.tgz", - "integrity": "sha512-chXa79rL/UC2KlX17jo3vRGz0azaWEx5tGqZg5pO3NUyEJVB17dMruQlzCCOfUvElghKcm5194+BCRvi2Rv/Gw==", - "dev": true + "es-to-primitive": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/es-to-primitive/-/es-to-primitive-1.2.1.tgz", + "integrity": "sha512-QCOllgZJtaUo9miYBcLChTUaHNjJF3PYs1VidD7AwiEj1kYxKeQTctLAezAOH5ZKRH0g2IgPn6KwB4IT8iRpvA==", + "dev": true, + "requires": { + "is-callable": "^1.1.4", + "is-date-object": "^1.0.1", + "is-symbol": "^1.0.2" + } }, "is-callable": { "version": "1.2.3", @@ -30853,6 +32243,28 @@ "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==" }, + "esptool-js": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/esptool-js/-/esptool-js-0.5.7.tgz", + "integrity": "sha512-k3pkXU9OTySCd58OUDjuJWNnFjM+QpPWAghxyWPm3zNfaLiP4ex2jNd7Rj0jWPu3/fgvwau236tetsTZrh4x5g==", + "requires": { + "atob-lite": "^2.0.0", + "pako": "^2.1.0", + "tslib": "^2.4.1" + }, + "dependencies": { + "pako": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/pako/-/pako-2.2.0.tgz", + "integrity": "sha512-zJq6RP/5q+TO2OpFV3FHzlPnFjmkb7Nc99a5SNjJE+uu/PkpChs+NIZSSzbBoD+6kjiISXjfYdwj1ZRQ81dz/w==" + }, + "tslib": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==" + } + } + }, "esquery": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.0.1.tgz", @@ -31416,12 +32828,6 @@ "picomatch": "^2.2.3" } }, - "picomatch": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.0.tgz", - "integrity": "sha512-lY1Q/PiJGC2zOv/z391WOTD+Z02bCgsFfvxoXXf6h7kv9o+WmsmzYqrAwY63sNgOxE4xEdq0WyUnXfKeBrSvYw==", - "dev": true - }, "to-regex-range": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", @@ -31639,6 +33045,60 @@ "locate-path": "^3.0.0" } }, + "find-yarn-workspace-root": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/find-yarn-workspace-root/-/find-yarn-workspace-root-2.0.0.tgz", + "integrity": "sha512-1IMnbjt4KzsQfnhnzNd8wUEgXZ44IzZaZmnLYx7D5FZlaHt2gW20Cri8Q+E/t5tIj4+epTBub+2Zxu/vNILzqQ==", + "dev": true, + "requires": { + "micromatch": "^4.0.2" + }, + "dependencies": { + "braces": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", + "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", + "dev": true, + "requires": { + "fill-range": "^7.1.1" + } + }, + "fill-range": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", + "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", + "dev": true, + "requires": { + "to-regex-range": "^5.0.1" + } + }, + "is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "dev": true + }, + "micromatch": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", + "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", + "dev": true, + "requires": { + "braces": "^3.0.3", + "picomatch": "^2.3.1" + } + }, + "to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "dev": true, + "requires": { + "is-number": "^7.0.0" + } + } + } + }, "findup": { "version": "0.1.5", "resolved": "https://registry.npmjs.org/findup/-/findup-0.1.5.tgz", @@ -32399,9 +33859,9 @@ } }, "function-bind": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", - "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==" + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==" }, "function.prototype.name": { "version": "1.1.1", @@ -32444,22 +33904,31 @@ "integrity": "sha1-XYVZJKQwOITJY4qrEnzOTQBlljs=" }, "get-intrinsic": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.0.2.tgz", - "integrity": "sha512-aeX0vrFm21ILl3+JpFFRNe9aUvp6VFZb2/CTbgLb8j75kOhvoNYjt9d8KA/tJG4gSo8nzEDedRl0h7vDmBYRVg==", + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", "dev": true, "requires": { - "function-bind": "^1.1.1", - "has": "^1.0.3", - "has-symbols": "^1.0.1" - }, - "dependencies": { - "has-symbols": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.1.tgz", - "integrity": "sha512-PLcsoqu++dmEIZB+6totNFKq/7Do+Z0u4oT0zKOJNl3lYK6vGwwu2hjHs+68OEZbTjiUE9bgOABXbP/GvrS0Kg==", - "dev": true - } + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + } + }, + "get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "dev": true, + "requires": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" } }, "get-stream": { @@ -32631,6 +34100,12 @@ "resolved": "https://registry.npmjs.org/google-closure-library/-/google-closure-library-20190301.0.0.tgz", "integrity": "sha512-mpeszbnXpRhXZ0sPqUxBgUmk0RtmzrJRy3KFygp0Ih9JuRUjQTCLhwYQeIlK2vB2lShhY/KUo9E1Z1gvxDFxOQ==" }, + "gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "dev": true + }, "got": { "version": "8.3.2", "resolved": "https://registry.npmjs.org/got/-/got-8.3.2.tgz", @@ -32763,15 +34238,24 @@ "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=" }, + "has-property-descriptors": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.2.tgz", + "integrity": "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==", + "dev": true, + "requires": { + "es-define-property": "^1.0.0" + } + }, "has-symbol-support-x": { "version": "1.4.2", "resolved": "https://registry.npmjs.org/has-symbol-support-x/-/has-symbol-support-x-1.4.2.tgz", "integrity": "sha512-3ToOva++HaW+eCpgqZrCfN51IPB+7bJNVT6CUATzueB5Heb8o6Nam0V3HG5dlDvZU1Gn5QLcbahiKw/XVk5JJw==" }, "has-symbols": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.0.tgz", - "integrity": "sha1-uhqPGvKg/DllD1yFA2dwQSIGO0Q=" + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==" }, "has-to-string-tag-x": { "version": "1.4.1", @@ -32828,6 +34312,15 @@ "minimalistic-assert": "^1.0.1" } }, + "hasown": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", + "dev": true, + "requires": { + "function-bind": "^1.1.2" + } + }, "he": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/he/-/he-1.2.0.tgz", @@ -33368,25 +34861,6 @@ "get-intrinsic": "^1.1.0", "has": "^1.0.3", "side-channel": "^1.0.4" - }, - "dependencies": { - "get-intrinsic": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.1.1.tgz", - "integrity": "sha512-kWZrnVM42QCiEA2Ig1bG8zjoIMOgxWwYCEeNdwY6Tv/cOSeGpcoX4pXHfKUxNKVoArnrEr2e9srnAxxGIraS9Q==", - "dev": true, - "requires": { - "function-bind": "^1.1.1", - "has": "^1.0.3", - "has-symbols": "^1.0.1" - } - }, - "has-symbols": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.2.tgz", - "integrity": "sha512-chXa79rL/UC2KlX17jo3vRGz0azaWEx5tGqZg5pO3NUyEJVB17dMruQlzCCOfUvElghKcm5194+BCRvi2Rv/Gw==", - "dev": true - } } }, "interpret": { @@ -33608,6 +35082,12 @@ "resolved": "https://registry.npmjs.org/is-directory/-/is-directory-0.3.1.tgz", "integrity": "sha1-YTObbyR1/Hcv2cnYP1yFddwVSuE=" }, + "is-docker": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/is-docker/-/is-docker-2.2.1.tgz", + "integrity": "sha512-F+i2BKsFrH66iaUFc0woD8sLy8getkwTwtOBjvs56Cx4CgJDeKQeqfz8wAYiSb8JOprWhHH5p77PbmYCvvUuXQ==", + "dev": true + }, "is-dotfile": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/is-dotfile/-/is-dotfile-1.0.3.tgz", @@ -34927,6 +36407,11 @@ "pretty-format": "^21.2.1" } }, + "jose": { + "version": "6.2.12", + "resolved": "https://registry.npmjs.org/jose/-/jose-6.2.12.tgz", + "integrity": "sha512-9NiFmJEex0sy2Dk58j2UGBSHgUs2ypF9eZSu4L6vjOX3Dp96Sw1F3uL+H+D1sx02jZZdzUT0HgvCy59CuvXcWw==" + }, "js-base64": { "version": "2.4.9", "resolved": "https://registry.npmjs.org/js-base64/-/js-base64-2.4.9.tgz", @@ -35030,12 +36515,24 @@ "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==" }, "json-stable-stringify": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/json-stable-stringify/-/json-stable-stringify-1.0.1.tgz", - "integrity": "sha1-mnWdOcXy/1A/1TAGRu1EX4jE+a8=", + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/json-stable-stringify/-/json-stable-stringify-1.3.0.tgz", + "integrity": "sha512-qtYiSSFlwot9XHtF9bD9c7rwKjr+RecWT//ZnPvSmEjpV5mmPOCN4j8UjY5hbjNkOwZ/jQv3J6R1/pL7RwgMsg==", "dev": true, "requires": { - "jsonify": "~0.0.0" + "call-bind": "^1.0.8", + "call-bound": "^1.0.4", + "isarray": "^2.0.5", + "jsonify": "^0.0.1", + "object-keys": "^1.1.1" + }, + "dependencies": { + "isarray": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-2.0.5.tgz", + "integrity": "sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw==", + "dev": true + } } }, "json-stable-stringify-without-jsonify": { @@ -35080,9 +36577,9 @@ } }, "jsonify": { - "version": "0.0.0", - "resolved": "https://registry.npmjs.org/jsonify/-/jsonify-0.0.0.tgz", - "integrity": "sha1-LHS27kHZPKUbe1qu6PUDYx0lKnM=", + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/jsonify/-/jsonify-0.0.1.tgz", + "integrity": "sha512-2/Ki0GcmuqSrgFyelQq9M05y7PS0mEwuIzrf3f1fPqkVDVRvZrPZtVSMHxdgo8Aq0sxAOb/cr2aqqA3LeWHVPg==", "dev": true }, "jsprim": { @@ -35107,12 +36604,6 @@ "object.assign": "^4.1.2" }, "dependencies": { - "has-symbols": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.2.tgz", - "integrity": "sha512-chXa79rL/UC2KlX17jo3vRGz0azaWEx5tGqZg5pO3NUyEJVB17dMruQlzCCOfUvElghKcm5194+BCRvi2Rv/Gw==", - "dev": true - }, "object.assign": { "version": "4.1.2", "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.2.tgz", @@ -35162,6 +36653,15 @@ "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.2.tgz", "integrity": "sha512-s5kLOcnH0XqDO+FvuaLX8DDjZ18CGFk7VygH40QoKPUQhW4e2rvM0rwUq0t8IQDOwYSeLK01U90OjzBTme2QqA==" }, + "klaw-sync": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/klaw-sync/-/klaw-sync-6.0.0.tgz", + "integrity": "sha512-nIeuVSzdCCs6TDPTqI8w1Yre34sSq7AkZ4B3sfOBbI2CgVSB4Du4aLQijFU2+lhAFCwt9+42Hel6lQNIv6AntQ==", + "dev": true, + "requires": { + "graceful-fs": "^4.1.11" + } + }, "lcid": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/lcid/-/lcid-1.0.0.tgz", @@ -35452,6 +36952,12 @@ "css-mediaquery": "^0.1.2" } }, + "math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "dev": true + }, "math-random": { "version": "1.0.4", "resolved": "https://registry.npmjs.org/math-random/-/math-random-1.0.4.tgz", @@ -36145,6 +37651,27 @@ "mimic-fn": "^1.0.0" } }, + "open": { + "version": "7.4.2", + "resolved": "https://registry.npmjs.org/open/-/open-7.4.2.tgz", + "integrity": "sha512-MVHddDVweXZF3awtlAS+6pgKLlm/JgxZ90+/NBurBoQctVOOB/zDdVjcyPzQ+0laDGbsWgrRkflI65sQeOgT9Q==", + "dev": true, + "requires": { + "is-docker": "^2.0.0", + "is-wsl": "^2.1.1" + }, + "dependencies": { + "is-wsl": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/is-wsl/-/is-wsl-2.2.0.tgz", + "integrity": "sha512-fKzAra0rGJUUBwGBgNkHZuToZcn+TtXHpeCgmkMJMMYx1sQDYaCSyjJBSCa2nH1DGm7s3n1oBnohoVTBaN7Lww==", + "dev": true, + "requires": { + "is-docker": "^2.0.0" + } + } + } + }, "openblock-blocks": { "version": "0.1.0-prerelease.20250611095335", "resolved": "https://registry.npmjs.org/openblock-blocks/-/openblock-blocks-0.1.0-prerelease.20250611095335.tgz", @@ -36537,6 +38064,171 @@ "resolved": "https://registry.npmjs.org/pascalcase/-/pascalcase-0.1.1.tgz", "integrity": "sha1-s2PlXoAGym/iF4TS2yK9FdeRfxQ=" }, + "patch-package": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/patch-package/-/patch-package-8.0.1.tgz", + "integrity": "sha512-VsKRIA8f5uqHQ7NGhwIna6Bx6D9s/1iXlA1hthBVBEbkq+t4kXD0HHt+rJhf/Z+Ci0F/HCB2hvn0qLdLG+Qxlw==", + "dev": true, + "requires": { + "@yarnpkg/lockfile": "^1.1.0", + "chalk": "^4.1.2", + "ci-info": "^3.7.0", + "cross-spawn": "^7.0.3", + "find-yarn-workspace-root": "^2.0.0", + "fs-extra": "^10.0.0", + "json-stable-stringify": "^1.0.2", + "klaw-sync": "^6.0.0", + "minimist": "^1.2.6", + "open": "^7.4.2", + "semver": "^7.5.3", + "slash": "^2.0.0", + "tmp": "^0.2.4", + "yaml": "^2.2.2" + }, + "dependencies": { + "ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "requires": { + "color-convert": "^2.0.1" + } + }, + "chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dev": true, + "requires": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + } + }, + "ci-info": { + "version": "3.9.0", + "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-3.9.0.tgz", + "integrity": "sha512-NIxF55hv4nSqQswkAeiOi1r83xy8JldOFDTWiug55KBu9Jnblncd2U6ViHmYgHf01TPZS77NJBhBMKdWj9HQMQ==", + "dev": true + }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "cross-spawn": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", + "dev": true, + "requires": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + } + }, + "fs-extra": { + "version": "10.1.0", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-10.1.0.tgz", + "integrity": "sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ==", + "dev": true, + "requires": { + "graceful-fs": "^4.2.0", + "jsonfile": "^6.0.1", + "universalify": "^2.0.0" + } + }, + "has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true + }, + "jsonfile": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.1.tgz", + "integrity": "sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q==", + "dev": true, + "requires": { + "graceful-fs": "^4.1.6", + "universalify": "^2.0.0" + } + }, + "minimist": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", + "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", + "dev": true + }, + "path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "dev": true + }, + "semver": { + "version": "7.8.5", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", + "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "dev": true + }, + "shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "dev": true, + "requires": { + "shebang-regex": "^3.0.0" + } + }, + "shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "dev": true + }, + "supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "requires": { + "has-flag": "^4.0.0" + } + }, + "tmp": { + "version": "0.2.7", + "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.2.7.tgz", + "integrity": "sha512-e0votIpp4Uo2AJYSzVHV6xCcawuiez3DzqDAbrTc3YxBkplN6e+dM13ZeIcZnDg/QpSuU2zfZ3rzwY8ukEnaXw==", + "dev": true + }, + "universalify": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz", + "integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==", + "dev": true + }, + "which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "dev": true, + "requires": { + "isexe": "^2.0.0" + } + } + } + }, "path-browserify": { "version": "0.0.1", "resolved": "https://registry.npmjs.org/path-browserify/-/path-browserify-0.0.1.tgz", @@ -36620,10 +38312,10 @@ "dev": true }, "picomatch": { - "version": "2.2.2", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.2.2.tgz", - "integrity": "sha512-q0M/9eZHzmr0AulXyPwNfZjtwZ/RBZlbN3K3CErVrk50T2ASYI7Bye0EvekFY3IP1Nt2DHu0re+V2ZHIpMkuWg==", - "optional": true + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz", + "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==", + "devOptional": true }, "pify": { "version": "4.0.1", @@ -37110,6 +38802,11 @@ "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.1.1.tgz", "integrity": "sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==" }, + "qrcode-generator": { + "version": "1.5.2", + "resolved": "https://registry.npmjs.org/qrcode-generator/-/qrcode-generator-1.5.2.tgz", + "integrity": "sha512-pItrW0Z9HnDBnFmgiNrY1uxRdri32Uh9EjNYLPVC2zZ3ZRIIEqBoDgm4DkvDwNNDHTK7FNkmr8zAa77BYc9xNw==" + }, "qs": { "version": "6.5.2", "resolved": "https://registry.npmjs.org/qs/-/qs-6.5.2.tgz", @@ -37667,9 +39364,9 @@ } }, "regenerator-runtime": { - "version": "0.11.1", - "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.11.1.tgz", - "integrity": "sha512-MguG95oij0fC3QV3URf4V2SDYGJhJnJGqvIIgdECeODCT98wSWDAJ94SSuVpYQUoTcGUIL6L4yNB7j1DFFHSBg==" + "version": "0.13.11", + "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.13.11.tgz", + "integrity": "sha512-kY1AZVr2Ra+t+piVaJ4gxaFaReZVH40AKNo7UCX6W+dEwBo/2oZJzqfuN1qLq1oL45o56cPaTXELwrTh8Fpggg==" }, "regenerator-transform": { "version": "0.14.5", @@ -37688,12 +39385,6 @@ "requires": { "regenerator-runtime": "^0.13.4" } - }, - "regenerator-runtime": { - "version": "0.13.7", - "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.13.7.tgz", - "integrity": "sha512-a54FxoJDIr27pgf7IgeQGxmqUNYrcV338lf/6gH456HZ/PhX+5BcwHXG9ajESmwe6WRO0tAzRUrRmNONWgkrew==", - "dev": true } } }, @@ -37755,12 +39446,6 @@ "is-symbol": "^1.0.2" } }, - "has-symbols": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.1.tgz", - "integrity": "sha512-PLcsoqu++dmEIZB+6totNFKq/7Do+Z0u4oT0zKOJNl3lYK6vGwwu2hjHs+68OEZbTjiUE9bgOABXbP/GvrS0Kg==", - "dev": true - }, "is-callable": { "version": "1.1.5", "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.1.5.tgz", @@ -38509,6 +40194,20 @@ "integrity": "sha1-BF+XgtARrppoA93TgrJDkrPYkPc=", "dev": true }, + "set-function-length": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.2.tgz", + "integrity": "sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==", + "dev": true, + "requires": { + "define-data-property": "^1.1.4", + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "get-intrinsic": "^1.2.4", + "gopd": "^1.0.1", + "has-property-descriptors": "^1.0.2" + } + }, "set-immediate-shim": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/set-immediate-shim/-/set-immediate-shim-1.0.1.tgz", @@ -38560,6 +40259,44 @@ "resolved": "https://registry.npmjs.org/shallow-copy/-/shallow-copy-0.0.1.tgz", "integrity": "sha1-QV9CcC1z2BAzApLMXuhurhoRoXA=" }, + "sharp": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.33.5.tgz", + "integrity": "sha512-haPVm1EkS9pgvHrQ/F3Xy+hgcuMV0Wm9vfIBSiwZ05k+xgb0PkBQpGsAA/oWdDobNaZTH5ppvHtzCFbnSEwHVw==", + "dev": true, + "requires": { + "@img/sharp-darwin-arm64": "0.33.5", + "@img/sharp-darwin-x64": "0.33.5", + "@img/sharp-libvips-darwin-arm64": "1.0.4", + "@img/sharp-libvips-darwin-x64": "1.0.4", + "@img/sharp-libvips-linux-arm": "1.0.5", + "@img/sharp-libvips-linux-arm64": "1.0.4", + "@img/sharp-libvips-linux-s390x": "1.0.4", + "@img/sharp-libvips-linux-x64": "1.0.4", + "@img/sharp-libvips-linuxmusl-arm64": "1.0.4", + "@img/sharp-libvips-linuxmusl-x64": "1.0.4", + "@img/sharp-linux-arm": "0.33.5", + "@img/sharp-linux-arm64": "0.33.5", + "@img/sharp-linux-s390x": "0.33.5", + "@img/sharp-linux-x64": "0.33.5", + "@img/sharp-linuxmusl-arm64": "0.33.5", + "@img/sharp-linuxmusl-x64": "0.33.5", + "@img/sharp-wasm32": "0.33.5", + "@img/sharp-win32-ia32": "0.33.5", + "@img/sharp-win32-x64": "0.33.5", + "color": "^4.2.3", + "detect-libc": "^2.0.3", + "semver": "^7.6.3" + }, + "dependencies": { + "semver": { + "version": "7.8.5", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", + "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "dev": true + } + } + }, "shebang-command": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-1.2.0.tgz", @@ -38606,6 +40343,23 @@ "integrity": "sha1-tf3AjxKH6hF4Yo5BXiUTK3NkbG0=", "dev": true }, + "simple-swizzle": { + "version": "0.2.4", + "resolved": "https://registry.npmjs.org/simple-swizzle/-/simple-swizzle-0.2.4.tgz", + "integrity": "sha512-nAu1WFPQSMNr2Zn9PGSZK9AGn4t/y97lEm+MXTtUDwfP0ksAIX4nO+6ruD9Jwut4C49SB1Ws+fbXsm/yScWOHw==", + "dev": true, + "requires": { + "is-arrayish": "^0.3.1" + }, + "dependencies": { + "is-arrayish": { + "version": "0.3.4", + "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.3.4.tgz", + "integrity": "sha512-m6UrgzFVUYawGBh1dUsWR5M2Clqic9RVXC/9f8ceNlv2IcO9j9J/z8UoCLPqtsPBFNzEpfR3xftohbfqDx8EQA==", + "dev": true + } + } + }, "slash": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/slash/-/slash-2.0.0.tgz", @@ -39211,23 +40965,6 @@ "is-symbol": "^1.0.2" } }, - "get-intrinsic": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.1.1.tgz", - "integrity": "sha512-kWZrnVM42QCiEA2Ig1bG8zjoIMOgxWwYCEeNdwY6Tv/cOSeGpcoX4pXHfKUxNKVoArnrEr2e9srnAxxGIraS9Q==", - "dev": true, - "requires": { - "function-bind": "^1.1.1", - "has": "^1.0.3", - "has-symbols": "^1.0.1" - } - }, - "has-symbols": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.2.tgz", - "integrity": "sha512-chXa79rL/UC2KlX17jo3vRGz0azaWEx5tGqZg5pO3NUyEJVB17dMruQlzCCOfUvElghKcm5194+BCRvi2Rv/Gw==", - "dev": true - }, "is-callable": { "version": "1.2.3", "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.3.tgz", @@ -39350,12 +41087,6 @@ "is-symbol": "^1.0.2" } }, - "has-symbols": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.1.tgz", - "integrity": "sha512-PLcsoqu++dmEIZB+6totNFKq/7Do+Z0u4oT0zKOJNl3lYK6vGwwu2hjHs+68OEZbTjiUE9bgOABXbP/GvrS0Kg==", - "dev": true - }, "is-callable": { "version": "1.1.5", "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.1.5.tgz", @@ -39459,12 +41190,6 @@ "is-symbol": "^1.0.2" } }, - "has-symbols": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.1.tgz", - "integrity": "sha512-PLcsoqu++dmEIZB+6totNFKq/7Do+Z0u4oT0zKOJNl3lYK6vGwwu2hjHs+68OEZbTjiUE9bgOABXbP/GvrS0Kg==", - "dev": true - }, "is-callable": { "version": "1.1.5", "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.1.5.tgz", @@ -40018,6 +41743,11 @@ "integrity": "sha1-f17oI66AUgfACvLfSoTsP8+lcLQ=", "dev": true }, + "three": { + "version": "0.186.1", + "resolved": "https://registry.npmjs.org/three/-/three-0.186.1.tgz", + "integrity": "sha512-blFeqb49wRCSGUGj7gtpfnSGHy2lwDk94RhUmS1c/hTby70kvChbWpkJ4Pm1390LqzzvTmzgXKHPEafJwCb8jA==" + }, "throat": { "version": "4.1.0", "resolved": "https://registry.npmjs.org/throat/-/throat-4.1.0.tgz", @@ -40434,14 +42164,6 @@ "has-bigints": "^1.0.1", "has-symbols": "^1.0.2", "which-boxed-primitive": "^1.0.2" - }, - "dependencies": { - "has-symbols": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.2.tgz", - "integrity": "sha512-chXa79rL/UC2KlX17jo3vRGz0azaWEx5tGqZg5pO3NUyEJVB17dMruQlzCCOfUvElghKcm5194+BCRvi2Rv/Gw==", - "dev": true - } } }, "unbzip2-stream": { @@ -41547,12 +43269,6 @@ "is-symbol": "^1.0.3" }, "dependencies": { - "has-symbols": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.2.tgz", - "integrity": "sha512-chXa79rL/UC2KlX17jo3vRGz0azaWEx5tGqZg5pO3NUyEJVB17dMruQlzCCOfUvElghKcm5194+BCRvi2Rv/Gw==", - "dev": true - }, "is-boolean-object": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/is-boolean-object/-/is-boolean-object-1.1.1.tgz", @@ -41772,6 +43488,12 @@ "resolved": "https://registry.npmjs.org/yallist/-/yallist-2.1.2.tgz", "integrity": "sha1-HBH5IY8HYImkfdUS+TxmmaaoHVI=" }, + "yaml": { + "version": "2.9.0", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.0.tgz", + "integrity": "sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA==", + "dev": true + }, "yargs": { "version": "9.0.1", "resolved": "https://registry.npmjs.org/yargs/-/yargs-9.0.1.tgz", diff --git a/package.json b/package.json index 4e7c06ec5ef..34f3185baf0 100644 --- a/package.json +++ b/package.json @@ -1,22 +1,26 @@ { "name": "openblock-gui", "version": "0.1.0", - "description": "GraphicaL User Interface for creating and running OpenBlock projects", + "description": "Graphical user interface for creating and running TinkerBit projects", "main": "./main/scratch-gui.js", "scripts": { - "build": "npm run clean && webpack --colors --bail", + "build": "npm run clean && npm run site-assets && cross-env NODE_ENV=production NODE_OPTIONS=--openssl-legacy-provider webpack --colors --bail", + "site-assets": "node scripts/build-site-assets.js", + "prestart": "npm run site-assets", "clean": "rimraf ./build && mkdirp build", "deploy": "touch build/.nojekyll && gh-pages -t -d build -m \"Build for $(git log --pretty=format:%H -n1) [skip ci]\"", "prune": "./prune-gh-pages.sh", "i18n:push": "tx-push-src openblock-editor interface translations/en.json", "i18n:src": "rimraf ./translations/messages/src && babel src > tmp.js && rimraf tmp.js && build-i18n-src ./translations/messages/src ./translations/", - "start": "webpack-dev-server --open --host 127.0.0.1", + "start": "cross-env NODE_OPTIONS=--openssl-legacy-provider webpack-dev-server --open --host 127.0.0.1", + "postinstall": "patch-package", "test": "npm run test:lint && npm run test:unit && npm run build && npm run test:integration", "test:integration": "jest --runInBand test[\\\\/]integration", "test:lint": "eslint . --ext .js,.jsx --fix", "test:unit": "", "test:smoke": "jest --runInBand test[\\\\/]smoke", - "watch": "webpack --colors --watch" + "check:templates": "node scripts/check-templates.js && node scripts/check-kit-projects.js", + "watch": "cross-env NODE_OPTIONS=--openssl-legacy-provider webpack --colors --watch" }, "author": "Massachusetts Institute of Technology", "license": "BSD-3-Clause", @@ -26,6 +30,7 @@ "url": "git+ssh://git@github.com/openblockcc/openblock-gui.git" }, "dependencies": { + "@microsoft/clarity": "^1.0.2", "@ramonak/react-progress-bar": "^3.1.0", "ansi-to-react": "^6.0.8", "arraybuffer-loader": "^1.0.6", @@ -36,15 +41,18 @@ "computed-style-to-inline-style": "3.0.0", "copy-webpack-plugin": "^4.5.1", "core-js": "2.5.7", + "crypto-js": "^4.2.0", "css-loader": "^1.0.0", "enzyme": "^3.5.0", "enzyme-adapter-react-16": "1.3.0", "es6-object-assign": "1.1.0", + "esptool-js": "^0.5.7", "file-loader": "2.0.0", "get-float-time-domain-data": "0.1.0", "get-user-media-promise": "1.1.4", "immutable": "3.8.2", "intl": "1.2.5", + "jose": "^6.2.12", "js-base64": "2.4.9", "keymirror": "0.1.1", "lodash.bindall": "4.4.0", @@ -64,6 +72,7 @@ "postcss-loader": "^3.0.0", "postcss-simple-vars": "^5.0.1", "prop-types": "^15.5.10", + "qrcode-generator": "^1.5.2", "query-string": "^5.1.1", "raw-loader": "^0.5.1", "react": "^16.0.0", @@ -85,6 +94,7 @@ "react-virtualized": "9.20.1", "redux": "3.7.2", "redux-throttle": "0.1.1", + "regenerator-runtime": "^0.13.11", "scratch-audio": "0.1.0-prerelease.20200528195344", "scratch-paint": "0.2.0-prerelease.20211027080909", "scratch-render": "0.1.0-prerelease.20211028200436", @@ -94,6 +104,7 @@ "startaudiocontext": "1.2.1", "style-loader": "^0.23.0", "text-encoding": "0.7.0", + "three": "0.186.1", "to-style": "1.3.3", "wav-encoder": "1.3.0", "xhr": "2.5.0" @@ -105,7 +116,15 @@ "devDependencies": { "@babel/cli": "7.14.8", "@babel/core": "7.14.8", + "@babel/plugin-proposal-class-properties": "7.14.5", + "@babel/plugin-proposal-class-static-block": "7.14.5", + "@babel/plugin-proposal-logical-assignment-operators": "7.14.5", + "@babel/plugin-proposal-nullish-coalescing-operator": "7.14.5", + "@babel/plugin-proposal-numeric-separator": "7.14.5", "@babel/plugin-proposal-object-rest-spread": "7.14.7", + "@babel/plugin-proposal-optional-chaining": "7.14.5", + "@babel/plugin-proposal-private-methods": "7.14.5", + "@babel/plugin-proposal-private-property-in-object": "7.14.5", "@babel/plugin-syntax-dynamic-import": "7.2.0", "@babel/plugin-transform-async-to-generator": "7.14.5", "@babel/preset-env": "7.14.8", @@ -114,6 +133,7 @@ "babel-eslint": "10.0.3", "babel-loader": "8.2.2", "chromedriver": "^96.0.0", + "cross-env": "^10.1.0", "enzyme": "3.10.0", "enzyme-adapter-react-16": "1.3.0", "eslint": "5.16.0", @@ -127,11 +147,14 @@ "jest-junit": "7.0.0", "mkdirp": "1.0.3", "monaco-editor-webpack-plugin": "^1.7.0", + "patch-package": "^8.0.1", "raf": "3.4.1", "react-test-renderer": "16.2.0", "redux-mock-store": "1.5.3", "rimraf": "2.7.1", "selenium-webdriver": "3.6.0", + "sharp": "^0.33.5", + "terser-webpack-plugin": "1.4.5", "uglifyjs-webpack-plugin": "1.3.0", "web-audio-test-api": "0.5.2", "webpack": "4.46.0", diff --git a/patches/openblock-vm+0.2.0-prerelease.20250609145235.patch b/patches/openblock-vm+0.2.0-prerelease.20250609145235.patch new file mode 100644 index 00000000000..8a646f461af --- /dev/null +++ b/patches/openblock-vm+0.2.0-prerelease.20250609145235.patch @@ -0,0 +1,76 @@ +diff --git a/node_modules/openblock-vm/src/devices/arduinoUno/arduinoUno.js b/node_modules/openblock-vm/src/devices/arduinoUno/arduinoUno.js +index 157a595..d4e7868 100644 +--- a/node_modules/openblock-vm/src/devices/arduinoUno/arduinoUno.js ++++ b/node_modules/openblock-vm/src/devices/arduinoUno/arduinoUno.js +@@ -946,6 +946,54 @@ class OpenBlockArduinoUnoDevice { + this._peripheral.setServoOutput(args.PIN, args.OUT); + return Promise.resolve(); + } ++ ++ /** ++ * Upload-mode-only blocks: used for codegen, not realtime VM execution. ++ * Stubs silence registration warnings when methods are missing. ++ */ ++ attachInterrupt () { ++ return Promise.resolve(); ++ } ++ detachInterrupt () { ++ return Promise.resolve(); ++ } ++ serialBegin () { ++ return Promise.resolve(); ++ } ++ serialPrint () { ++ return Promise.resolve(); ++ } ++ serialAvailable () { ++ return Promise.resolve(0); ++ } ++ serialReadAByte () { ++ return Promise.resolve(0); ++ } ++ dataMap (args) { ++ const value = Number(args.DATA); ++ const fromLow = Number(args.ARG0); ++ const fromHigh = Number(args.ARG1); ++ const toLow = Number(args.ARG2); ++ const toHigh = Number(args.ARG3); ++ if (fromHigh === fromLow) return toLow; ++ return (value - fromLow) * (toHigh - toLow) / (fromHigh - fromLow) + toLow; ++ } ++ dataConstrain (args) { ++ const value = Number(args.DATA); ++ const min = Number(args.ARG0); ++ const max = Number(args.ARG1); ++ return Math.min(Math.max(value, min), max); ++ } ++ dataConvert (args) { ++ return args.DATA; ++ } ++ dataConvertASCIICharacter (args) { ++ return String.fromCharCode(Number(args.DATA) || 0); ++ } ++ dataConvertASCIINumber (args) { ++ const text = String(args.DATA || ''); ++ return text.length ? text.charCodeAt(0) : 0; ++ } + } + + module.exports = OpenBlockArduinoUnoDevice; +diff --git a/node_modules/openblock-vm/src/virtual-machine.js b/node_modules/openblock-vm/src/virtual-machine.js +index d278803..681e9a6 100644 +--- a/node_modules/openblock-vm/src/virtual-machine.js ++++ b/node_modules/openblock-vm/src/virtual-machine.js +@@ -1313,9 +1313,9 @@ class VirtualMachine extends EventEmitter { + * updated for a new locale (or empty if locale hasn't changed.) + */ + setLocale (locale, messages) { +- if (locale !== formatMessage.setup().locale) { +- formatMessage.setup({locale: locale, translations: {[locale]: messages}}); +- } ++ // Always apply messages. Skipping when locale is unchanged left device ++ // strings (e.g. arduinoUno.*) unregistered and flooded the console. ++ formatMessage.setup({locale: locale, translations: {[locale]: messages || {}}}); + return this.extensionManager.refreshBlocks(); + } + diff --git a/prototypes/micropython/.gitignore b/prototypes/micropython/.gitignore new file mode 100644 index 00000000000..70c2c62753f --- /dev/null +++ b/prototypes/micropython/.gitignore @@ -0,0 +1,6 @@ +node_modules/ +test-results/ +playwright-report/ +__pycache__/ +.pytest_cache/ +firmware/build/ diff --git a/prototypes/micropython/MIGRATION_EDGE_CASES.md b/prototypes/micropython/MIGRATION_EDGE_CASES.md new file mode 100644 index 00000000000..0a0cd5a771a --- /dev/null +++ b/prototypes/micropython/MIGRATION_EDGE_CASES.md @@ -0,0 +1,352 @@ +# Replacing the Arduino compile in Beginner Studio with MicroPython: edge cases + +What changes, what can break, and how to handle it, if Beginner Studio stops sending C++ +to the compile server and instead uploads Python to a board running MicroPython. Based +on the current Beginner code (`codegen.js`, `cloudFirmware.js`, `aiFirmware.js`, the +upload and monitor hooks) and on the measurements in [RESULTS.md](RESULTS.md). + +Labels: + +- **Blocker**: must be solved before Beginner can drop the Arduino path. +- **Must handle**: a known failure; the generator, library or page has to deal with it. +- **Watch**: probably fine; needs a test or a soak run to be sure. + +## 1. Board firmware lifecycle + +1. **Board still has an Arduino sketch** (every kit board today). It never answers the + raw REPL, and a sketch printing at 9600 looks like zero bytes at 115200 (seen on the + COM19 board). *Must handle:* the probe has to time out cleanly, not mistake the + garbage for a REPL, and offer "Install TinkerBit firmware". That costs about 100 s per + board at 115200 (measured 99 s write plus 6.5 s erase). +2. **The Advanced IDE wipes MicroPython.** Any Advanced upload (Arduino) replaces the + firmware. Coming back to Beginner then needs the 100 s install again. *Decided + (2026-11-07):* the Advanced IDE stays Arduino and we accept the reinstall. Beginner + reads the board info on every upload and never caches "this port has MicroPython". +3. **Going back to Arduino from MicroPython.** The compile server's ESP32 images must + include the bootloader and partition table, not just the app, or the board keeps the + MicroPython layout. *Watch:* test one Arduino upload over a MicroPython board. +4. **Wrong chip or flash.** The image is for the classic ESP32 with 4 MB flash. A kit + board with 2 MB flash, an S3 or a C3 must be refused before flashing (read the chip and + flash ID first, the way esptool's `flash-id` did on COM19). *Must handle.* +5. **Install interrupted** (cable pulled, laptop sleeps). The ROM bootloader survives, so + the board can always be reinstalled, but the page must say so instead of "Upload + failed". If auto-reset fails on a laptop, the BOOT-button fallback from + `esptool-flash.js` is still needed. *Must handle.* +6. **Firmware and library versions drift.** Boards in a classroom will carry different + library or firmware versions. `TB_INFO` already reports `lib`, `api` and `fw`; the + page must refuse or update when the generator needs a newer API. With Stage B (frozen + library) a library fix means a firmware reflash. *Done in the Studio:* the board info + reports `fw`, `api` and `ver`; an older firmware is refused with "Choose Update + board", a newer one with "Reload the page". On the TinkerBit firmware Upload writes + only `/boot.py` and removes any copied `/lib/tinkerbit`; stock MicroPython still gets + the library copy. +7. **Stock firmware cannot run Cloud.** Cloud needs the custom Stage B build (C MQTT + module). Shipping stock MicroPython plus `/lib` is fine for everything else, but then + Cloud projects need a second firmware. *Done:* one TinkerBit firmware for everyone, + `static/firmware/tinkerbit-esp32-v1.24.1.bin`, checked against its SHA-256 and served + from our own origin. "Update board" in the Studio menu installs it; Upload never + does. A board on stock MicroPython runs everything except Cloud, which asks for + Update board. Service-worker caching for offline use is still open (section 8). +8. **Filesystem full or corrupt.** Writes fail with `ENOSPC` or `EIO`. *Must handle:* + friendly text and a "Reset board storage" action (reformat, reinstall library). +9. **Students edit board files by hand** (Thonny, mpremote). A broken `boot.py` is not + covered by safe mode on stock firmware. *Watch:* Stage B's frozen `_boot.py` still + works; "Install library" rewrites `boot.py`. + +## 2. Connect, upload and stop + +1. **Opening the port may reset the board.** pyserial with DTR/RTS held low did not + reset the CH340 board; mpremote's open did. Chrome's Web Serial behaviour is not + measured yet. *Watch:* check 3 in Chrome on CH340 and CP210x. +2. **The running program fights the upload.** Upload has to stop it first: + - A normal loop: Ctrl-C works. + - A program inside a long C call (`time_pulse_us`, a DHT read, an I2C hang): Ctrl-C + waits for the call to finish. + - HC-05 programs turn Ctrl-C off on purpose. + + *Must handle:* Ctrl-C, then after 1 s a hard reset plus safe mode (built and passing + 10/10 on CH340 with a 2.5 s burst). +3. **The spec's 500 ms safe-mode burst fails** (0/10 on CH340: the board only listens + about 0.8 s after reset). *Must handle:* keep 2.5 s. +4. **Stop leaves outputs running.** Ctrl-C stops the Python code, but PWM keeps + running: motors keep spinning, a servo holds its angle, a tone keeps sounding. Today + every Arduino upload resets the chip, so this never happened. *Done in the + prototype:* after a successful Ctrl-C (Run, uploaded program, or a program that ends + with an error) the page runs `tinkerbit.stop_all()`, which also ends the Cloud + connection. Playwright checks that no PWM is left running. Confirmed on the CH340 + board: after Ctrl-C alone the servo and tone channels kept running; after + `stop_all()` both were off (RESULTS.md, retest 2026-11-07). +5. **A soft reset does not reset hardware.** Upload ends in a soft reset; pins, PWM, I2C + devices and possibly the WiFi state carry over into the next program. *Must handle:* + `boot.py` (or the library's `begin()`) puts every output the project uses into its + safe state. +6. **A program that prints in a tight loop floods the serial line.** The page must drain + and still find the raw REPL prompt. *Watch:* add a "print with no wait" case to the + Playwright and hardware checks. +7. **Upload speed.** Measured on CH340: hex and raw-paste fail the 5 s target for 25 KB; + base64 over the plain raw REPL with no pause passes (3.5 s). A normal Beginner + program is 1 to 5 KB, but an Edge AI model table can be much bigger. *Done in the + prototype:* base64 with no pause is now the page default (25 KB in 3.7 to 3.8 s on + the CH340 board). Still to do: keep the model compact (section 6) and confirm the + speed in Chrome and on CP210x. +8. **The cable is pulled mid-upload.** The `.tmp` plus rename keeps the old `main.py` + whole; stale `.tmp` files are removed on the next connect. *Done in the prototype.* +9. **Port held by something else** (Arduino IDE, Thonny, PuTTY, another TinkerBit tab, + the Advanced IDE monitor). *Done:* friendly text names them. +10. **Monitor and upload share one port.** Today the upload pipeline stops the monitor, + closes the port, flashes and reopens. With MicroPython the monitor, Upload, Stop, + the AI recorder and the Cloud checklist must all share one open connection. *Must + handle:* one serial owner in the Studio, not three hooks each opening the port at + 9600. +11. **Laptop sleep or a USB replug mid-session.** *Done in the prototype:* `getPorts()` + plus the `connect` event, no second picker. +12. **Nothing listed in the picker** (charge-only cable, missing CH340 driver on + Windows). Same as today. *Done:* hint text. + +## 3. Generating Python from the block tree + +`codegen.js` writes C++ line by line. A Python generator needs the same tree walk, plus +these Python-specific rules. *Status:* `pycodegen.js` handles 1 to 5, 7 and 8 and the +float printing in 6 (`"%.2f" %`); `map()` is written inline with `//`, not a helper +module. For 9, the prototype tests compile every template with CPython and run the fully +supported ones in the simulator (Cloud templates on the simulated Stage B board); this +is not in CI yet, and there is no fuzzing or browser-side check. + +1. **Empty bodies are a syntax error in Python.** An If with nothing inside, an empty + Repeat, or an empty program must emit `pass`. *Must handle.* +2. **Indentation is the syntax.** One fixed indent (4 spaces), never mixed, at every + nesting depth. *Must handle.* +3. **Student text must be escaped for Python.** Print text, OLED text, alerts, the BLE + name and HC-05 text can contain quotes, backslashes, newlines, emoji or other scripts. + One `pyStr()` helper must turn any text into a safe Python string literal; otherwise + a student can break the program or inject code. *Must handle.* +4. **Text inside comments.** `codegen.js` puts the port label and other text in `//` + comments. In Python a newline inside a comment becomes code. *Must handle:* strip + newlines or leave text out of comments. +5. **Legacy free-text conditions.** `formatCondition` returns `params.condition` as-is + for old projects. That is a C expression (`&&`, `||`, `!`, `.length()`). *Must + handle:* translate the common forms or turn the If into `False` with a "redo this + If" note (the same way a removed sensor is handled today). +6. **C idioms that change meaning:** + - `true`/`false` become `True`/`False`. + - `x.length() > 0` becomes `len(x) > 0` (for `rfidUid` and `hc05Line`). + - Arduino `map()` with integers needs `//` in Python, not `/`. + - C `int` overflow and truncation do not exist in Python. + - `Serial.println(float)` prints `23.00`; Python prints `23.0`. + + *Must handle:* a small runtime helper module so generated code calls + `tb.map_range(...)` rather than reimplementing it inline. +7. **Variable names.** Part values (`knobValue`, `distance2`, `temperature`, ...) become + module globals. They must not shadow Python or library names (`print`, `time`, + `min`, `id`, `tinkerbit`). If the loop is wrapped in a function, every assigned value + needs a `global` line. *Must handle:* keep the loop at module level, or emit + `global` lines. +8. **The loop.** Arduino's `loop()` becomes `while True:`. *Watch:* behaviour with no + wait at all (Ctrl-C still works; the console floods). +9. **Errors happen on the board now, not on the server.** Today a generator bug fails at + compile time on the server. With Python it becomes a `NameError` or `SyntaxError` on + the board after upload. *Must handle:* + - CI compiles every template and a fuzzed set of block trees with `mpy-cross`, or at + least CPython `ast.parse` plus a name check. + - The browser checks the code before upload (mpy-cross WebAssembly, or a light + check). +10. **Runtime errors must not look like a dead board.** In Arduino a missing OLED prints + a line and the loop goes on. In Python an uncaught `OSError` ends the program and the + board sits at the REPL. *Must handle:* library methods catch hardware errors and + return the same fallbacks as today (-1, 0, a printed hint). The generated program + wraps the loop so an unexpected error prints one friendly line (the prototype's + `hintFor` texts) instead of a traceback. +11. **Big programs and memory.** `main.py` is compiled on the board at every boot, which + costs RAM and time. The library import alone takes 498 ms and 17.6 KB on stock + firmware. *Must handle:* freeze the library (Stage B). For large programs, either + precompile to `.mpy` in the browser (mpy-cross WebAssembly) or keep the generated + code small by moving logic into the library. +12. **The code panel shows Python, not C++.** The "Arduino IDE users: install + ESP32Servo..." note and Copy-to-Arduino go away. Copy becomes "open in Thonny". + Secrets still never appear (section 5). +13. **The Studio's Arduino-specific wording.** For example `friendlyUpload.js` talks + about compiling, the compile server and the BOOT button during upload. *Must + handle:* new messages (no compile step; BOOT only during a firmware install). + +## 4. Runtime behaviour, part by part + +| Part | Edge case | Label | +|---|---|---| +| All analog parts (pot, mic, gas, soil, water) | MicroPython's ADC defaults to 0 dB attenuation (about 0 to 1.1 V); the library must set 11 dB (the prototype does). Raw values can still differ from Arduino's `analogRead`, so thresholds saved in projects (knob > 2000, gas > 700, soil 3200/1200) may shift. Measure the same sensor on both firmwares. | Must handle | +| All analog parts | ADC2 is off while WiFi is on: same rule as today, plus a friendly error if a program reads A1 to A4 with WiFi on. | Done | +| LED brightness, L293D, servo, buzzer tone | ESP32 PWM has 16 channels and 8 timers, and each distinct frequency takes a timer. Several parts at different frequencies (LED 1 kHz, servo 50 Hz, motors, a changing tone) can run out: "out of PWM timers". Arduino allocates differently. The simulator now raises the same error. | Must handle (test the worst template) | +| Servo | `tinkerbit.Servo`: 50 Hz, 500 to 2400 us pulses via `duty_ns`, centred at 90 on creation, limp after Stop. | Done in the library; compare angles with `ESP32Servo` on the board | +| Stepper | `tinkerbit.Stepper`: 200 steps a turn, 1 to 60 RPM from Python sleeps. Unlike the Arduino `Stepper`, the coils are released after every move, because ST has a strapping pin; the motor holds less torque between moves. Long moves block Ctrl-C until the sleep ends. | Watch | +| L293D motors | `tinkerbit.Motors`: speed 0 to 255, forward/back, 1 kHz. | Done in the library | +| Active and passive buzzer | `Buzzer.tone(freq)` is 50 % PWM, `no_tone()` deinits. | Done in the library | +| 4-ch relay (active-low) | Arduino drives it HIGH in `setup()` (about 0.3 s after reset). MicroPython reaches `boot.py` about 0.8 s after reset, so the relay inputs float longer at power-up. | Watch (look at the relays during a reset) | +| Pump, solenoid, buzzer (`offAtStart`) | Today `setup()` drives them LOW. On MicroPython nothing touches them until `main.py` runs (about 1.4 s after a soft reset, 2 s after a hard reset). A pump or lock could run for a second at power-up. | Done in the prototype: creating a `Pump`, `Lock` or `Buzzer` records its jack in `/tb_boot.json` (rewritten only when the set changes) and `boot.py` drives those pins LOW. Confirmed on the CH340 board after a hard reset. Still to measure: the gap before `boot.py` (about 0.8 s), when the pins float | +| DHT11 | MicroPython's `dht` module is C, so timing is fine. Keep the 2 s minimum gap and the A1-first rule. | Watch | +| HC-SR04 | `time_pulse_us` is C, so fine. Echo must never be an output. | Done | +| OLED | The `ssd1306` driver is vendored. Its font is ASCII only, so student text in other scripts or emoji shows as boxes. | Must handle (filter or warn) | +| MPU6050 | Ported; retries every 5 s; shake -1 when missing. | Done | +| HW-605 pulse (MAX30102) | Needs a Python port of the SparkFun beat detector. BPM depends on sampling fast enough, and other blocks' waits slow the loop (already true in Arduino). | Done in the library (`max30102.py`, `Heartbeat`): the detector is a line-by-line port with C integer wrap-around, checked sample by sample against a C-typed reference in the tests. Each `bpm()` drains the 32-sample FIFO (320 ms at 100 Hz), so waits longer than that lose samples, as in Arduino. Still to try with a finger on a real sensor | +| RFID RC522 | Needs a Python MFRC522 driver on SPI with the 3D pins (SCK 16, MOSI 23, MISO 34). | Done in the library (`rc522.py`, `Rfid`): hardware SPI 2 at 1 MHz, pins from `board.py`, 4-, 7- and 10-byte UIDs, the same hex text as Arduino. Still to try with a real reader and card | +| BLE | MicroPython's `bluetooth` module uses about 40 to 50 KB of RAM. It must keep the same service and characteristic UUIDs and the 20-byte limit so phone apps still work. Changing the name means restarting advertising. | Done in the library (`ble.py`, `Ble`): same UUIDs, READ, WRITE and NOTIFY, 20 bytes, the name in the scan response. Cloud and BLE refuse to run together. Advertising checked on the board; still to try with a phone | +| HC-05 | Shares UART0 with the REPL: Upload-only, Ctrl-C off, the monitor at 9600, Stop by hard reset (built). Today the monitor and HC-05 both sit at 9600, so the student sees HC-05 traffic; with MicroPython the monitor has to follow the board between 115200 and 9600. Some HC-05 modules ship at 38400. | Done in the Studio: the monitor and the Cloud dashboard open at 9600 when the project has an HC-05, else at 115200; Upload falls back to safe mode when Ctrl-C is off. 38400 modules are still not handled | +| Copies of a part (LED 2, knob 2) | Each copy is its own cached object per jack; variable names keep the `2` suffix. | Must handle in the generator | + +## 5. TinkerBit Cloud + +The production Cloud firmware in `cloudFirmware.js` did much more than the prototype's +first `tbcloud` C module, which only published. Items 1 to 7 and 9 are now written into +`tbcloud.c` and `tinkerbit/cloud.py`, and tested against a fake module in the simulator. +Stage B is built and runs on the COM19 board (RESULTS.md, build record), and the Studio +generates Cloud projects in Python. A run against a real broker has **not happened +yet**, so items 1 to 5, 7, 9 and 10 still need it. + +1. **Dashboard controls.** The board subscribes to `tb//state/#`, applies switch 1 to + 4 and slider 1 and 2 with version numbers, and sends an `ack` for each. *Written:* + the C module subscribes, clamps and acks; Python reads `cloud.switch(1)`, + `cloud.slider(2)`. +2. **Failsafe values.** When offline for `fs` seconds, each control falls back to its + safe value. *Written* in the C task, so it still works while the program is in a long + Wait. +3. **Heartbeat while the program blocks.** Today the Cloud task runs on its own FreeRTOS + task and keeps sending while `loop()` sits in `delay()`. In Python the readings are + Python variables that the C task cannot read. *Written:* Python pushes values into a + table in the C module (`cloud.set('knobValue', v)`) and the C task sends the table + on its interval, or the empty `{"v":{}}` heartbeat. The generator has to call + `cloud.set` after each read (and `cloud.set(name, None)` for an invalid value such as + distance -1). +4. **Telemetry format.** `{"seq":n,"boot":"xxxxxxxx","v":{...}}`, at most 24 readings, + `%.2f` floats, NaN skipped. *Written.* MicroPython floats are single precision, so + values above about 100,000 lose their last digits. +5. **Alerts.** At most one every 10 s, up to 483 bytes, queued while offline, with the + same printed notes. *Written.* +6. **The going-live checklist reads the USB lines** (`cloudProgress.js`). *Written:* the + C module prints the same `Cloud: ...` lines through `mp_sched_schedule` (so they never + land in the middle of other output), and `cloud.begin()` prints `joining WiFi`. Port + numbers in the lines are the configured ones, so on production they read 8883 and + 443 exactly. The checklist reads them at 115200 instead of 9600. If Python is stuck in + a long C call, lines wait (up to 8 are kept). *Done in the Studio:* the checklist + replays what the board printed during the upload, then keeps reading at 115200. + Confirmed on COM19 up to "WiFi name not found" for a missing network. +7. **Remembering WSS.** *Written:* NVS namespace `tbcloud`, key `wss`, retested daily. +8. **Credentials.** Today they are compiled into the sketch, masked in the panel and + logs, and sent over HTTPS to the compile server. With MicroPython: + - Studio writes `/config.json` over USB at upload time. They never leave the + computer, which is better than today. + - They sit in plain text in board flash, readable by anyone with a USB cable. That is + no worse than today: the sketch also holds them in plain text. + - The write command must never be echoed into the console or the "Details" log. + - "Use for this project", a new device key or a new WiFi password only rewrites + `config.json`: a 1 s action, not a reflash. + + *Done in the Studio:* Upload writes `/config.json` for Cloud projects and logs only + "Wrote the Cloud settings to /config.json". An upload without Cloud removes the file, + and Update board erases it. Checked on COM19: no secret in the log or on the serial + line. +9. **Production broker.** Username is the device id, the password is the device token, + and the ACL is `tb//#`. *Written:* the topics are now `tb//...` and the login + is the device id and `token` from `config.json`; the status message reports + `fw: "mpy-1"`, which the service accepts and treats as a heartbeat firmware. Still to + do: a run against the real service with a test device (needs one from you). +10. **Memory.** Unmeasured: TLS plus MicroPython plus the program on a WROOM without + PSRAM, and reconnects hours later. *Blocker:* check 1. +11. **Cloud plus Edge AI** (Phone AI Alert template): the AI's answers become readings + `ai_`. Memory for both together is untested. *Watch.* + +## 6. Edge AI + +1. **Existing examples must stay valid.** Saved projects hold examples recorded by the + C++ recorder. A Python classifier on the board must compute features that match + exactly (same axes, order, units, 100 Hz, the 200 ms pre-roll, the jolt threshold + 0.35). Otherwise old projects classify wrongly with no visible error. *Blocker:* + - Either keep the recorder and classifier numerically identical (test with the same + raw data through both), + - or bump the parts signature so old examples are asked to be re-recorded (the + mechanism already exists). +2. **100 Hz sampling in Python.** One MPU6050 read (14 bytes at 100 kHz I2C) is about + 1.5 ms plus Python overhead, so 10 ms slots should hold. GC pauses could make a slot + late. *Watch:* measure jitter on the board. +3. **The model table.** Up to 4 things × 10 examples × 24 features = 960 numbers. As a + Python list of floats that is about 15 KB of heap and a slow compile. *Must handle:* + ship it as one `array('f')` built from a bytes literal, or as a separate data file. +4. **The recorder protocol** (`TBAI1,H/F/L/E` lines, `aiLine.js`). Keep the same lines + and the 2 s hello. The recorder hook reads at 9600 today and must read at 115200. + *Must handle.* +5. **The Sensors kind** reads several parts for about 1 s. With analog parts this is + ADC2, so it never runs with Cloud WiFi on. Same rule as today. *Done.* + +## 7. Studio and projects + +1. **Saved projects are block trees**, so they load unchanged. Aliases (`gas` to `mq2`, + `dc` to `l293d`) still apply. *Done.* +2. **Every template must generate valid Python that runs.** `templates.js` has about 90 + templates, from LED Blink to the Advanced scenes (Garden Station, Maker Console, + Access Gate) and the Edge AI and Cloud ones. *Must handle:* a CI test per template, + plus a hardware run of at least one template per part combination before release. +3. **Undo, autosave, the Build view, jack rules.** Unchanged: they work on connections + and blocks, not on code. *Done.* +4. **"Upload complete" now means less.** Arduino's success means compiled and flashed. + With MicroPython, success means the file was written; the program can still fail a + second later. *Must handle:* wait for the program's first line or an error before + saying "Done", and show the friendly error otherwise. +5. **New possibility: instant Run.** Raw REPL Run (no save) takes well under a second. + It is optional, but it changes the lesson flow (try, then Upload to keep it). +6. **Mixed classroom during the switch.** Some boards on Arduino, some on MicroPython, + students moving between Beginner and Advanced. *Must handle:* clear "This board needs + TinkerBit firmware (2 minutes, once)" text and a teacher prep checklist. + +## 8. Offline and classroom operations + +1. **Offline really means offline.** The firmware image (1.7 MB), the library files and + esptool-js must come from our origin and be cached by a service worker. The + prototype loads esptool-js from jsDelivr. *Must handle.* +2. **First-time setup per board** is about 2 minutes at 115200. For 30 boards that is + an hour of prep. *Must handle:* ship kits pre-flashed, or a teacher bulk-flash page. +3. **Chromebooks.** Web Serial works on ChromeOS with built-in CH340 and CP210x + drivers. *Watch:* test once. +4. **Weak USB power.** WiFi or BLE start can brown out the board and loop resets. This + is the same as today, but `TB_INFO`'s `reset` field makes it visible. *Watch.* +5. **Plugged into a laptop, the board starts in its flashing mode.** Seen on the COM19 + CH340 board (2026-11-12): after a replug the ROM bootloader answered esptool with no + reset, and the saved `main.py` did not run; on a phone charger it ran every time, and + RST always fixed it. Windows toggles DTR/RTS while it sets up the CH340, and the + auto-reset circuit turns that into GPIO 0 low while EN rises. It happens before any + firmware, so Arduino sketches are hit the same way. *Board fix:* 1 to 10 µF from EN + to GND (Espressif's recommendation for this circuit) in the next board revision. + *Done in the Studio:* Upload already resets a silent board (safe mode); the serial + monitor's Start now restarts the board with GPIO 0 high, hides the ROM boot log + (garbage at 9600), and after 4 s of silence says to press RST once. The monitor + restarting the program on Start matches the Arduino IDE. + +## 9. Security + +1. **Code injection through student text.** Covered by `pyStr()` (section 3, item 3). + *Must handle.* +2. **Anyone with the USB cable has full control** (raw REPL, read `config.json`). That + matches today: an Arduino board can be read out with esptool. Accept it. +3. **No hardware watchdog, Secure Boot or flash encryption**, as the prototype spec + asked. Accept it for now. + +## Order of work if the checks pass + +1. Hardware checks: page checks 3 to 5 on CH340 and CP210x; Stage B build; checks 1 and 2. +2. ~~Close the prototype gaps: `stop_all()` after Stop, keeping `offAtStart` pins off at + boot, base64 with no pause by default, telemetry topics and dashboard controls in + `tbcloud`.~~ Done in simulation; the board retest and the Stage B build remain. +3. The Python generator behind a setting, with Arduino still the default: control + blocks and simple parts first, then OLED, MPU6050 and Edge AI, then RFID, pulse, BLE + and Cloud. *Started (2026-11-07):* `src/beginner-studio/domain/pycodegen.js`, turned + on with `?board=micropython` (remembered per browser, `?board=arduino` turns it off). + Every control block and every part except Edge AI (RFID, heartbeat, BLE and HC-05 + were added later on 2026-11-07). + Cloud was added on 2026-11-07 (`cloud.set`, `alert`, `send`, `switch(n)`, + `slider(n)`; credentials in `/config.json`). The Studio uploads over the raw REPL. +4. Equivalence tests: each block's Python and C++ produce the same printed lines and + the same pin activity in a simulator; every template runs on a real board. +5. ~~Switch the default to MicroPython, keep Arduino as a fallback for one term, then + remove it.~~ *Done (2026-11-07), changed:* Beginner Studio is MicroPython only and + Arduino is reachable only through the hidden `?board=arduino` switch for teachers. + Edge AI is greyed out with "Coming soon in MicroPython" and cannot be added; + templates that use it cannot be opened. +6. *Done (2026-11-07):* RFID, HC-05, BLE and heartbeat are ported (library 0.2.0, + firmware API 2, the bundled image rebuilt). Next: the real broker run plus check 1, + the new parts on real hardware, then Edge AI. diff --git a/prototypes/micropython/README.md b/prototypes/micropython/README.md new file mode 100644 index 00000000000..2a1d3d3c0c7 --- /dev/null +++ b/prototypes/micropython/README.md @@ -0,0 +1,196 @@ +# TinkerBit MicroPython prototype + +A throwaway prototype that proves or disproves five risks of moving Beginner Studio to +MicroPython on the existing kit (classic ESP32 WROOM-32, no PSRAM, 4 MB flash, CP210x or +CH340/CH9102 USB-serial at 115200). It is not a product rewrite: nothing outside this +folder depends on it. Results go in [RESULTS.md](RESULTS.md). + +## What is here + +| Path | What it is | +|---|---| +| `lib/tinkerbit/board.py` | The jack map. The only file that knows GPIO numbers. | +| `lib/tinkerbit/__init__.py` | The `tinkerbit` library (parts, jack ownership, friendly errors, `info()`). | +| `lib/tinkerbit/cloud.py` | Cloud API (`begin/set/send/alert/switch/slider/connected/status/end`). Stage B firmware only. | +| `lib/ssd1306.py` | OLED driver, vendored from micropython-lib (MIT). | +| `boot.py` | Stage A: relays off at boot, serial safe mode (`TB_SAFE`). | +| `main.py` | Default program: short blink, `info()`, exits within 1 s. | +| `index.html` | Single-file test page: Web Serial transport, raw REPL, Upload, Live, Stop, Recover, HC-05 mode, firmware install, checks 3 to 5. | +| `checks/` | Board-side programs for checks 1 and 2. | +| `firmware/` | Stage B: Docker build script, freeze manifest, frozen `_boot.py`, C modules `tbsys` (ADC sampler, safe mode) and `tbcloud` (esp-mqtt). | +| `sim/` | CPython board simulator, host-side protocol helper, WebSocket bridge for Playwright. | +| `tests/` | pytest (library, simulator, cloud, checks, Studio programs) and Playwright (`tests/e2e/`). | +| `tools/studio_python.js` | Prints the MicroPython Beginner Studio writes for every template (JSON), for `tests/test_studio_programs.py`. | +| `config.example.json` | Template for `/config.json` on the board (Cloud credentials). Placeholders only. | + +## Firmware stages + +- **Stage A:** stock MicroPython v1.24.1 (`ESP32_GENERIC`) with the library copied to `/lib` + by the test page. Used for checks 3, 4 and 5. +- **Stage B:** custom MicroPython v1.24.1 with the library frozen in, the `tbsys` and + `tbcloud` C modules, and our frozen `_boot.py` (serial safe mode before `boot.py`). + Used for checks 1 and 2. + +### Flash Stage A + +1. Download `ESP32_GENERIC-20241129-v1.24.1.bin` from + [micropython.org/download/ESP32_GENERIC](https://micropython.org/download/ESP32_GENERIC/). +2. Either use the test page (Connect; when no MicroPython answers it shows the + "Install TinkerBit firmware" box; pick the `.bin` and install, written at `0x1000`), + or use esptool from a terminal: + + ``` + python -m pip install esptool + python -m esptool --chip esp32 --port COM5 --baud 115200 erase_flash + python -m esptool --chip esp32 --port COM5 --baud 115200 write_flash -z 0x1000 ESP32_GENERIC-20241129-v1.24.1.bin + ``` + + Replace `COM5` with your port. Stay at 115200: CP210x corrupts data above it. + +### Build and flash Stage B + +Needs Docker (on Windows: Docker Desktop, then run the script from WSL or Git Bash). + +``` +cd prototypes/micropython/firmware +./build.sh +``` + +The script uses the pinned `espressif/idf:v5.2.2` image, clones MicroPython `v1.24.1`, +and builds `ESP32_GENERIC` with `FROZEN_MANIFEST=manifest.py` and +`USER_C_MODULES=cmodules/micropython.cmake`. Output: + +- `firmware/build/tinkerbit-stage-b-esp32.bin` (write at `0x1000`, same as Stage A) +- `firmware/build/size.txt` (image and partition usage) + +Flash it the same way as Stage A (page or esptool, `erase_flash` first). The frozen +library wins over a leftover `/lib/tinkerbit` from Stage A because `.frozen` comes before +`/lib` on `sys.path`, but erasing keeps the results clean. + +## Use the test page + +Web Serial needs desktop Chrome or Edge and a secure origin; `localhost` counts. The page +loads the library files with `fetch`, so serve the folder instead of opening the file: + +``` +cd prototypes/micropython +python -m http.server 8000 +``` + +Open . + +1. **Connect.** The picker only lists CP210x and CH340/CH9102 boards. If nothing is + listed, try a data cable (charge-only cables are common). If the port is busy, close + Arduino IDE, Thonny, PuTTY and other TinkerBit tabs. After the first pick the page + reconnects by itself (`getPorts()` and the `connect` event). +2. **Install library** (Stage A only). Writes `/lib/tinkerbit/__init__.py`, `board.py`, + `/lib/ssd1306.py` and `/boot.py`, and `/main.py` only if the board has none. Every + file goes through `.tmp` and a rename, so a cut cable never leaves half a file; + stale `.tmp` files are removed on the next connect. +3. **Run** executes the editor contents through the raw REPL and streams the output. + Nothing is saved; a reset forgets it. +4. **Upload** writes the editor contents to `/main.py` and soft-resets the board so it + runs on its own. +5. **Live** runs one line at a time (`tinkerbit.Led('D13').on()`); expressions print + their value. +6. **Stop** sends Ctrl-C, then runs `tinkerbit.stop_all()` so motors, servos, tones, + pumps and the Cloud connection stop too (Ctrl-C alone leaves PWM running). If the + board does not answer within 1 s it does Recover. + +Options: the transfer mode and the file encoding. The defaults are what measured fastest +on a CH340 board: the plain raw REPL with no pause between writes, and base64 (about +30 % smaller on the wire than hex). Raw-paste and chunked (256 bytes then an 8 ms pause) +are still there for comparison. URL parameters: `?recoverMs=2500` (how long Recover sends +`TB_SAFE`) and `?chunk=2048` (bytes per write command). + +## Safe mode and recovery + +A4 is GPIO 0 (the BOOT pin) and may have a part on it, so the kit cannot rely on the BOOT +button. Instead, after every reset the board listens on the serial line for `TB_SAFE\n`: + +- Stage A: `boot.py` listens for 300 ms. On `TB_SAFE` it prints `TB_SAFE_OK` and raises, + which makes MicroPython skip `main.py`. +- Stage B: the frozen `_boot.py` listens for 300 ms before the filesystem `boot.py` + runs. On `TB_SAFE` it prints `TB_SAFE_OK` and switches the board to the raw REPL, so + `main.py` is skipped. A broken `boot.py` still runs in Stage B (see RESULTS.md). + +Our `boot.py` drives the MD relay pins HIGH (off) before anything else, and it runs in +safe mode too. Stage B's frozen `_boot.py` does not touch the relays, so on Stage B +install the library once (it writes `/boot.py`) to get relays off at boot. **Recover** on the page does: hard reset +(an EN pulse through RTS), send `TB_SAFE` every 50 ms for `recoverMs` (default 2500 ms; +the spec's 500 ms is shorter than the ESP32's boot), wait for `TB_SAFE_OK`, then enter +the raw REPL. From there, Upload a fixed `main.py`. + +If Recover fails (no MicroPython, or a broken `boot.py` in Stage A), reflash with the +page's "Install TinkerBit firmware" or with esptool as above. + +## HC-05 programs + +HC-05 sits on UART0, the same wire as USB and the REPL. Unplug the HC-05 before Connect +or Upload. Programs that use `tinkerbit.HC05()` are Upload-only (Run refuses them): the +library turns off Ctrl-C (`micropython.kbd_intr(-1)`) and switches UART0 to 9600, and +the page monitor follows to 9600. Stop does a hard reset, safe mode, and returns the page +to 115200. + +## Cloud credentials (Stage B, check 1) + +Cloud reads everything from `/config.json` on the board; nothing goes in `main.py` or in +the serial log. Copy `config.example.json`, fill in your WiFi, and keep the test broker +(`test.mosquitto.org`, MQTT over TLS on 8886 with a Let's Encrypt certificate, WSS +fallback on 8081). Do not point it at production `api.tinkerbit.io`. + +The board speaks the production protocol: it logs in with `device_id` as the user name +and `token` as the password (leave it empty on the test broker), publishes on +`tb//telemetry|status|ack|alert`, and listens on `tb//state/#`. +`interval_sec` (default 10) and `min_interval_sec` (default 5) work like the Studio's +Cloud settings. + +```python +from tinkerbit import cloud +cloud.begin() # prints the same "Cloud: ..." lines as the Arduino firmware +cloud.set("temp", 21.5) # sent on the interval, even while the program sleeps +cloud.send({"moving": True}) # set, then send as soon as the minimum gap allows +cloud.alert("Too hot") # at most one every 10 s, kept until online +cloud.switch(1), cloud.slider(2) # dashboard controls, with failsafe values when offline +``` + +Stop (and `tinkerbit.stop_all()`) ends the Cloud connection and publishes `offline`. + +Copy the file with mpremote while the page is disconnected: + +``` +python -m pip install mpremote +mpremote connect COM5 fs cp config.json :/config.json +``` + +Do not commit your filled-in `config.json`. + +## Run the tests + +Simulation only; no board needed. + +``` +cd prototypes/micropython +python -m pip install pytest +python -m pytest tests -q + +npm install +npx playwright install chrome # once, if Chrome is not installed +npx playwright test +``` + +`tests/test_studio_programs.py` needs Node and the repo's `node_modules` (it runs +`tools/studio_python.js`); it is skipped when `node` is missing and takes about two +minutes. + +Playwright starts `sim/bridge.py` itself (page on port 8796, WebSocket on 8795; set +`TB_HTTP_PORT` to move both). The bridge serves this folder and connects a fake +`navigator.serial` in the page to the CPython board simulator. To run it by hand: +`python sim/bridge.py --http-port 8796 --ws-port 8795 --firmware stage_a`. + +## Beginner Studio preview + +Open the Studio with `?board=micropython` to see the blocks as MicroPython for this +library (`src/beginner-studio/domain/pycodegen.js`); the choice is remembered in the +browser until `?board=arduino`. Upload stays Arduino-only for now: in this mode it shows a +note, and the code panel's Copy gives the `main.py` to run from `index.html`. diff --git a/prototypes/micropython/RESULTS.md b/prototypes/micropython/RESULTS.md new file mode 100644 index 00000000000..37209ec5d70 --- /dev/null +++ b/prototypes/micropython/RESULTS.md @@ -0,0 +1,383 @@ +# Results: MicroPython prototype on the TinkerBit kit + +Status: **simulation done; first hardware runs on a CH340 board from a Python host +(see "Hardware runs so far").** The per-check tables below are still empty: they are for +the runs through the test page in Chrome. Fill in one row per board (CP210x and +CH340/CH9102) and write the firmware stage on every row. + +## Hardware runs so far + +Board: CH340 (`1a86:7523`) on COM19, ESP32-D0WD-V3 rev 3.1, 4 MB flash (3.3 V), no +PSRAM. It came with an Arduino sketch (printing `LED: OFF` at 9600), which was erased. +Firmware: Stage A, stock `ESP32_GENERIC-20241129-v1.24.1.bin` (SHA-256 `21d61b52...f048`), +library copied with mpremote. Host: Windows, Python 3.11 + pyserial 3.5 driving the +same protocol code as the simulator tests (`sim/host.py`), **not** Chrome Web Serial. +Measured 2026-11-06. + +| What | Result | +|---|---| +| Opening the port with DTR/RTS held low (pyserial) | no reset (no ROM banner, `up_ms` kept counting) | +| Opening the port with mpremote | reset the board (ROM banner) | +| EN reset reported as | `rst:0x1 (POWERON_RESET)`, as expected on the classic ESP32 | +| Idle Python heap after boot | 164,688 bytes free at 160 MHz | +| `import tinkerbit` from source (Stage A) | 498 ms, peak 23.7 KB, 17.6 KB kept | +| `TB_INFO` | one correct line (`fw: stock`, 13 jacks, uid `28562f4a41f4`) | +| Soft reset to default `main.py` done (`TB_INFO`) | 1,403 ms after Ctrl-D (includes the 300 ms safe-mode window) | +| Hard reset (EN) to default `main.py` done | 2,047 ms (ROM at 7 ms, app entry at 34 ms) | +| Hard reset to `TB_SAFE_OK` | 811 ms (5/5), 1,214 ms (10/10) in a second series | +| Safe mode on a stuck `while True: pass`, 2500 ms burst | **10/10** | +| Safe mode, spec's 500 ms burst | **0/10**: the board starts listening after the burst ends | + +Upload speed (check 5 logic, same commands as `index.html`, 2048 data bytes per command): + +| File | Transfer | Encoding | Wire bytes | ms | Target | Result | +|---|---|---|---|---|---|---| +| 3 KB | raw-paste | hex | 6,406 | 1,219 | < 1500 | PASS | +| 3 KB | raw-paste | base64 | 4,383 | 979 | < 1500 | PASS | +| 3 KB | chunked 256 B / 8 ms | hex | 6,406 | 910 | < 1500 | PASS | +| 3 KB | chunked 256 B / 8 ms | base64 | 4,383 | 785 | < 1500 | PASS | +| 25 KB | raw-paste | hex | 52,144 | 8,668 | < 5000 | FAIL | +| 25 KB | raw-paste | base64 | 34,985 | 6,122 | < 5000 | FAIL | +| 25 KB | chunked 256 B / 8 ms | hex | 52,144 | 5,691 to 6,255 | < 5000 | FAIL | +| 25 KB | chunked 256 B / 8 ms | base64 | 34,985 | 3,862 to 5,005 | < 5000 | PASS (one run at 5,005) | +| 25 KB | chunked, no pause | hex | 52,144 | 5,028 to 5,066 | < 5000 | FAIL | +| 25 KB | chunked, no pause | base64 | 34,985 | 3,483 to 3,521 | < 5000 | **PASS** | + +Every no-pause run (256, 512 and 1024-byte writes, 3 runs each) was checked with +SHA-256 on the board: 24/24 correct. The first raw-paste run, with a host reader that +waited up to 10 ms per read, was slower still (25 KB hex 15.0 s), which shows how +sensitive raw-paste is to read latency. + +What this means: + +- **Raw-paste is the slowest option on CH340.** Its 128-byte flow-control window needs a + credit byte back from the board; one window took about 21 ms against 11 ms of wire + time, so the USB round trip, not the baud rate, sets the speed. +- **Hex cannot pass 25 KB in 5 s at 115200**, even with no pauses: 52 KB on the wire is + 4.5 s before any command overhead. +- **Base64 over the plain raw REPL with no pause passes** (about 3.5 s) and kept every + byte. This is the combination to use, which changes two spec choices (hex chunks and + preferring raw-paste). Still to confirm in Chrome and on CP210x. + +Retest after the gap fixes (same board and host, 2026-11-07). Library installed with the +page's new default transfer (base64, plain raw REPL, no pause). Pin states were read from +the ESP32 GPIO matrix and LEDC registers, not from the library. + +| What | Result | +|---|---| +| Install `__init__.py` (21.7 KB), `cloud.py` (8.1 KB), `boot.py` (2.8 KB) | 3,448 / 1,441 / 769 ms, SHA-256 correct on all three | +| 3 KB upload, default transfer, 3 runs | 526 to 1,234 ms, **PASS**, SHA-256 correct | +| 25 KB upload, default transfer, 3 runs | 3,694 to 3,789 ms, **PASS**, SHA-256 correct | +| Run with a servo (D13) and a 440 Hz tone (A3), then Ctrl-C only | both PWM channels **still running** (the risk is real) | +| Same, then `stop_all()` as the page now does | tone pin driven LOW; servo channel stopped, idle LOW (arm limp) | +| Same two steps on an uploaded `main.py` | identical results | +| `Pump('A2')`, `Lock('D13')`, then hard reset (EN) | `/tb_boot.json` = `{"off": ["A2", "D13"]}`; after boot A2 and D13 are outputs at LOW, A1 (not listed) stays an input | +| Hard reset to `main.py` output | 1,466 to 1,641 ms | + +Not measured: how long after reset `boot.py` drives the pins (earlier runs put +`boot.py` at about 0.8 s after reset; before that the pins float as inputs). + +| # | Risk | Firmware | Pass when | Simulation | CP210x | CH340 | +|---|---|---|---|---|---|---| +| 1 | Memory with Cloud on WROOM without PSRAM | Stage B | at least 30 KB free after connecting, 0 crashes in 24 h | flow only (no real heap) | | | +| 2 | Mic sampling on A1 (GPIO 4, ADC2) | Stage B | at least 8 kHz, jitter under 10 % | flow only (no real timing) | | | +| 3 | Connect without reset, safe mode 10/10 | Stage A | no reset on open, 10/10 recoveries | passes 10/10 | | Python host: no reset on open, 10/10 at 2500 ms, 0/10 at 500 ms; page run pending | +| 4 | HC-05 upload-only, Stop 10/10, back to 115200 | Stage A | 10/10 and page at 115200 | passes | | | +| 5 | Upload speed | Stage A | 3 KB under 1.5 s, 25 KB under 5 s | not meaningful (no baud-rate delay) | | Python host: the new default (base64, no pause) passes, 25 KB in 3.5 to 3.8 s; page run pending | + +## Before you start + +- Two boards: one with CP210x (`10c4:ea60`), one with CH340/CH9102 (`1a86`). Write + down which kit revision each is. Use known data cables. +- Desktop Chrome or Edge, page served from `localhost` (see README, "Use the test page"). +- Close Arduino IDE, Thonny, PuTTY and any other TinkerBit tab. +- Stage A: flash `ESP32_GENERIC-20241129-v1.24.1.bin` after `erase_flash`, Connect, + Install library. The status line must show `TB_INFO` with `fw: stock`. +- Stage B: run `firmware/build.sh`, record `firmware/build/size.txt` below, flash the + `.bin` after `erase_flash`, Connect, Install library (for `/boot.py`). The status line + must show `fw: tinkerbit`. + +### Stage B build record + +| Item | Value | +|---|---| +| Build host (WSL / Linux / macOS) | Windows, Docker Desktop (engine 29.9.2), the `docker run` step of `build.sh` run from PowerShell; MicroPython checkout kept in the `tb-mp` volume | +| `build.sh` exit status | 0 (2026-11-07) | +| Image size (bytes) / app partition size | First build: 1,773,264 bytes, 16 % free. Rebuilt 2026-11-07 with library 0.2.0 (RFID, heartbeat, BLE frozen in): 1,781,600 bytes (SHA-256 `23236190...0ea9a822`); app 1.71 MB, 15 % of the app partition free | +| Linker errors fixed (if any) | `tbcloud` no longer links `idf::mqtt` (it broke MicroPython's module scan); it adds the MQTT header folders instead. `LINE_MAX` renamed `TB_LINE_MAX` (clashed with libc). One harmless warning left: implicit `xTaskCreatePinnedToCore` | +| `import tbsys, tbcloud` on the board | yes on COM19: `TB_INFO` reports `fw: tinkerbit`, `lib: 0.1.0`, `api: 1`; 154 KB heap free after the library; safe mode recovered a Ctrl-C-proof `main.py`. After the rebuild: `lib: 0.2.0`, `api: 2`; with no parts plugged in, `Rfid("3D").card()` gives "" and `Heartbeat("I2C1").bpm()` gives -1, each with its "not found" message once; `Ble("ESP")` advertises, sends and stops cleanly; 152 KB heap free afterwards. Not yet tried with a real reader, sensor or phone | + +The Studio now ships this image as `static/firmware/tinkerbit-esp32-v1.24.1.bin`. + +## Check 1: memory with Cloud (Stage B) + +Steps: + +1. Fill in `config.json` from `config.example.json` (your WiFi, keep + `test.mosquitto.org`, a unique `device_id`). Copy it to the board with + `mpremote connect COMx fs cp config.json :/config.json`. Never paste the password + into the editor, `main.py` or the console. +2. Optional: watch `tb//#` on test.mosquitto.org with any MQTT client to see + the `status` message, the telemetry heartbeat and the readings arrive. Publishing + `{"v":1,"ver":1}` to `tb//state/switch1` should print + `Cloud: switch1 = 1` and answer on `tb//ack`. +3. Open `checks/check1_cloud_memory.py` in the page editor and click **Upload**. Save + the console output (it is all `TB_INFO`, `TB_MEM` and `TB_CLOUD` lines). For the + 24 h run you can instead close the page and log with a serial terminal at 115200 + (for example PuTTY with session logging to a file), as long as nothing else holds the + port. +4. Record the `boot`, `wifi` and `mqtt` records. `ok` must be `true` on both. +5. Leave it 24 h. Take reconnects, WiFi restarts and fresh MQTT starts from the last + `TB_CLOUD` line (`reconnects`, `wifi_restarts`, `fresh_starts`), and count crashes + (a new `TB_INFO` line at any time after the first one = the board restarted; write + down its `reset` field). +6. Pass = `gc_free` **and** `idf_free` both at least 30 KB at the `mqtt` record, and + 0 crashes. Also record `idf_largest` and `idf_min_ever`: TLS reconnects need a large + contiguous block, so these matter more than the total. +7. Repeat once with the WSS fallback forced (set `port` in `config.json` to a closed + port, for example 1, so the module swaps to WSS after 3 failures). Record whether it + connects on 8081. + +| Board | Stage | Point | gc_free | idf_free | idf_largest | idf_min_ever | Notes | +|---|---|---|---|---|---|---|---| +| | B | boot | | | | | | +| | B | wifi | | | | | | +| | B | mqtt (TLS 8886) | | | | | | +| | B | after 24 h | | | | | | +| | B | mqtt (WSS 8081) | | | | | | + +| Board | Stage | Hours | Sends | Failed sends | Reconnects | WiFi restarts | Fresh starts | Crashes | Result | +|---|---|---|---|---|---|---|---|---|---| +| | B | 24 | | | | | | | | + +## Check 2: mic sampling on A1 / ADC2 (Stage B, WiFi off) + +Steps: + +1. Plug the microphone into A1. Power cycle the board so WiFi has never been on. +2. Open `checks/check2_mic_rate.py` in the editor and click **Run**. It sets the CPU to + 240 MHz and captures 4000 samples (0.5 s) three ways. +3. Copy the three `TB_MIC` lines. The `c_sampler` line carries PASS/FAIL (rate at least + 99 % of 8000 Hz and max jitter under 10 %). +4. Run it 3 times; record the worst run. Also run it once on Stage A for the + pure-Python numbers on stock firmware. +5. Sanity check the data: `min`/`max` should move when you clap or talk. + +| Board | Stage | Method | Rate (Hz) | Max jitter % | Mean jitter % | Overruns | min/max | Result | +|---|---|---|---|---|---|---|---|---| +| | A | Python free-running | | | | | | info | +| | A | Python paced 8 kHz | | | | | | info | +| | B | Python free-running | | | | | | info | +| | B | Python paced 8 kHz | | | | | | info | +| | B | C sampler 8 kHz | | | | | | | + +## Check 3: connect without reset, serial safe mode (Stage A, both USB chips) + +Steps: + +1. Stage A with the library installed and the default `main.py`. Connect. +2. Click **Check 3**. It closes and reopens the port 5 times and compares the board's + uptime (`ticks_ms`) and looks for the ROM banner (`rst:0x`) to tell whether opening + reset the board. The `reset` field of `TB_INFO` cannot tell: an EN reset reports + `power_on` on the classic ESP32. +3. It then writes `while True: pass` to `main.py` and runs **Recover** 10 times (hard + reset, `TB_SAFE` burst, wait for `TB_SAFE_OK`). It restores the default `main.py` + at the end. +4. Copy the report box into the table. Do it on both boards. +5. By hand, once per board: unplug and replug the USB cable while the page is open. The + page should reconnect by itself without a second picker. +6. Once per board: run Check 3 with `?recoverMs=500` (the spec's burst length) and record + the recovery count. This tells whether 500 ms is enough on real boot timing. +7. Once per board: plug a button into A4 and hold it during Recover. Note the result + (holding GPIO 0 LOW at reset should enter the ROM download mode, so Recover is + expected to fail; the note just confirms it). + +| Board | Stage | Open resets board? (5 tries) | Recover 10/10 (2500 ms) | Recover times (ms) | Recover with 500 ms | Auto-reconnect after replug | Result | +|---|---|---|---|---|---|---|---| +| CP210x | A | | | | | | | +| CH340 | A | | | | | | | + +## Check 4: HC-05 upload-only mode (Stage A) + +Background: HC-05 TX and the USB chip's TX both drive GPIO 3. Run the check twice per +board. + +Steps, pass 1 (HC-05 unplugged, the page plays the phone): + +1. Tick **HC-05 mode** so the warning shows. Connect. +2. Click **Check 4**. Each round uploads an echo program that uses `tinkerbit.HC05()`, + switches the page to 9600, sends `ping`, expects `echo:ping`, then runs Stop + (hard reset, safe mode, back to 115200). 10 rounds. +3. Copy the report table. + +Steps, pass 2 (HC-05 plugged in, a phone does the talking): + +1. Unplug the HC-05, Upload the echo program (it is in `index.html`, function `check4`; + or type it: `bt = tinkerbit.HC05()`, then echo lines back with `echo:` in front). +2. Plug the HC-05 in, pair the phone, open a Bluetooth serial terminal app at 9600. +3. Send 10 lines from the phone; count the echoes on the phone. +4. Click **Stop** with the HC-05 still plugged in. Record whether the page reaches + `TB_SAFE_OK` and returns to 115200. Repeat 10 times (re-upload in between with the + HC-05 unplugged, as the page says). + +| Board | Stage | HC-05 | Lines echoed at 9600 | Stop recovered | Page back at 115200 | Result | +|---|---|---|---|---|---|---| +| CP210x | A | unplugged (page echo) | /10 | /10 | | | +| CP210x | A | plugged (phone) | /10 | /10 | | | +| CH340 | A | unplugged (page echo) | /10 | /10 | | | +| CH340 | A | plugged (phone) | /10 | /10 | | | + +## Check 5: upload speed (Stage A) + +Steps: + +1. Connect, then click **Check 5**. It writes a 3 KB and a 25 KB file with each + transfer (raw REPL with no pause, raw-paste, chunked 256 B / 8 ms), each in hex and + base64, and times each write from the first byte to the rename. +2. Copy the report table. Run it twice per board and keep the slower run. +3. Also time a real Upload by hand: put a 3 KB program in the editor and click Upload; + note the time from the click to `TB_INFO`/program output (soft reset included). + +| Board | Stage | File | Transfer | Encoding | ms | Target | Result | +|---|---|---|---|---|---|---|---| +| | A | 3 KB | no pause | hex | | < 1500 | | +| | A | 3 KB | no pause | base64 | | < 1500 | | +| | A | 3 KB | raw-paste | hex | | < 1500 | | +| | A | 3 KB | raw-paste | base64 | | < 1500 | | +| | A | 3 KB | chunked | hex | | < 1500 | | +| | A | 3 KB | chunked | base64 | | < 1500 | | +| | A | 25 KB | no pause | hex | | < 5000 | | +| | A | 25 KB | no pause | base64 | | < 5000 | | +| | A | 25 KB | raw-paste | hex | | < 5000 | | +| | A | 25 KB | raw-paste | base64 | | < 5000 | | +| | A | 25 KB | chunked | hex | | < 5000 | | +| | A | 25 KB | chunked | base64 | | < 5000 | | +| | A | 3 KB Upload incl. reset | no pause | base64 | | < 1500 | | + +## What simulation verified + +Run on Windows, Python 3.11, Chrome via Playwright 1.49.1. pytest: **66 passed**. +Playwright: **18 passed**. + +The simulator (`sim/board_sim.py`) follows MicroPython v1.24.1 behaviour read from the +source: the boot order (`_boot.py`, `boot.py`, then `main.py` only in friendly mode when +`boot.py` did not raise), the raw REPL and raw-paste protocol with the 128-byte window +(violations are counted), the REPL UART interrupt character, a 260-byte stdin buffer, +DTR/RTS wired like the auto-reset circuit, baud-rate mismatch garbling, and the +ADC2-off-while-WiFi `OSError`. Within that model, these are verified: + +- Library: one `TB_INFO` line with all fields; `begin()` twice; `stop_all()`; relays HIGH + at boot without importing the library; one object per jack; D13+3D, digital-on-D5, + unknown jack, A-jack-only parts, A jack with Cloud/WiFi on (at creation and when the + program starts WiFi itself) all give the friendly text; 12-sample averaging, soil %, + HC-SR04 cm and -1, DHT11, OLED text and missing OLED, MPU6050 tilt/shake/missing, + LED brightness, button pull-up, the A4 BOOT note, HC-05 at 9600 with Ctrl-C off; no + bare `except:`; no GPIO numbers outside `board.py` (scanned over every source file). +- Protocol: raw REPL framing, exceptions after the first `\x04`, raw-paste flow control + honoured by the host, Ctrl-C stopping busy and sleeping loops, soft reset from friendly + and raw mode. +- Reset control: opening the port with DTR/RTS dropped in the page's order does not + reset; a glitchy RTS-first open does; hard reset through RTS; the esptool classic + sequence enters download mode. +- Safe mode: Stage A (`boot.py`) and Stage B (frozen `_boot.py`) both recover a stuck + `main.py` (Ctrl-C disabled) 10/10. +- Motion and keep-off parts: servo pulse widths, motor duty and direction, buzzer tones, + stepper coils released after a move, the active-low 4-channel relay, and the ESP32 + running out of PWM timers. Pump, lock and buzzer jacks are recorded in + `/tb_boot.json` and driven LOW by `boot.py` on the next power-up. +- Cloud against a fake `tbcloud` that follows the C module: `/config.json` loading, the + exact `Cloud: ...` checklist lines, retained `online` status, `tb//state/#` + subscription, the heartbeat and `{"seq","boot","v"}` telemetry (`%.2f`, NaN skipped, + 24 readings), minimum gap and interval, switch/slider acks with clamping, failsafe + values, disconnect and reconnect lines, alert rate limit and offline queue, Stop ending + the Cloud with `offline`, secrets never in the log; A jacks locked, never together with + Bluetooth, friendly errors for missing config and Stage A. +- Checks: check 2 prints Python rates on Stage A and the C-sampler record on Stage B; + check 1 reaches its `mqtt` record (fake module). +- Test page (Playwright, fake `navigator.serial` over a WebSocket to the simulator): + probe without the library, install, `TB_INFO`; Run streams output; Upload then reset + runs `main.py`; base64 and chunked uploads; Stop on Run and on an uploaded loop, with + motors and tones off afterwards (`stop_all`); Stop + falling back to hard reset and safe mode; Recover on a stuck `main.py`; friendly jack + and ADC2 errors; Live commands; stale `.tmp` cleanup; HC-05 Upload-only at 9600 and + back to 115200; busy port, cancelled picker and no-Web-Serial messages; no firmware + offers the install; Stage B safe mode into the raw REPL; no console errors. + +## What still needs real hardware + +Unless a bullet says otherwise, nothing below was observed on a real ESP32. + +- **All five pass/fail numbers.** The simulator has no real heap, no real ADC timing + and no baud-rate delay, so checks 1, 2 and 5 are flow tests only. +- **Stage B is built and boots on COM19** (see the build record), and safe mode works + on it. A Studio upload printed `Cloud: joining WiFi` and the "WiFi name not found" + line for a missing network. Still unverified, because no broker run has happened: + a real MQTT connection, the WiFi event handlers after a successful join, the NVS + namespace `tbcloud`, the `offline` publish on stop, `tbcloud.stop()` in `_boot.py` + ending the task on soft reset while connected, and the memory numbers of check 1. +- **Real USB chips:** whether opening the port resets the board on CP210x and on CH340 + with Chrome's Web Serial (driver and OS can toggle DTR/RTS before the page does); + real boot timing for the `TB_SAFE` window; `getPorts()` reconnect after replug. +- **TLS and the test broker:** the ISRG roots against test.mosquitto.org 8886, and which + CA the WSS endpoint on 8081 uses (not checked). The 30 s / 2 min / 3 min reconnect + timers have not run against a real outage. +- **HC-05 on a shared UART0:** electrical contention on GPIO 3 with the HC-05 plugged in. +- **Library on real parts:** DHT11 timing, `time_pulse_us` on the HC-SR04, the OLED + driver, MPU6050 reads, PWM brightness, and the import time and RAM cost of compiling + the 15.7 KB `__init__.py` on the board in Stage A. +- **esptool-js 0.5.7** firmware install from the page (only the "offer install" path was + tested; the flashing itself needs a board). + +## Risks that already look bad on paper + +1. **25 KB upload in hex likely fails the 5 s target.** At 115200 baud the wire carries + about 11.5 KB/s. Hex doubles 25 KB to about 52 KB on the wire, which is 4.5 s before + any command overhead; about 13 write commands at roughly 60 ms each (round trip plus + flash write) add about 0.8 s, so about 5.3 s. Base64 is about 35 KB, roughly 3.8 s, + and should pass. The chunked fallback (256 bytes then an 8 ms pause) adds about 1.6 s + in hex (about 7 s, fail) and about 1.1 s in base64 (about 4.9 s, borderline). + Recommendation: base64 by default. A 3 KB `main.py` should take about 0.9 s and pass. +2. **Raw-paste flow control can slow everything down.** The window is 128 bytes and the + host can have 2 windows (256 bytes) in flight, which covers about 22 ms of round trip + at 115200. If the Windows USB driver plus Chrome take longer than that to return the + board's credit byte, throughput drops below the wire speed. Check 5 will show it. +3. **The spec's 500 ms `TB_SAFE` burst is shorter than the ESP32's boot.** From EN + release to `boot.py` takes roughly 0.5 to 1 s (ROM, bootloader, MicroPython start, + filesystem mount), and `boot.py` only listens for 300 ms after that. A 500 ms burst + would end before the board listens. The page sends for 2500 ms by default; check 3 + measures both. +4. **Check 2 jitter under 10 % at 8 kHz means every sample within 12.5 us of its slot.** + A single ADC2 read costs roughly 20 to 50 us in the IDF driver, and the FreeRTOS tick + and other interrupts can each add several microseconds. The average rate should pass; + **max** jitter under 10 % over 4000 samples is at risk even in C. The sampler reports + max and mean jitter separately so you can decide which one the product needs. +5. **HC-05 Stop with the HC-05 plugged in may fail.** HC-05 TX and the USB chip's TX both + drive GPIO 3. Without a series resistor on the kit board, the page's `TB_SAFE` may not + reach the ESP32 while the HC-05 holds the line idle-high. If pass 2 of check 4 fails, + the product needs "unplug HC-05, then Stop", or a series resistor. +6. **Memory with Cloud is tight.** MicroPython v1.24.1 grows the Python heap on demand + out of the same IDF heap that mbedTLS needs for each TLS handshake (tens of KB). The + first connect at boot is the easy case; reconnects hours later, after the Python heap + has grown, are where a WROOM without PSRAM can run out. Watch `idf_largest` and + `idf_min_ever`, not only the totals. +7. **Stage B safe mode still runs the filesystem `boot.py`.** Safe mode skips `main.py` + only. A `boot.py` that hangs would still need a reflash. The test page only ever + writes our own `boot.py`, so this matters only if students can edit it. +8. **Stage A compiles the library on the board at every boot that imports it.** The + 15.7 KB `__init__.py` is compiled from source on the ESP32, which costs time and a + peak of RAM. Stage B freezes it. For a Stage A product, ship precompiled `.mpy` + files. +9. **The reset cause cannot detect an EN reset.** The classic ESP32 reports an EN-pin + reset as power-on, so the page uses the uptime (`up_ms` in `TB_INFO`) instead. + +## Notes on deviations from the spec + +- Test broker port: the spec suggests `test.mosquitto.org:8883`, but 8883 uses + Mosquitto's own CA, not ISRG. The config uses 8886 (Let's Encrypt certificate, so the + ISRG roots from `cloudCerts.js` work) and 8081 for WSS. `config.json` can name a + `ca_file` to use another broker. +- The Recover burst defaults to 2500 ms instead of 500 ms (risk 3); `?recoverMs=500` + restores the spec value for the measurement. +- Check 2 raises the CPU to 240 MHz (MicroPython starts the ESP32 at 160 MHz). +- `cloud.begin()` takes the spec's arguments but they are optional: anything missing + comes from `/config.json`, which is the only place credentials should live. diff --git a/prototypes/micropython/boot.py b/prototypes/micropython/boot.py new file mode 100644 index 00000000000..e1f5c3f9ba0 --- /dev/null +++ b/prototypes/micropython/boot.py @@ -0,0 +1,83 @@ +# TinkerBit boot.py. +# 1. Relays off (active-low outputs driven HIGH) and the last program's pumps, locks and +# buzzers LOW, as early as possible. Only board.py is read here: importing the whole +# library would mean compiling it on every boot. +# 2. Serial safe mode (Stage A, stock MicroPython): if "TB_SAFE\n" arrives within SAFE_MS, +# skip main.py. MicroPython only runs main.py when boot.py finishes without an +# exception, so raising here is how main.py gets skipped. Stage B firmware does this in +# frozen _boot.py instead. +SAFE_MS = 300 + + +def _tb_relays_off(): + from machine import Pin + + ns = {} + try: + with open("/lib/tinkerbit/board.py") as f: + exec(f.read(), ns) + jacks, safe_high = ns["JACKS"], ns["SAFE_HIGH"] + except OSError: + from tinkerbit import board # frozen in Stage B firmware + + jacks, safe_high = board.JACKS, board.SAFE_HIGH + for name in safe_high: + for gpio in jacks[name]["pins"].values(): + Pin(gpio, Pin.OUT, value=1) + # Pumps, locks and buzzers the last program used (the library writes this file). + try: + import json + + with open("/tb_boot.json") as f: + keep_off = json.load(f).get("off", []) + except (OSError, ValueError): + keep_off = [] + for name in keep_off: + spec = jacks.get(name) + if spec and spec["kind"] == "io": + Pin(spec["pins"]["sig"], Pin.OUT, value=0) + + +def _tb_safe(window_ms): + import select + import sys + import time + + poll = select.poll() + poll.register(sys.stdin, select.POLLIN) + end = time.ticks_add(time.ticks_ms(), window_ms) + seen = "" + while time.ticks_diff(end, time.ticks_ms()) > 0: + if not poll.poll(10): + continue + seen = (seen + sys.stdin.read(1))[-16:] + if "TB_SAFE\n" in seen: + # The page keeps sending TB_SAFE until it sees TB_SAFE_OK: answer first, then + # swallow the repeats so they do not reach the REPL as typed text. + print("TB_SAFE_OK") + quiet = time.ticks_ms() + give_up = time.ticks_add(quiet, 1000) + while time.ticks_diff(time.ticks_ms(), quiet) < 150 and time.ticks_diff(give_up, time.ticks_ms()) > 0: + if poll.poll(10): + sys.stdin.read(1) + quiet = time.ticks_ms() + return True + return False + + +try: + _tb_relays_off() +except Exception as e: + print("TB_BOOT relays:", e) + +try: + # TinkerBit firmware (Stage B): frozen _boot.py already listened for TB_SAFE. + import tbsys + + _tb_check = False +except ImportError: + _tb_check = True + +if _tb_check and _tb_safe(SAFE_MS): + raise Exception("TB_SAFE: main.py skipped") +del _tb_relays_off, _tb_safe, _tb_check diff --git a/prototypes/micropython/checks/check1_cloud_memory.py b/prototypes/micropython/checks/check1_cloud_memory.py new file mode 100644 index 00000000000..c4dac4c5319 --- /dev/null +++ b/prototypes/micropython/checks/check1_cloud_memory.py @@ -0,0 +1,60 @@ +# Check 1: memory with Cloud on a WROOM-32 without PSRAM (Stage B firmware). +# Put /config.json on the board (see README), Upload this file as main.py and log the +# serial output for 24 h. Every TB_MEM / TB_CLOUD line is one JSON record. +# A crash shows up as a new "boot" record with a reset cause other than power_on. +import gc +import json +import time + +import esp32 +import network + +import tinkerbit +from tinkerbit import cloud + +SEND_EVERY_S = 5 +REPORT_EVERY = 60 # sends between memory records (5 min) + + +def mem(tag, **extra): + gc.collect() + heap = esp32.idf_heap_info(esp32.HEAP_DATA) + rec = { + "tag": tag, + "t_s": time.ticks_ms() // 1000, + "gc_free": gc.mem_free(), + "idf_free": sum(h[1] for h in heap), + "idf_largest": max(h[2] for h in heap), + "idf_min_ever": min(h[3] for h in heap), + } + rec.update(extra) + print("TB_MEM " + json.dumps(rec)) + + +def wait(cond, seconds): + end = time.ticks_add(time.ticks_ms(), seconds * 1000) + while not cond(): + if time.ticks_diff(end, time.ticks_ms()) <= 0: + return False + time.sleep_ms(200) + return True + + +tinkerbit.info() +mem("boot") +cloud.begin() +sta = network.WLAN(network.STA_IF) +mem("wifi", ok=wait(sta.isconnected, 30)) +mem("mqtt", ok=wait(cloud.connected, 60)) + +sent = 0 +failed = 0 +while True: + if cloud.send({"n": sent, "gc": gc.mem_free()}): + sent += 1 + else: + failed += 1 + if (sent + failed) % REPORT_EVERY == 0: + mem("run", sent=sent, failed=failed) + print("TB_CLOUD " + json.dumps(cloud.status())) + time.sleep(SEND_EVERY_S) diff --git a/prototypes/micropython/checks/check2_mic_rate.py b/prototypes/micropython/checks/check2_mic_rate.py new file mode 100644 index 00000000000..8c876351240 --- /dev/null +++ b/prototypes/micropython/checks/check2_mic_rate.py @@ -0,0 +1,71 @@ +# Check 2: microphone sampling on A1 (ADC2) with WiFi off. Run it from the test page. +# Prints TB_MIC JSON lines: pure-Python rates (both firmware stages) and the C sampler +# (Stage B). Pass = C sampler >= 8000 Hz with max jitter under 10 %. +import array +import json +import time + +import machine + +from tinkerbit import board + +RATE = 8000 +SECONDS = 0.5 +N = int(RATE * SECONDS) + +# MicroPython starts the ESP32 at 160 MHz; the check runs at the chip's full speed. +machine.freq(240000000) +adc = machine.ADC(machine.Pin(board.pin("A1")), atten=machine.ADC.ATTN_11DB) +buf = array.array("h", bytes(2 * N)) +read = adc.read_u16 + + +def report(kind, **values): + values["kind"] = kind + values["cpu_mhz"] = machine.freq() // 1000000 + values["min"] = min(buf) + values["max"] = max(buf) + print("TB_MIC " + json.dumps(values)) + + +# 1. Pure Python, as fast as it goes. +t0 = time.ticks_us() +for i in range(N): + buf[i] = read() >> 4 +dt = max(1, time.ticks_diff(time.ticks_us(), t0)) +report("python_free_running", rate_hz=N * 1000000 // dt) + +# 2. Pure Python, paced at RATE. +period = 1000000 // RATE +nxt = time.ticks_us() +prev = None +max_dev = 0 +total_dev = 0 +late = 0 +for i in range(N): + while time.ticks_diff(nxt, time.ticks_us()) > 0: + pass + t = time.ticks_us() + buf[i] = read() >> 4 + if prev is not None: + dev = abs(time.ticks_diff(t, prev) - period) + total_dev += dev + if dev > max_dev: + max_dev = dev + prev = t + nxt = time.ticks_add(nxt, period) + if time.ticks_diff(t, nxt) >= 0: + late += 1 + nxt = time.ticks_add(t, period) +report("python_paced", target_hz=RATE, max_jitter_pct=max_dev * 100 / period, + mean_jitter_pct=total_dev * 100 / period / (N - 1), overruns=late) + +# 3. C sampler (Stage B firmware only). +try: + import tbsys +except ImportError: + print('TB_MIC {"kind": "c_sampler", "error": "needs TinkerBit firmware (Stage B)"}') +else: + rate, jmax, jmean, over = tbsys.sample(adc, buf, RATE) + report("c_sampler", target_hz=RATE, rate_hz=rate, max_jitter_pct=jmax, mean_jitter_pct=jmean, overruns=over, + result="PASS" if rate >= RATE * 0.99 and jmax < 10 else "FAIL") diff --git a/prototypes/micropython/config.example.json b/prototypes/micropython/config.example.json new file mode 100644 index 00000000000..d30d20a9fe9 --- /dev/null +++ b/prototypes/micropython/config.example.json @@ -0,0 +1,12 @@ +{ + "wifi_ssid": "YOUR-WIFI-NAME", + "wifi_password": "YOUR-WIFI-PASSWORD", + "host": "test.mosquitto.org", + "port": 8886, + "ws_port": 8081, + "ws_path": "/mqtt", + "device_id": "tinkerbit-proto-CHANGE-ME", + "token": "", + "interval_sec": 10, + "min_interval_sec": 5 +} diff --git a/prototypes/micropython/firmware/build.sh b/prototypes/micropython/firmware/build.sh new file mode 100644 index 00000000000..98e70177abd --- /dev/null +++ b/prototypes/micropython/firmware/build.sh @@ -0,0 +1,38 @@ +#!/usr/bin/env bash +# Build TinkerBit Stage B firmware for the classic ESP32 (WROOM-32, 4 MB, no PSRAM). +# MicroPython v1.24.1, board ESP32_GENERIC, ESP-IDF v5.2.2 (pinned Docker image) +# + frozen tinkerbit library, ssd1306, our _boot.py (manifest.py) +# + C modules tbsys (ADC sampler, safe mode) and tbcloud (esp-mqtt) (cmodules/) +# Output: firmware/build/tinkerbit-stage-b-esp32.bin, written at 0x1000. +# Needs Docker. On Windows run it from WSL or Git Bash with Docker Desktop. +set -euo pipefail + +IDF_IMAGE="espressif/idf:v5.2.2" +MPY_TAG="v1.24.1" +BOARD="ESP32_GENERIC" + +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +PROTO="$(dirname "$HERE")" +OUT="$HERE/build" +mkdir -p "$OUT" + +docker run --rm \ + -v "$PROTO":/proto:ro \ + -v "$OUT":/out \ + -e MPY_TAG="$MPY_TAG" -e BOARD="$BOARD" \ + "$IDF_IMAGE" \ + bash -c ' +set -euo pipefail +git clone --depth 1 --branch "$MPY_TAG" https://github.com/micropython/micropython.git /mp +make -C /mp/mpy-cross -j"$(nproc)" +cd /mp/ports/esp32 +make submodules BOARD="$BOARD" +make -j"$(nproc)" BOARD="$BOARD" \ + FROZEN_MANIFEST=/proto/firmware/manifest.py \ + USER_C_MODULES=/proto/firmware/cmodules/micropython.cmake +cp "build-$BOARD/firmware.bin" /out/tinkerbit-stage-b-esp32.bin +idf.py -B "build-$BOARD" size > /out/size.txt 2>&1 || true +' + +echo "Firmware: $OUT/tinkerbit-stage-b-esp32.bin (write at 0x1000)" +echo "Sizes: $OUT/size.txt" diff --git a/prototypes/micropython/firmware/cmodules/micropython.cmake b/prototypes/micropython/firmware/cmodules/micropython.cmake new file mode 100644 index 00000000000..524da904564 --- /dev/null +++ b/prototypes/micropython/firmware/cmodules/micropython.cmake @@ -0,0 +1,3 @@ +# USER_C_MODULES entry point for the ESP32 port (CMake build). +include(${CMAKE_CURRENT_LIST_DIR}/tbsys/micropython.cmake) +include(${CMAKE_CURRENT_LIST_DIR}/tbcloud/micropython.cmake) diff --git a/prototypes/micropython/firmware/cmodules/tbcloud/micropython.cmake b/prototypes/micropython/firmware/cmodules/tbcloud/micropython.cmake new file mode 100644 index 00000000000..e362be429cf --- /dev/null +++ b/prototypes/micropython/firmware/cmodules/tbcloud/micropython.cmake @@ -0,0 +1,21 @@ +add_library(usermod_tbcloud INTERFACE) +target_sources(usermod_tbcloud INTERFACE ${CMAKE_CURRENT_LIST_DIR}/tbcloud.c) +target_include_directories(usermod_tbcloud INTERFACE ${CMAKE_CURRENT_LIST_DIR}) + +# esp-mqtt is the ESP-IDF "mqtt" component (built in to IDF v5.2). The port builds and links every +# IDF component, but its main component does not require mqtt, so only the headers are missing. +# Plain paths only: MicroPython's usermod scan cannot read the generator expressions that linking +# idf::mqtt would pull in. esp_wifi, esp_timer, esp_event, esp_netif and nvs_flash are already +# required by the port. +foreach(tb_comp mqtt tcp_transport esp-tls) + idf_component_get_property(tb_comp_dir ${tb_comp} COMPONENT_DIR) + idf_component_get_property(tb_comp_incs ${tb_comp} INCLUDE_DIRS) + foreach(tb_inc ${tb_comp_incs}) + if(NOT IS_ABSOLUTE ${tb_inc}) + set(tb_inc ${tb_comp_dir}/${tb_inc}) + endif() + target_include_directories(usermod_tbcloud INTERFACE ${tb_inc}) + endforeach() +endforeach() + +target_link_libraries(usermod INTERFACE usermod_tbcloud) diff --git a/prototypes/micropython/firmware/cmodules/tbcloud/tbcloud.c b/prototypes/micropython/firmware/cmodules/tbcloud/tbcloud.c new file mode 100644 index 00000000000..05d1d9696f6 --- /dev/null +++ b/prototypes/micropython/firmware/cmodules/tbcloud/tbcloud.c @@ -0,0 +1,906 @@ +// tbcloud: TinkerBit Cloud for TinkerBit firmware (Stage B), built on ESP-IDF esp-mqtt. +// +// Speaks the same protocol as the Arduino Cloud firmware (src/beginner-studio/domain/ +// cloudFirmware.js), so the Cloud service and dashboard need no changes: +// * topics tb//telemetry, status (retained; last will "offline"), ack and alert; +// subscribes to tb//state/# for dashboard switch1-4 and slider1-2. +// * telemetry {"seq":n,"boot":"xxxxxxxx","v":{...}} on its interval from this task, so it +// keeps going while Python sits in a long sleep. With no readings it is the heartbeat. +// * failsafe: offline for fs seconds, a control falls back to its safe value. +// * alerts: at most one every 10 s, queued while offline. +// * reconnect rules: WiFi kick every 30 s, WiFi restart after 3 min down, fresh MQTT client +// after 2 min stuck, 3 failures before the first connect swap the TLS port and the +// WebSocket port (remembered in NVS, retested daily), login rejected waits 5 min. +// * prints the "Cloud: ..." lines the going-live checklist reads (cloudProgress.js). +// They go through mp_sched_schedule, so Python prints them between bytecodes instead +// of this task writing into the middle of the REPL stream. +// WiFi is started from Python (network.WLAN). The token is copied into C memory and never printed. +// +// tbcloud.start(host, port, ws_port, device_id, token, ca, *, ws_path="/mqtt", +// interval_ms=10000, min_gap_ms=5000, fw="mpy-1") +// tbcloud.set(key, value) -> bool int/float/bool reading, None removes it; at most 24 +// tbcloud.send_now() telemetry as soon as the minimum gap allows +// tbcloud.alert(text) -> int 0 queued, 1 skipped (print the note), 2 skipped quietly +// tbcloud.get(key) -> int switch1-4 (0/1), slider1-2 (0-100) +// tbcloud.status() -> (state, reconnects, transport, last_error, wifi_restarts, fresh_starts, seq) +// state: 0 stopped, 1 waiting for WiFi, 2 connecting, 3 connected +// tbcloud.stop() + +#include +#include +#include +#include +#include + +#include "py/runtime.h" +#include "py/obj.h" +#include "py/mphal.h" + +#include "freertos/FreeRTOS.h" +#include "freertos/semphr.h" +#include "freertos/task.h" +#include "esp_event.h" +#include "esp_idf_version.h" +#include "esp_netif.h" +#include "esp_random.h" +#include "esp_timer.h" +#include "esp_wifi.h" +#include "mqtt_client.h" +#include "nvs.h" + +#define WIFI_KICK_US (30LL * 1000000) +#define WIFI_RESTART_US (180LL * 1000000) +#define MQTT_STUCK_US (120LL * 1000000) +#define AUTH_PAUSE_US (300LL * 1000000) +#define WSS_RETEST_US (86400LL * 1000000) +#define ALERT_GAP_US (10LL * 1000000) +#define NOTE_GAP_US (10LL * 1000000) +#define NO_MEMORY_RETRY_US (5LL * 1000000) +#define SWAP_AFTER_FAILURES (3) +#define MAX_READINGS (24) +#define KEY_MAX (24) +#define ALERT_MAX (484) +#define N_LINES (8) +#define TB_LINE_MAX (112) +#define N_CONTROLS (6) + +enum { ST_STOPPED = 0, ST_WIFI_WAIT = 1, ST_CONNECTING = 2, ST_CONNECTED = 3 }; + +typedef struct { + char key[KEY_MAX]; + float value; + bool is_int; +} reading_t; + +static const char *const control_keys[N_CONTROLS] = {"switch1", "switch2", "switch3", "switch4", "slider1", "slider2"}; + +// Guards everything Python, the MQTT task and the supervisor share (short copies only). +static portMUX_TYPE mux = portMUX_INITIALIZER_UNLOCKED; + +static struct { + SemaphoreHandle_t lock; + TaskHandle_t task; + esp_mqtt_client_handle_t client; + volatile bool running; + volatile int state; + volatile bool connected; + volatile bool ever_connected; + volatile bool auth_rejected; + volatile int failures; + volatile int reconnects; + volatile int last_error; + volatile int64_t down_since; + int wifi_restarts; + int fresh_starts; + bool use_wss; + bool transport_saved; + bool retest_scheduled; + bool auth_paused; + bool handlers; + int64_t auth_at; + int64_t wss_since; + int64_t wifi_lost_at; + int64_t wifi_kick; + int64_t wifi_note; + int64_t mqtt_kick; + int64_t no_memory_at; + int64_t last_send; + uint32_t seq; + int interval_ms; + int min_gap_ms; + char boot[9]; + char fw[25]; + char host[96]; + int port; + int ws_port; + char ws_path[48]; + char device_id[32]; + char token[160]; + char uri[192]; + char will_topic[64]; + char *ca; + + reading_t readings[MAX_READINGS]; + int n_readings; + bool send_now; + int values[N_CONTROLS]; + uint16_t failsafe_sec[N_CONTROLS]; + int failsafe_value[N_CONTROLS]; + bool failsafe_on[N_CONTROLS]; + char alert[ALERT_MAX]; + bool alert_pending; + bool alert_ever; + int64_t alert_at; + int64_t alert_note_at; + + char lines[N_LINES][TB_LINE_MAX]; + int line_head; + int line_count; + bool drain_scheduled; +} s; + +// ---- printed lines ------------------------------------------------------------------- + +static mp_obj_t tbcloud_drain(mp_obj_t arg) { + (void)arg; + char line[TB_LINE_MAX]; + for (;;) { + portENTER_CRITICAL(&mux); + if (!s.line_count) { + s.drain_scheduled = false; + portEXIT_CRITICAL(&mux); + break; + } + memcpy(line, s.lines[s.line_head], TB_LINE_MAX); + s.line_head = (s.line_head + 1) % N_LINES; + s.line_count--; + portEXIT_CRITICAL(&mux); + mp_printf(&mp_plat_print, "%s\n", line); + } + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_1(tbcloud_drain_obj, tbcloud_drain); + +static void note(const char *fmt, ...) { + char line[TB_LINE_MAX]; + va_list ap; + va_start(ap, fmt); + vsnprintf(line, sizeof(line), fmt, ap); + va_end(ap); + portENTER_CRITICAL(&mux); + int slot = (s.line_head + s.line_count) % N_LINES; + if (s.line_count == N_LINES) { + // Python has not run for a while: drop the oldest line. + s.line_head = (s.line_head + 1) % N_LINES; + } else { + s.line_count++; + } + memcpy(s.lines[slot], line, TB_LINE_MAX); + bool schedule = !s.drain_scheduled; + s.drain_scheduled = true; + portEXIT_CRITICAL(&mux); + if (schedule && !mp_sched_schedule(MP_OBJ_FROM_PTR(&tbcloud_drain_obj), mp_const_none)) { + s.drain_scheduled = false; + } +} + +// ---- helpers --------------------------------------------------------------------------- + +static void copy_str(char *dst, size_t size, mp_obj_t obj) { + dst[0] = 0; + if (obj == mp_const_none || obj == MP_OBJ_NULL) { + return; + } + size_t len; + const char *src = mp_obj_str_get_data(obj, &len); + if (len >= size) { + mp_raise_ValueError(MP_ERROR_TEXT("cloud setting too long")); + } + memcpy(dst, src, len); + dst[len] = 0; +} + +static int control_index(const char *key) { + for (int i = 0; i < N_CONTROLS; i++) { + if (strcmp(key, control_keys[i]) == 0) { + return i; + } + } + return -1; +} + +static bool json_long(const char *str, const char *key, long *out) { + const char *p = strstr(str, key); + if (!p) { + return false; + } + p += strlen(key); + char *end = NULL; + long n = strtol(p, &end, 10); + if (end == p) { + return false; + } + *out = n; + return true; +} + +static long clamp(long v, long lo, long hi) { + return v < lo ? lo : (v > hi ? hi : v); +} + +static bool wifi_up(void) { + wifi_ap_record_t ap; + if (esp_wifi_sta_get_ap_info(&ap) != ESP_OK) { + return false; + } + esp_netif_t *netif = esp_netif_get_handle_from_ifkey("WIFI_STA_DEF"); + esp_netif_ip_info_t ip; + return netif && esp_netif_get_ip_info(netif, &ip) == ESP_OK && ip.ip.addr != 0; +} + +static int wifi_rssi(void) { + wifi_ap_record_t ap; + return esp_wifi_sta_get_ap_info(&ap) == ESP_OK ? ap.rssi : 0; +} + +static bool nvs_get_wss(void) { + nvs_handle_t h; + uint8_t v = 0; + if (nvs_open("tbcloud", NVS_READONLY, &h) == ESP_OK) { + nvs_get_u8(h, "wss", &v); + nvs_close(h); + } + return v != 0; +} + +static void nvs_put_wss(bool on) { + nvs_handle_t h; + if (nvs_open("tbcloud", NVS_READWRITE, &h) != ESP_OK) { + return; + } + uint8_t v = 0; + if (nvs_get_u8(h, "wss", &v) != ESP_OK || v != (on ? 1 : 0)) { + nvs_set_u8(h, "wss", on ? 1 : 0); + nvs_commit(h); + } + nvs_close(h); +} + +static void publish(esp_mqtt_client_handle_t client, const char *suffix, const char *msg, int qos, int retain) { + if (!client) { + return; + } + char topic[64]; + snprintf(topic, sizeof(topic), "tb/%s/%s", s.device_id, suffix); + // enqueue never blocks the caller; the MQTT task sends it. + esp_mqtt_client_enqueue(client, topic, msg, 0, qos, retain, true); +} + +// ---- MQTT and WiFi events -------------------------------------------------------------- + +static void on_state(esp_mqtt_event_handle_t e) { + // Only whole, small messages: state payloads are ~40 bytes. Empty = retained message cleared. + if (e->current_data_offset != 0 || e->data_len != e->total_data_len) { + return; + } + if (e->topic_len <= 0 || e->topic_len >= 64 || e->data_len <= 0 || e->data_len >= 96) { + return; + } + char topic[64]; + char body[96]; + memcpy(topic, e->topic, e->topic_len); + topic[e->topic_len] = 0; + memcpy(body, e->data, e->data_len); + body[e->data_len] = 0; + const char *slash = strrchr(topic, '/'); + int idx = slash ? control_index(slash + 1) : -1; + if (idx < 0) { + return; + } + long v = 0, ver = 0, fs = 120, fv = 0; + if (!json_long(body, "\"v\":", &v) || !json_long(body, "\"ver\":", &ver)) { + return; + } + json_long(body, "\"fs\":", &fs); + json_long(body, "\"fv\":", &fv); + long max_v = idx < 4 ? 1 : 100; + v = clamp(v, 0, max_v); + fv = clamp(fv, 0, max_v); + fs = clamp(fs, 0, 3600); + portENTER_CRITICAL(&mux); + s.values[idx] = (int)v; + s.failsafe_sec[idx] = (uint16_t)fs; + s.failsafe_value[idx] = (int)fv; + s.failsafe_on[idx] = false; + portEXIT_CRITICAL(&mux); + char ack[64]; + snprintf(ack, sizeof(ack), "{\"key\":\"%s\",\"ver\":%ld}", control_keys[idx], ver); + publish(e->client, "ack", ack, 1, 0); + note("Cloud: %s = %ld", control_keys[idx], v); +} + +static void on_event(void *arg, esp_event_base_t base, int32_t id, void *data) { + esp_mqtt_event_handle_t e = (esp_mqtt_event_handle_t)data; + switch ((esp_mqtt_event_id_t)id) { + case MQTT_EVENT_CONNECTED: { + s.connected = true; + s.ever_connected = true; + s.failures = 0; + s.state = ST_CONNECTED; + char msg[160]; + snprintf(msg, sizeof(msg), "{\"s\":\"online\",\"fw\":\"%s\",\"rssi\":%d,\"boot\":\"%s\",\"tr\":\"%s\"}", + s.fw, wifi_rssi(), s.boot, s.use_wss ? "wss" : "mqtts"); + publish(e->client, "status", msg, 1, 1); + char topic[64]; + snprintf(topic, sizeof(topic), "tb/%s/state/#", s.device_id); + #if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 1, 0) + esp_mqtt_client_subscribe_single(e->client, topic, 1); + #else + esp_mqtt_client_subscribe(e->client, topic, 1); + #endif + note("Cloud: connected (port %d)", s.use_wss ? s.ws_port : s.port); + break; + } + case MQTT_EVENT_DISCONNECTED: + if (s.connected) { + s.reconnects++; + s.down_since = esp_timer_get_time(); + note("Cloud: disconnected - retrying"); + } + s.connected = false; + if (s.state == ST_CONNECTED) { + s.state = ST_CONNECTING; + } + break; + case MQTT_EVENT_DATA: + on_state(e); + break; + case MQTT_EVENT_ERROR: + if (e->error_handle && e->error_handle->error_type == MQTT_ERROR_TYPE_CONNECTION_REFUSED) { + int rc = (int)e->error_handle->connect_return_code; + s.last_error = rc; + if (rc == MQTT_CONNECTION_REFUSE_BAD_USERNAME || rc == MQTT_CONNECTION_REFUSE_NOT_AUTHORIZED) { + s.auth_rejected = true; + } + } else { + if (e->error_handle && e->error_handle->error_type == MQTT_ERROR_TYPE_TCP_TRANSPORT) { + s.last_error = e->error_handle->esp_tls_last_esp_err; + } + if (!s.connected && wifi_up() && s.failures < 255) { + s.failures++; + } + } + break; + default: + break; + } +} + +static void on_wifi(void *arg, esp_event_base_t base, int32_t id, void *data) { + if (!s.running) { + return; + } + if (base == IP_EVENT && id == IP_EVENT_STA_GOT_IP) { + note("Cloud: WiFi connected (RSSI %d)", wifi_rssi()); + return; + } + if (base != WIFI_EVENT || id != WIFI_EVENT_STA_DISCONNECTED) { + return; + } + int64_t now = esp_timer_get_time(); + if (s.wifi_note && now - s.wifi_note < NOTE_GAP_US) { + return; + } + s.wifi_note = now; + uint8_t reason = ((wifi_event_sta_disconnected_t *)data)->reason; + if (reason == WIFI_REASON_NO_AP_FOUND) { + note("Cloud: WiFi name not found - check spelling, 2.4 GHz networks only"); + } else if (reason == WIFI_REASON_AUTH_FAIL || reason == WIFI_REASON_4WAY_HANDSHAKE_TIMEOUT || + reason == WIFI_REASON_HANDSHAKE_TIMEOUT) { + note("Cloud: wrong WiFi password?"); + } else { + note("Cloud: WiFi lost (reason %u) - reconnecting", (unsigned)reason); + } +} + +// ---- client ------------------------------------------------------------------------------ + +// Both helpers run with s.lock held. +static void client_stop(void) { + if (s.client) { + esp_mqtt_client_destroy(s.client); + s.client = NULL; + } + if (s.connected) { + s.down_since = esp_timer_get_time(); + } + s.connected = false; +} + +static void client_start(int64_t now) { + if (s.no_memory_at && now - s.no_memory_at < NO_MEMORY_RETRY_US) { + return; + } + if (s.use_wss) { + snprintf(s.uri, sizeof(s.uri), "wss://%s:%d%s", s.host, s.ws_port, s.ws_path); + } else { + snprintf(s.uri, sizeof(s.uri), "mqtts://%s:%d", s.host, s.port); + } + esp_mqtt_client_config_t cfg = {0}; + cfg.broker.address.uri = s.uri; + cfg.broker.verification.certificate = s.ca; + cfg.credentials.client_id = s.device_id; + cfg.credentials.username = s.device_id; + cfg.credentials.authentication.password = s.token[0] ? s.token : NULL; + cfg.session.keepalive = 30; + cfg.session.disable_clean_session = false; + cfg.session.last_will.topic = s.will_topic; + cfg.session.last_will.msg = "offline"; + cfg.session.last_will.msg_len = 7; + cfg.session.last_will.qos = 1; + cfg.session.last_will.retain = 1; + cfg.network.reconnect_timeout_ms = 5000; + cfg.network.timeout_ms = 10000; + cfg.buffer.size = 1024; + cfg.buffer.out_size = 1024; + cfg.task.stack_size = 6144; + s.client = esp_mqtt_client_init(&cfg); + if (!s.client) { + s.last_error = ESP_ERR_NO_MEM; + s.no_memory_at = now; + note("Cloud: not enough memory to start"); + return; + } + s.no_memory_at = 0; + esp_mqtt_client_register_event(s.client, (esp_mqtt_event_id_t)ESP_EVENT_ANY_ID, on_event, NULL); + s.ever_connected = false; + s.failures = 0; + s.transport_saved = false; + s.state = ST_CONNECTING; + if (s.use_wss) { + s.wss_since = now; + } + esp_mqtt_client_start(s.client); + note("Cloud: connecting to %s", s.uri); +} + +static int append(char *buf, size_t size, int n, bool *first, const reading_t *r) { + if (n < 0 || (size_t)n >= size || !isfinite(r->value)) { + return n; + } + int w = r->is_int + ? snprintf(buf + n, size - n, "%s\"%s\":%ld", *first ? "" : ",", r->key, (long)r->value) + : snprintf(buf + n, size - n, "%s\"%s\":%.2f", *first ? "" : ",", r->key, (double)r->value); + if (w < 0 || (size_t)w >= size - n) { + return (int)size; + } + *first = false; + return n + w; +} + +// Sent even with no readings: it doubles as the heartbeat. +static void send_telemetry(void) { + reading_t copy[MAX_READINGS]; + portENTER_CRITICAL(&mux); + int count = s.n_readings; + memcpy(copy, s.readings, sizeof(reading_t) * count); + portEXIT_CRITICAL(&mux); + char buf[768]; + bool first = true; + int n = snprintf(buf, sizeof(buf), "{\"seq\":%lu,\"boot\":\"%s\",\"v\":{", (unsigned long)(s.seq + 1), s.boot); + for (int i = 0; i < count; i++) { + n = append(buf, sizeof(buf), n, &first, ©[i]); + } + if (n < 0 || (size_t)n + 3 > sizeof(buf)) { + return; + } + buf[n++] = '}'; + buf[n++] = '}'; + buf[n] = 0; + s.seq++; + publish(s.client, "telemetry", buf, 0, 0); +} + +// ---- supervisor task --------------------------------------------------------------------- + +static void supervisor(void *arg) { + while (s.running) { + vTaskDelay(pdMS_TO_TICKS(100)); + int64_t now = esp_timer_get_time(); + bool up = wifi_up(); + + xSemaphoreTake(s.lock, portMAX_DELAY); + if (up) { + s.wifi_lost_at = 0; + } else { + if (!s.wifi_lost_at) { + s.wifi_lost_at = now; + } + if (!s.connected) { + s.state = ST_WIFI_WAIT; + } + } + if (!up && now - s.wifi_kick >= WIFI_KICK_US) { + s.wifi_kick = now; + esp_wifi_connect(); + } + // The WiFi driver can get stuck after a power dip or router hiccup: restart it. + if (s.wifi_lost_at && now - s.wifi_lost_at >= WIFI_RESTART_US) { + s.wifi_lost_at = now; + s.wifi_restarts++; + note("Cloud: WiFi stuck - restarting WiFi"); + client_stop(); + esp_wifi_disconnect(); + xSemaphoreGive(s.lock); + vTaskDelay(pdMS_TO_TICKS(500)); + xSemaphoreTake(s.lock, portMAX_DELAY); + esp_wifi_connect(); + s.wifi_kick = esp_timer_get_time(); + } + // WiFi is fine but MQTT has not come back for 2 min: start a fresh connection. + if (up && s.client && s.ever_connected && !s.connected && + now - s.down_since >= MQTT_STUCK_US && now - s.mqtt_kick >= MQTT_STUCK_US) { + s.mqtt_kick = now; + s.fresh_starts++; + note("Cloud: reconnect stuck - starting a fresh connection"); + client_stop(); + } + if (s.auth_rejected) { + s.auth_rejected = false; + client_stop(); + s.auth_paused = true; + s.auth_at = now; + note("Cloud: login rejected - re-upload from Studio (trying again in 5 min)"); + } + if (s.auth_paused && now - s.auth_at >= AUTH_PAUSE_US) { + s.auth_paused = false; + } + if (up && !s.client && !s.auth_paused) { + client_start(now); + } + // TLS port blocked (school networks)? Try the WebSocket port, and back again. + if (s.client && !s.ever_connected && s.failures >= SWAP_AFTER_FAILURES) { + client_stop(); + s.use_wss = !s.use_wss; + if (s.use_wss) { + note("Cloud: port %d blocked? using port %d", s.port, s.ws_port); + } else { + note("Cloud: trying port %d again", s.port); + } + client_start(now); + } + if (s.connected && !s.transport_saved) { + s.transport_saved = true; + nvs_put_wss(s.use_wss); + } + // Once a day on the WebSocket port, forget it so the next start tries TLS first again. + if (s.use_wss && s.connected && !s.retest_scheduled && now - s.wss_since >= WSS_RETEST_US) { + s.retest_scheduled = true; + nvs_put_wss(false); + } + + if (!s.connected) { + int64_t down = now - s.down_since; + for (int i = 0; i < N_CONTROLS; i++) { + portENTER_CRITICAL(&mux); + uint16_t fs = s.failsafe_sec[i]; + bool fire = fs > 0 && !s.failsafe_on[i] && down >= (int64_t)fs * 1000000; + if (fire) { + s.failsafe_on[i] = true; + s.values[i] = s.failsafe_value[i]; + } + int fv = s.failsafe_value[i]; + portEXIT_CRITICAL(&mux); + if (fire) { + note("Cloud: offline %us - %s set to safe value %d", (unsigned)fs, control_keys[i], fv); + } + } + } + + if (s.connected) { + char text[ALERT_MAX]; + bool pending = false; + portENTER_CRITICAL(&mux); + if (s.alert_pending) { + memcpy(text, s.alert, sizeof(text)); + s.alert_pending = false; + pending = true; + } + portEXIT_CRITICAL(&mux); + if (pending) { + publish(s.client, "alert", text, 1, 0); + } + + int64_t since = now - s.last_send; + portENTER_CRITICAL(&mux); + bool due = since >= (int64_t)s.interval_ms * 1000 || + (s.send_now && since >= (int64_t)s.min_gap_ms * 1000); + if (due) { + s.send_now = false; + } + portEXIT_CRITICAL(&mux); + if (due) { + s.last_send = now; + send_telemetry(); + } + } + xSemaphoreGive(s.lock); + } + xSemaphoreTake(s.lock, portMAX_DELAY); + if (s.client && s.connected) { + // A clean disconnect does not fire the last will: say it ourselves. + char topic[64]; + snprintf(topic, sizeof(topic), "tb/%s/status", s.device_id); + esp_mqtt_client_publish(s.client, topic, "offline", 7, 1, 1); + vTaskDelay(pdMS_TO_TICKS(200)); + } + client_stop(); + s.state = ST_STOPPED; + s.task = NULL; + xSemaphoreGive(s.lock); + vTaskDelete(NULL); +} + +static void stop_and_wait(void) { + if (!s.task) { + return; + } + s.running = false; + for (int i = 0; i < 60 && s.task; i++) { + MP_THREAD_GIL_EXIT(); + vTaskDelay(pdMS_TO_TICKS(50)); + MP_THREAD_GIL_ENTER(); + } +} + +// ---- Python API -------------------------------------------------------------------------- + +static mp_obj_t tbcloud_start(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + enum { ARG_host, ARG_port, ARG_ws_port, ARG_device_id, ARG_token, ARG_ca, ARG_ws_path, ARG_interval_ms, ARG_min_gap_ms, ARG_fw }; + static const mp_arg_t allowed[] = { + { MP_QSTR_host, MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, + { MP_QSTR_port, MP_ARG_REQUIRED | MP_ARG_INT, {.u_int = 8883} }, + { MP_QSTR_ws_port, MP_ARG_REQUIRED | MP_ARG_INT, {.u_int = 443} }, + { MP_QSTR_device_id, MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, + { MP_QSTR_token, MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = mp_const_none} }, + { MP_QSTR_ca, MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, + { MP_QSTR_ws_path, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, + { MP_QSTR_interval_ms, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 10000} }, + { MP_QSTR_min_gap_ms, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 5000} }, + { MP_QSTR_fw, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, + }; + mp_arg_val_t args[MP_ARRAY_SIZE(allowed)]; + mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed), allowed, args); + + if (!s.lock) { + s.lock = xSemaphoreCreateMutex(); + } + stop_and_wait(); + + copy_str(s.host, sizeof(s.host), args[ARG_host].u_obj); + copy_str(s.device_id, sizeof(s.device_id), args[ARG_device_id].u_obj); + copy_str(s.token, sizeof(s.token), args[ARG_token].u_obj); + copy_str(s.ws_path, sizeof(s.ws_path), args[ARG_ws_path].u_obj); + copy_str(s.fw, sizeof(s.fw), args[ARG_fw].u_obj); + if (!s.ws_path[0]) { + strcpy(s.ws_path, "/mqtt"); + } + if (!s.fw[0]) { + strcpy(s.fw, "mpy-1"); + } + s.port = args[ARG_port].u_int; + s.ws_port = args[ARG_ws_port].u_int; + s.interval_ms = args[ARG_interval_ms].u_int; + s.min_gap_ms = args[ARG_min_gap_ms].u_int; + snprintf(s.will_topic, sizeof(s.will_topic), "tb/%s/status", s.device_id); + + size_t ca_len; + const char *ca = mp_obj_str_get_data(args[ARG_ca].u_obj, &ca_len); + free(s.ca); + // esp-mqtt keeps a pointer to the PEM, so it lives outside the GC heap. + s.ca = malloc(ca_len + 1); + if (!s.ca) { + mp_raise_msg(&mp_type_MemoryError, MP_ERROR_TEXT("no memory for the CA")); + } + memcpy(s.ca, ca, ca_len); + s.ca[ca_len] = 0; + + int64_t now = esp_timer_get_time(); + snprintf(s.boot, sizeof(s.boot), "%08lx", (unsigned long)esp_random()); + s.state = ST_WIFI_WAIT; + s.connected = false; + s.ever_connected = false; + s.auth_rejected = false; + s.auth_paused = false; + s.failures = 0; + s.reconnects = 0; + s.last_error = 0; + s.wifi_restarts = 0; + s.fresh_starts = 0; + s.use_wss = nvs_get_wss(); + s.transport_saved = false; + s.retest_scheduled = false; + s.wifi_lost_at = 0; + s.wifi_kick = now; + s.wifi_note = 0; + s.down_since = now; + s.mqtt_kick = 0; + s.no_memory_at = 0; + s.last_send = 0; + s.seq = 0; + portENTER_CRITICAL(&mux); + s.n_readings = 0; + s.send_now = false; + for (int i = 0; i < N_CONTROLS; i++) { + s.values[i] = 0; + s.failsafe_sec[i] = 120; + s.failsafe_value[i] = 0; + s.failsafe_on[i] = false; + } + s.alert_pending = false; + s.alert_ever = false; + s.alert_note_at = 0; + s.line_head = 0; + s.line_count = 0; + s.drain_scheduled = false; + portEXIT_CRITICAL(&mux); + + // Needs the default event loop, which network.WLAN().active(True) creates. + if (!s.handlers && + esp_event_handler_instance_register(WIFI_EVENT, WIFI_EVENT_STA_DISCONNECTED, on_wifi, NULL, NULL) == ESP_OK && + esp_event_handler_instance_register(IP_EVENT, IP_EVENT_STA_GOT_IP, on_wifi, NULL, NULL) == ESP_OK) { + s.handlers = true; + } + + s.running = true; + if (xTaskCreatePinnedToCore(supervisor, "tbcloud", 6144, NULL, 4, &s.task, 0) != pdPASS) { + s.running = false; + s.task = NULL; + mp_raise_msg(&mp_type_MemoryError, MP_ERROR_TEXT("no memory for the cloud task")); + } + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_KW(tbcloud_start_obj, 6, tbcloud_start); + +static mp_obj_t tbcloud_set(mp_obj_t key_in, mp_obj_t value_in) { + size_t len; + const char *key = mp_obj_str_get_data(key_in, &len); + bool ok = len > 0 && len < KEY_MAX; + for (size_t i = 0; ok && i < len; i++) { + char c = key[i]; + ok = c == '_' || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (i > 0 && c >= '0' && c <= '9'); + } + if (!ok) { + mp_raise_ValueError(MP_ERROR_TEXT("reading names use letters, digits and _ (up to 23)")); + } + bool remove = value_in == mp_const_none; + float value = 0; + bool is_int = false; + if (!remove) { + if (mp_obj_is_bool(value_in) || mp_obj_is_int(value_in)) { + is_int = true; + value = (float)mp_obj_get_int(value_in); + } else if (mp_obj_is_float(value_in)) { + value = mp_obj_get_float(value_in); + } else { + mp_raise_TypeError(MP_ERROR_TEXT("readings are numbers")); + } + } + bool stored = false; + portENTER_CRITICAL(&mux); + int found = -1; + for (int i = 0; i < s.n_readings; i++) { + if (strncmp(s.readings[i].key, key, KEY_MAX) == 0) { + found = i; + break; + } + } + if (remove) { + if (found >= 0) { + memmove(&s.readings[found], &s.readings[found + 1], sizeof(reading_t) * (s.n_readings - found - 1)); + s.n_readings--; + } + stored = true; + } else { + if (found < 0 && s.n_readings < MAX_READINGS) { + // The Cloud service drops a message with more than 24 readings: skip the rest. + found = s.n_readings++; + memcpy(s.readings[found].key, key, len); + s.readings[found].key[len] = 0; + } + if (found >= 0) { + s.readings[found].value = value; + s.readings[found].is_int = is_int; + stored = true; + } + } + portEXIT_CRITICAL(&mux); + return mp_obj_new_bool(stored); +} +static MP_DEFINE_CONST_FUN_OBJ_2(tbcloud_set_obj, tbcloud_set); + +static mp_obj_t tbcloud_send_now(void) { + portENTER_CRITICAL(&mux); + s.send_now = true; + portEXIT_CRITICAL(&mux); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_0(tbcloud_send_now_obj, tbcloud_send_now); + +static mp_obj_t tbcloud_alert(mp_obj_t text_in) { + size_t len; + const char *text = mp_obj_str_get_data(text_in, &len); + int64_t now = esp_timer_get_time(); + int result; + portENTER_CRITICAL(&mux); + if (s.alert_pending || (s.alert_ever && now - s.alert_at < ALERT_GAP_US)) { + if (!s.alert_note_at || now - s.alert_note_at >= NOTE_GAP_US) { + s.alert_note_at = now; + result = 1; + } else { + result = 2; + } + } else { + size_t n = len < ALERT_MAX - 1 ? len : ALERT_MAX - 1; + memcpy(s.alert, text, n); + s.alert[n] = 0; + s.alert_pending = true; + s.alert_ever = true; + s.alert_at = now; + result = 0; + } + portEXIT_CRITICAL(&mux); + return mp_obj_new_int(result); +} +static MP_DEFINE_CONST_FUN_OBJ_1(tbcloud_alert_obj, tbcloud_alert); + +static mp_obj_t tbcloud_get(mp_obj_t key_in) { + int idx = control_index(mp_obj_str_get_str(key_in)); + if (idx < 0) { + mp_raise_ValueError(MP_ERROR_TEXT("dashboard controls are switch1-4 and slider1-2")); + } + portENTER_CRITICAL(&mux); + int v = s.values[idx]; + portEXIT_CRITICAL(&mux); + return mp_obj_new_int(v); +} +static MP_DEFINE_CONST_FUN_OBJ_1(tbcloud_get_obj, tbcloud_get); + +static mp_obj_t tbcloud_status(void) { + mp_obj_t t[7] = { + mp_obj_new_int(s.task ? s.state : ST_STOPPED), + mp_obj_new_int(s.reconnects), + mp_obj_new_str(s.use_wss ? "wss" : "mqtts", s.use_wss ? 3 : 5), + mp_obj_new_int(s.last_error), + mp_obj_new_int(s.wifi_restarts), + mp_obj_new_int(s.fresh_starts), + mp_obj_new_int_from_uint(s.seq), + }; + return mp_obj_new_tuple(7, t); +} +static MP_DEFINE_CONST_FUN_OBJ_0(tbcloud_status_obj, tbcloud_status); + +static mp_obj_t tbcloud_stop(void) { + stop_and_wait(); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_0(tbcloud_stop_obj, tbcloud_stop); + +static const mp_rom_map_elem_t tbcloud_globals_table[] = { + { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_tbcloud) }, + { MP_ROM_QSTR(MP_QSTR_start), MP_ROM_PTR(&tbcloud_start_obj) }, + { MP_ROM_QSTR(MP_QSTR_set), MP_ROM_PTR(&tbcloud_set_obj) }, + { MP_ROM_QSTR(MP_QSTR_send_now), MP_ROM_PTR(&tbcloud_send_now_obj) }, + { MP_ROM_QSTR(MP_QSTR_alert), MP_ROM_PTR(&tbcloud_alert_obj) }, + { MP_ROM_QSTR(MP_QSTR_get), MP_ROM_PTR(&tbcloud_get_obj) }, + { MP_ROM_QSTR(MP_QSTR_status), MP_ROM_PTR(&tbcloud_status_obj) }, + { MP_ROM_QSTR(MP_QSTR_stop), MP_ROM_PTR(&tbcloud_stop_obj) }, +}; +static MP_DEFINE_CONST_DICT(tbcloud_globals, tbcloud_globals_table); + +const mp_obj_module_t tbcloud_module = { + .base = { &mp_type_module }, + .globals = (mp_obj_dict_t *)&tbcloud_globals, +}; + +MP_REGISTER_MODULE(MP_QSTR_tbcloud, tbcloud_module); diff --git a/prototypes/micropython/firmware/cmodules/tbsys/micropython.cmake b/prototypes/micropython/firmware/cmodules/tbsys/micropython.cmake new file mode 100644 index 00000000000..5c84df7beb7 --- /dev/null +++ b/prototypes/micropython/firmware/cmodules/tbsys/micropython.cmake @@ -0,0 +1,4 @@ +add_library(usermod_tbsys INTERFACE) +target_sources(usermod_tbsys INTERFACE ${CMAKE_CURRENT_LIST_DIR}/tbsys.c) +target_include_directories(usermod_tbsys INTERFACE ${CMAKE_CURRENT_LIST_DIR}) +target_link_libraries(usermod INTERFACE usermod_tbsys) diff --git a/prototypes/micropython/firmware/cmodules/tbsys/tbsys.c b/prototypes/micropython/firmware/cmodules/tbsys/tbsys.c new file mode 100644 index 00000000000..ba3859f444a --- /dev/null +++ b/prototypes/micropython/firmware/cmodules/tbsys/tbsys.c @@ -0,0 +1,97 @@ +// tbsys: small native helpers for TinkerBit firmware (Stage B). +// +// tbsys.skip_main() +// Called from frozen _boot.py when TB_SAFE arrives. Switches pyexec to raw-REPL mode; +// ports/esp32/main.c only runs main.py in friendly-REPL mode, so main.py is skipped +// and the host lands in the raw REPL. +// +// tbsys.sample(adc, buf, rate_hz) -> (rate_hz, max_jitter_pct, mean_jitter_pct, overruns) +// Fills array('h') `buf` with 12-bit readings (adc.read_u16() >> 4) paced by +// esp_timer at `rate_hz`. Calling the ADC object's own read_u16 keeps pin and driver +// handling in MicroPython (no GPIO numbers here, no clash between ADC drivers). +// Jitter is the deviation of each sample interval from the ideal period. + +#include + +#include "py/runtime.h" +#include "py/obj.h" +#include "shared/runtime/pyexec.h" +#include "esp_timer.h" + +static mp_obj_t tbsys_skip_main(void) { + pyexec_mode_kind = PYEXEC_MODE_RAW_REPL; + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_0(tbsys_skip_main_obj, tbsys_skip_main); + +static mp_obj_t tbsys_sample(mp_obj_t adc_in, mp_obj_t buf_in, mp_obj_t rate_in) { + mp_buffer_info_t bufinfo; + mp_get_buffer_raise(buf_in, &bufinfo, MP_BUFFER_WRITE); + if (bufinfo.typecode != 'h') { + mp_raise_ValueError(MP_ERROR_TEXT("buf must be array('h')")); + } + size_t n = bufinfo.len / sizeof(int16_t); + mp_int_t rate = mp_obj_get_int(rate_in); + if (n < 2 || rate < 100 || rate > 50000) { + mp_raise_ValueError(MP_ERROR_TEXT("need 2+ samples and 100..50000 Hz")); + } + int16_t *out = (int16_t *)bufinfo.buf; + + mp_obj_t read[2]; + mp_load_method(adc_in, MP_QSTR_read_u16, read); + + const int64_t period = 1000000 / rate; + int64_t next = esp_timer_get_time(); + int64_t first = 0; + int64_t prev = 0; + int64_t max_dev = 0; + int64_t sum_dev = 0; + mp_int_t overruns = 0; + + for (size_t i = 0; i < n; i++) { + int64_t t; + while ((t = esp_timer_get_time()) < next) { + } + out[i] = (int16_t)(mp_obj_get_int(mp_call_method_n_kw(0, 0, read)) >> 4); + if (i == 0) { + first = t; + } else { + int64_t dev = llabs((t - prev) - period); + sum_dev += dev; + if (dev > max_dev) { + max_dev = dev; + } + } + prev = t; + next += period; + if (t >= next) { + // A whole period was lost (interrupt or slow read): restart the schedule. + overruns++; + next = t + period; + } + } + + int64_t span = prev - first; + mp_obj_t result[4] = { + mp_obj_new_int(span > 0 ? (mp_int_t)((int64_t)(n - 1) * 1000000 / span) : 0), + mp_obj_new_float((mp_float_t)max_dev * 100 / (mp_float_t)period), + mp_obj_new_float((mp_float_t)sum_dev * 100 / (mp_float_t)period / (mp_float_t)(n - 1)), + mp_obj_new_int(overruns), + }; + return mp_obj_new_tuple(4, result); +} +static MP_DEFINE_CONST_FUN_OBJ_3(tbsys_sample_obj, tbsys_sample); + +static const mp_rom_map_elem_t tbsys_globals_table[] = { + { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_tbsys) }, + { MP_ROM_QSTR(MP_QSTR_skip_main), MP_ROM_PTR(&tbsys_skip_main_obj) }, + { MP_ROM_QSTR(MP_QSTR_sample), MP_ROM_PTR(&tbsys_sample_obj) }, +}; +static MP_DEFINE_CONST_DICT(tbsys_globals, tbsys_globals_table); + +const mp_obj_module_t tbsys_module = { + .base = { &mp_type_module }, + .globals = (mp_obj_dict_t *)&tbsys_globals, +}; + +MP_REGISTER_MODULE(MP_QSTR_tbsys, tbsys_module); diff --git a/prototypes/micropython/firmware/frozen/_boot.py b/prototypes/micropython/firmware/frozen/_boot.py new file mode 100644 index 00000000000..9b9066658d1 --- /dev/null +++ b/prototypes/micropython/firmware/frozen/_boot.py @@ -0,0 +1,56 @@ +# TinkerBit frozen _boot.py (Stage B firmware). Replaces ports/esp32/modules/_boot.py. +# MicroPython runs it before boot.py on every boot, and it cannot be broken from the +# filesystem, so serial safe mode always works. +import gc +import vfs +from flashbdev import bdev + +try: + if bdev: + vfs.mount(bdev, "/") +except OSError: + import inisetup + + inisetup.setup() + +# A soft reset does not stop FreeRTOS tasks: end the last program's Cloud connection. +import tbcloud + +tbcloud.stop() +del tbcloud + + +def _tb_safe(window_ms): + import select + import sys + import time + + poll = select.poll() + poll.register(sys.stdin, select.POLLIN) + end = time.ticks_add(time.ticks_ms(), window_ms) + seen = "" + while time.ticks_diff(end, time.ticks_ms()) > 0: + if not poll.poll(10): + continue + seen = (seen + sys.stdin.read(1))[-16:] + if "TB_SAFE\n" in seen: + # Answer first so the page stops repeating, then swallow the repeats. + print("TB_SAFE_OK") + quiet = time.ticks_ms() + give_up = time.ticks_add(quiet, 1000) + while time.ticks_diff(time.ticks_ms(), quiet) < 150 and time.ticks_diff(give_up, time.ticks_ms()) > 0: + if poll.poll(10): + sys.stdin.read(1) + quiet = time.ticks_ms() + return True + return False + + +if _tb_safe(300): + import tbsys + + # Switches pyexec to raw-REPL mode: main.c then skips main.py and the host lands + # directly in the raw REPL. + tbsys.skip_main() +del _tb_safe +gc.collect() diff --git a/prototypes/micropython/firmware/manifest.py b/prototypes/micropython/firmware/manifest.py new file mode 100644 index 00000000000..952a4e8a8f6 --- /dev/null +++ b/prototypes/micropython/firmware/manifest.py @@ -0,0 +1,26 @@ +# TinkerBit Stage B manifest. Same content as ports/esp32/boards/manifest.py in +# MicroPython v1.24.1, except that _boot.py is ours (serial safe mode) and the TinkerBit +# library plus the ssd1306 driver are frozen in. Relative paths are relative to this file. + +# Port modules, without the stock _boot.py. +freeze("$(PORT_DIR)/modules", ("apa106.py", "espnow.py", "flashbdev.py", "inisetup.py")) +freeze("frozen", "_boot.py") + +include("$(MPY_DIR)/extmod/asyncio") + +# Useful networking-related packages. +require("bundle-networking") + +# Require some micropython-lib modules. +require("aioespnow") +require("dht") +require("ds18x20") +require("neopixel") +require("onewire") +require("umqtt.robust") +require("umqtt.simple") +require("upysh") + +# TinkerBit additions. +require("ssd1306") +package("tinkerbit", base_path="../lib") diff --git a/prototypes/micropython/index.html b/prototypes/micropython/index.html new file mode 100644 index 00000000000..33892f68d3a --- /dev/null +++ b/prototypes/micropython/index.html @@ -0,0 +1,1067 @@ + + + + + +TinkerBit MicroPython prototype + + + + +
+

TinkerBit MicroPython prototype

+ Disconnected + +
+
This page needs Web Serial. Use desktop Chrome or Edge.
+
+
+

Board

+
+ + No board listed? Try a data cable + +
+
+ + + + + +
+
+ + + +
+
Unplug HC-05 before Connect or Upload. HC-05 programs run with Upload only; the monitor switches to 9600 baud.
+
+ No TinkerBit board answered. Install TinkerBit firmware (MicroPython .bin for ESP32, written at 0x1000): +
+
+ + +
+
+

Console

+

+    
+ +
+
+ Hardware checks (results for RESULTS.md) +
+ + + +
+ +
+
+
+ + + diff --git a/prototypes/micropython/lib/ssd1306.py b/prototypes/micropython/lib/ssd1306.py new file mode 100644 index 00000000000..f00999fbe04 --- /dev/null +++ b/prototypes/micropython/lib/ssd1306.py @@ -0,0 +1,167 @@ +# MicroPython SSD1306 OLED driver, I2C and SPI interfaces. +# Vendored from micropython-lib (MIT licence, micropython/micropython-lib +# micropython/drivers/display/ssd1306/ssd1306.py) because stock ESP32_GENERIC +# firmware does not include it. Stage B freezes the same file via require("ssd1306"). + +from micropython import const +import framebuf + + +# register definitions +SET_CONTRAST = const(0x81) +SET_ENTIRE_ON = const(0xA4) +SET_NORM_INV = const(0xA6) +SET_DISP = const(0xAE) +SET_MEM_ADDR = const(0x20) +SET_COL_ADDR = const(0x21) +SET_PAGE_ADDR = const(0x22) +SET_DISP_START_LINE = const(0x40) +SET_SEG_REMAP = const(0xA0) +SET_MUX_RATIO = const(0xA8) +SET_IREF_SELECT = const(0xAD) +SET_COM_OUT_DIR = const(0xC0) +SET_DISP_OFFSET = const(0xD3) +SET_COM_PIN_CFG = const(0xDA) +SET_DISP_CLK_DIV = const(0xD5) +SET_PRECHARGE = const(0xD9) +SET_VCOM_DESEL = const(0xDB) +SET_CHARGE_PUMP = const(0x8D) + + +# Subclassing FrameBuffer provides support for graphics primitives +# http://docs.micropython.org/en/latest/pyboard/library/framebuf.html +class SSD1306(framebuf.FrameBuffer): + def __init__(self, width, height, external_vcc): + self.width = width + self.height = height + self.external_vcc = external_vcc + self.pages = self.height // 8 + self.buffer = bytearray(self.pages * self.width) + super().__init__(self.buffer, self.width, self.height, framebuf.MONO_VLSB) + self.init_display() + + def init_display(self): + for cmd in ( + SET_DISP, # display off + # address setting + SET_MEM_ADDR, + 0x00, # horizontal + # resolution and layout + SET_DISP_START_LINE, # start at line 0 + SET_SEG_REMAP | 0x01, # column addr 127 mapped to SEG0 + SET_MUX_RATIO, + self.height - 1, + SET_COM_OUT_DIR | 0x08, # scan from COM[N] to COM0 + SET_DISP_OFFSET, + 0x00, + SET_COM_PIN_CFG, + 0x02 if self.width > 2 * self.height else 0x12, + # timing and driving scheme + SET_DISP_CLK_DIV, + 0x80, + SET_PRECHARGE, + 0x22 if self.external_vcc else 0xF1, + SET_VCOM_DESEL, + 0x30, # 0.83*Vcc + # display + SET_CONTRAST, + 0xFF, # maximum + SET_ENTIRE_ON, # output follows RAM contents + SET_NORM_INV, # not inverted + SET_IREF_SELECT, + 0x30, # enable internal IREF during display on + # charge pump + SET_CHARGE_PUMP, + 0x10 if self.external_vcc else 0x14, + SET_DISP | 0x01, # display on + ): # on + self.write_cmd(cmd) + self.fill(0) + self.show() + + def poweroff(self): + self.write_cmd(SET_DISP) + + def poweron(self): + self.write_cmd(SET_DISP | 0x01) + + def contrast(self, contrast): + self.write_cmd(SET_CONTRAST) + self.write_cmd(contrast) + + def invert(self, invert): + self.write_cmd(SET_NORM_INV | (invert & 1)) + + def rotate(self, rotate): + self.write_cmd(SET_COM_OUT_DIR | ((rotate & 1) << 3)) + self.write_cmd(SET_SEG_REMAP | (rotate & 1)) + + def show(self): + x0 = 0 + x1 = self.width - 1 + if self.width != 128: + # narrow displays use centred columns + col_offset = (128 - self.width) // 2 + x0 += col_offset + x1 += col_offset + self.write_cmd(SET_COL_ADDR) + self.write_cmd(x0) + self.write_cmd(x1) + self.write_cmd(SET_PAGE_ADDR) + self.write_cmd(0) + self.write_cmd(self.pages - 1) + self.write_data(self.buffer) + + +class SSD1306_I2C(SSD1306): + def __init__(self, width, height, i2c, addr=0x3C, external_vcc=False): + self.i2c = i2c + self.addr = addr + self.temp = bytearray(2) + self.write_list = [b"\x40", None] # Co=0, D/C#=1 + super().__init__(width, height, external_vcc) + + def write_cmd(self, cmd): + self.temp[0] = 0x80 # Co=1, D/C#=0 + self.temp[1] = cmd + self.i2c.writeto(self.addr, self.temp) + + def write_data(self, buf): + self.write_list[1] = buf + self.i2c.writevto(self.addr, self.write_list) + + +class SSD1306_SPI(SSD1306): + def __init__(self, width, height, spi, dc, res, cs, external_vcc=False): + self.rate = 10 * 1024 * 1024 + dc.init(dc.OUT, value=0) + res.init(res.OUT, value=0) + cs.init(cs.OUT, value=1) + self.spi = spi + self.dc = dc + self.res = res + self.cs = cs + import time + + self.res(1) + time.sleep_ms(1) + self.res(0) + time.sleep_ms(10) + self.res(1) + super().__init__(width, height, external_vcc) + + def write_cmd(self, cmd): + self.spi.init(baudrate=self.rate, polarity=0, phase=0) + self.cs(1) + self.dc(0) + self.cs(0) + self.spi.write(bytearray([cmd])) + self.cs(1) + + def write_data(self, buf): + self.spi.init(baudrate=self.rate, polarity=0, phase=0) + self.cs(1) + self.dc(1) + self.cs(0) + self.spi.write(buf) + self.cs(1) diff --git a/prototypes/micropython/lib/tinkerbit/__init__.py b/prototypes/micropython/lib/tinkerbit/__init__.py new file mode 100644 index 00000000000..ef3034adc5a --- /dev/null +++ b/prototypes/micropython/lib/tinkerbit/__init__.py @@ -0,0 +1,989 @@ +# TinkerBit library: kit parts by jack name. GPIO numbers live only in board.py. +import gc +import json +import os +import sys +import time + +import machine +from machine import Pin + +from . import board + +VERSION = "0.2.0" +API = 2 + +ANALOG_SAMPLES = 12 +DHT_PERIOD_MS = 2000 +MPU_RETRY_MS = 5000 +# A missing RFID reader or heartbeat sensor is looked for again this often. +FIND_AGAIN_MS = 5000 +ULTRA_TIMEOUT_US = 30000 +RFID_SPI_HZ = 1000000 + + +class TinkerBitError(Exception): + pass + + +_parts = {} +_begun = False +_radio = False +_ble = False +_i2c = None +_pwms = [] +_said = {} + + +def _fail(msg): + raise TinkerBitError(msg) + + +def _say_once(key, msg): + if key not in _said: + _said[key] = True + print(msg) + + +def radio(on): + """Tell the library WiFi/Cloud is on or off (tinkerbit.cloud calls this).""" + global _radio + _radio = bool(on) + + +def bluetooth(on): + """Mark Bluetooth on or off. Cloud and Bluetooth never run together.""" + global _ble + if on and _radio: + _fail("Cloud and Bluetooth can't run together. Turn Cloud off first.") + _ble = bool(on) + + +def _wifi_on(): + # Asking network.WLAN() would start the WiFi driver (RAM cost), and built-in modules + # never appear in sys.modules, so only the Cloud flag is checked here. Programs that + # start WiFi themselves get the same message from the OSError that ADC2 raises. + return _radio + + +_RESET_NAMES = ( + ("PWRON_RESET", "power_on"), + ("HARD_RESET", "hard"), + ("WDT_RESET", "watchdog"), + ("DEEPSLEEP_RESET", "deepsleep"), + ("SOFT_RESET", "soft"), +) + + +def _reset_name(): + cause = machine.reset_cause() + for const, name in _RESET_NAMES: + if getattr(machine, const, None) == cause: + return name + return str(cause) + + +def info(): + try: + st = os.statvfs("/") + flash_free = st[0] * st[3] + except Exception: + flash_free = -1 + try: + import tbsys # only in TinkerBit firmware (Stage B) + + fw = "tinkerbit" + except ImportError: + fw = "stock" + gc.collect() + data = { + "board": board.BOARD, + "rev": board.REV, + "mcu": board.MCU, + "lib": VERSION, + "api": API, + "jacks": len(board.JACKS), + "uid": "".join("%02x" % b for b in machine.unique_id()), + "mpy": ".".join(str(n) for n in sys.implementation.version[:3]), + "fw": fw, + "flash_free": flash_free, + "heap_free": gc.mem_free(), + "reset": _reset_name(), + "up_ms": time.ticks_ms(), + } + print("TB_INFO " + json.dumps(data)) + + +def begin(): + """Put every output in a safe state. Safe to call more than once.""" + global _begun + for name in board.SAFE_HIGH: + for gpio in board.JACKS[name]["pins"].values(): + Pin(gpio, Pin.OUT, value=1) + _begun = True + + +def stop_all(): + """Turn off motors, buzzer, LEDs and pumps, release the relays, stop PWM and the Cloud.""" + cloud = sys.modules.get("tinkerbit.cloud") + if cloud and cloud._started: + try: + cloud.end() + except Exception as e: + print("stop_all:", e) + for part in list(_parts.values()): + try: + part._stop() + except Exception as e: + print("stop_all:", e) + while _pwms: + try: + _pwms.pop().deinit() + except Exception: + pass + begin() + + +def _bus_of(jack): + return board.JACKS[jack].get("bus", jack) + + +def _check(cls, jack): + spec = board.jack(jack) + if spec is None: + _fail("There is no jack called {}. Jacks: {}".format(jack, ", ".join(board.JACK_NAMES))) + kind = spec["kind"] + if kind not in cls.KINDS: + if kind == "ultra": + _fail("D5 is only for the distance sensor (HC-SR04). Plug the {} into {}.".format(cls.NAME, cls.WHERE)) + _fail("The {} can't go on {}. Use {}.".format(cls.NAME, jack, cls.WHERE)) + if cls.ANALOG and not spec.get("adc2"): + _fail("The {} needs an A jack ({}).".format(cls.NAME, cls.WHERE)) + for other in spec.get("shares", ()): + if other in _parts: + _fail("{} and {} can't be used together (they share a wire). Unplug one.".format(jack, other)) + if spec.get("adc2") and _wifi_on(): + _fail("A ports are off while Cloud/WiFi is on. Move the {} to D13, or turn Cloud off.".format(cls.NAME)) + if spec.get("boot"): + _say_once(jack, "Note: A4 is the BOOT pin. If the board will not start, unplug the {} from A4.".format(cls.NAME)) + + +class _Part: + KINDS = ("io",) + DEFAULT = "D13" + NAME = "part" + WHERE = "D13 or A1-A4" + ANALOG = False + SHARED_BUS = False + + def __new__(cls, jack=None): + jack = jack or cls.DEFAULT + # Parts on the shared I2C bus are cached per bus and type (I2C and I2C1 are the same + # wires); every other part owns its jack. + key = (_bus_of(jack), cls.__name__) if cls.SHARED_BUS and jack in board.JACKS else jack + part = _parts.get(key) + if part is not None: + if type(part) is cls: + return part + _fail("{} already has the {}. One part per jack: pick another jack.".format(jack, part.NAME)) + _check(cls, jack) + if not _begun: + begin() + part = object.__new__(cls) + part.jack = jack + part._setup() + _parts[key] = part + return part + + def __init__(self, jack=None): + pass + + def _gpio(self, role="sig"): + return board.pin(self.jack, role) + + def _setup(self): + pass + + def _stop(self): + pass + + def __repr__(self): + return "<{} on {}>".format(self.NAME, self.jack) + + +class _Output(_Part): + OFF_AT_START = True + + def _setup(self): + self._pin = Pin(self._gpio(), Pin.OUT, value=0) + self._pwm = None + + def on(self): + self._write(1) + + def off(self): + self._write(0) + + def value(self): + return self._pin.value() + + def _write(self, v): + if self._pwm is not None: + self._pwm.duty_u16(65535 if v else 0) + else: + self._pin.value(1 if v else 0) + + def _stop(self): + if self._pwm is not None: + try: + self._pwm.deinit() + except Exception: + pass + if self._pwm in _pwms: + _pwms.remove(self._pwm) + self._pwm = None + self._pin = Pin(self._gpio(), Pin.OUT, value=0) + self._pin.value(0) + + +class Led(_Output): + NAME = "LED" + + def toggle(self): + self._write(0 if self.value() else 1) + + def brightness(self, level): + level = max(0, min(255, int(level))) + if self._pwm is None: + self._pwm = machine.PWM(self._pin, freq=1000, duty_u16=0) + _pwms.append(self._pwm) + self._pwm.duty_u16(level * 257) + + def blink(self, ms=500, times=1): + for _ in range(int(times)): + self.on() + time.sleep_ms(int(ms)) + self.off() + time.sleep_ms(int(ms)) + + +BOOT_FILE = "/tb_boot.json" +_boot_off = None + + +def _remember_off_at_boot(jack): + """Record a jack that must stay LOW from power-up (pump, lock, buzzer); boot.py reads + the file. The first part of a run replaces the old list, so unplugged parts drop out. + The file is only written when the list changes, to spare the flash.""" + global _boot_off + try: + with open(BOOT_FILE) as f: + saved = json.load(f).get("off", []) + except (OSError, ValueError): + saved = [] + if _boot_off is None: + _boot_off = [] + if jack not in _boot_off: + _boot_off.append(jack) + if sorted(saved) != sorted(_boot_off): + try: + with open(BOOT_FILE, "w") as f: + json.dump({"off": sorted(_boot_off)}, f) + except OSError as e: + print("Could not save the boot settings:", e) + + +class _KeepOffOutput(_Output): + """Outputs that must never run while the board starts (they draw power or move things).""" + + def _setup(self): + _Output._setup(self) + _remember_off_at_boot(self.jack) + + +class Buzzer(_KeepOffOutput): + NAME = "buzzer" + + def beep(self, ms=200): + self.on() + time.sleep_ms(int(ms)) + self.off() + + def tone(self, freq=1000): + """Play a note (for a passive buzzer) until no_tone() or stop.""" + freq = max(31, min(20000, int(freq))) + if self._pwm is None: + self._pwm = machine.PWM(self._pin, freq=freq, duty_u16=32768) + _pwms.append(self._pwm) + else: + self._pwm.freq(freq) + self._pwm.duty_u16(32768) + + def no_tone(self): + self._stop() + + +class Relay(_Output): + NAME = "relay" + + +class Pump(_KeepOffOutput): + NAME = "water pump" + + +class Lock(_KeepOffOutput): + """Solenoid door lock: open() for a few seconds at a time (it heats up).""" + NAME = "door lock" + + def open(self): + self.on() + + def close(self): + self.off() + + +class Servo(_Part): + NAME = "servo" + FREQ = 50 + MIN_US = 500 + MAX_US = 2400 + + def _setup(self): + self._pwm = machine.PWM(Pin(self._gpio()), freq=self.FREQ, duty_ns=0) + _pwms.append(self._pwm) + self._angle = None + self.angle(90) + + def angle(self, degrees=None): + """Move to 0-180 degrees; with no argument, the last angle set.""" + if degrees is None: + return self._angle + degrees = max(0, min(180, int(degrees))) + if self._pwm is None: + self._setup() + us = self.MIN_US + (self.MAX_US - self.MIN_US) * degrees // 180 + self._pwm.duty_ns(us * 1000) + self._angle = degrees + return degrees + + def _stop(self): + # No pulses: the arm goes limp, as after a reset. + if self._pwm is not None: + try: + self._pwm.deinit() + except Exception: + pass + if self._pwm in _pwms: + _pwms.remove(self._pwm) + self._pwm = None + + +class Motors(_Part): + """L293D on MD: motor A and motor B, speed 0-255 forward or backward.""" + NAME = "motor driver" + KINDS = ("motor",) + DEFAULT = "MD" + WHERE = "MD" + FREQ = 1000 + PINS = {"A": ("a1", "a2"), "B": ("b1", "b2")} + + def _setup(self): + self._pwm = {} + for role in ("a1", "a2", "b1", "b2"): + pwm = machine.PWM(Pin(self._gpio(role)), freq=self.FREQ, duty_u16=0) + self._pwm[role] = pwm + _pwms.append(pwm) + + def speed(self, motor="A", speed=180, forward=True): + if not self._pwm: + self._setup() + motor = "B" if str(motor).upper() == "B" else "A" + duty = max(0, min(255, int(speed))) * 257 + fwd, back = self.PINS[motor] + self._pwm[fwd].duty_u16(duty if forward else 0) + self._pwm[back].duty_u16(0 if forward else duty) + + def stop(self): + for pwm in self._pwm.values(): + pwm.duty_u16(0) + + def _stop(self): + for pwm in self._pwm.values(): + try: + pwm.deinit() + except Exception: + pass + if pwm in _pwms: + _pwms.remove(pwm) + self._pwm = {} + + +class Relay4(_Part): + """4-channel relay board on MD. Active-low: a channel is on while its pin is LOW.""" + NAME = "4-channel relay" + KINDS = ("motor",) + DEFAULT = "MD" + WHERE = "MD" + ROLES = ("a1", "a2", "b1", "b2") + + def _setup(self): + self._pins = [Pin(self._gpio(role), Pin.OUT, value=1) for role in self.ROLES] + + def channel(self, number, on=True): + number = max(1, min(4, int(number))) + self._pins[number - 1].value(0 if on else 1) + + def all(self, on=False): + for p in self._pins: + p.value(0 if on else 1) + + def _stop(self): + self.all(False) + + +class Stepper(_Part): + """4-wire stepper on ST, same step order as the Arduino Stepper library (200 steps a turn). + ST has a strapping pin (see board.py): the coils are left off after every move.""" + NAME = "stepper motor" + KINDS = ("stepper",) + DEFAULT = "ST" + WHERE = "ST" + STEPS_PER_TURN = 200 + SEQUENCE = ((1, 0, 1, 0), (0, 1, 1, 0), (0, 1, 0, 1), (1, 0, 0, 1)) + + def _setup(self): + self._pins = [Pin(self._gpio(role), Pin.OUT, value=0) for role in ("in1", "in2", "in3", "in4")] + self._phase = 0 + + def move(self, steps=100, rpm=12): + """Turn by steps (negative = backward) at rpm (1-60).""" + steps = int(steps) + rpm = max(1, min(60, int(rpm))) + delay_us = 60 * 1000000 // (self.STEPS_PER_TURN * rpm) + direction = 1 if steps >= 0 else -1 + try: + for _ in range(abs(steps)): + self._phase = (self._phase + direction) % 4 + for pin, level in zip(self._pins, self.SEQUENCE[self._phase]): + pin.value(level) + time.sleep_us(delay_us) + finally: + self._stop() + + def _stop(self): + for pin in self._pins: + pin.value(0) + + +class Button(_Part): + NAME = "button" + + def _setup(self): + self._pin = Pin(self._gpio(), Pin.IN, Pin.PULL_UP) + + def pressed(self): + return self._pin.value() == 0 + + +class _Detector(_Part): + """On/off sensor with a digital output; ACTIVE_LOW parts pull it LOW when they detect.""" + ACTIVE_LOW = False + + def _setup(self): + self._pin = Pin(self._gpio(), Pin.IN) + + def detected(self): + return self._pin.value() == (0 if self.ACTIVE_LOW else 1) + + +class Obstacle(_Detector): + NAME = "IR obstacle sensor" + ACTIVE_LOW = True + + +class Pir(_Detector): + """PIR motion sensor: it settles about a minute after power-up.""" + NAME = "PIR motion sensor" + + +class Reed(_Detector): + NAME = "reed switch" + ACTIVE_LOW = True + + +class Light(_Detector): + """LDR module: detected() is True when it is dark (its screw sets how dark).""" + NAME = "light sensor" + + +class Flame(_Detector): + NAME = "flame sensor" + ACTIVE_LOW = True + + +class Pot(_Part): + NAME = "potentiometer" + DEFAULT = "A1" + WHERE = "A1-A4" + ANALOG = True + + def _setup(self): + self._adc = machine.ADC(Pin(self._gpio()), atten=machine.ADC.ATTN_11DB) + + def raw(self): + """One 0-4095 reading, averaged over ANALOG_SAMPLES.""" + if _wifi_on(): + _fail("A ports are off while Cloud/WiFi is on. Turn Cloud off to read the {}.".format(self.NAME)) + total = 0 + try: + for _ in range(ANALOG_SAMPLES): + total += self._adc.read_u16() >> 4 + time.sleep_us(100) + except OSError: + _fail("A ports are off while Cloud/WiFi is on. Turn Cloud off to read the {}.".format(self.NAME)) + return total // ANALOG_SAMPLES + + def read(self): + return self.raw() + + +class Mic(Pot): + NAME = "microphone" + + +class Gas(Pot): + NAME = "MQ-2 gas sensor" + + +class Water(Pot): + NAME = "water level sensor" + + +class Soil(Pot): + NAME = "soil sensor" + DRY = 3200 + WET = 1200 + + def percent(self): + """0 % dry to 100 % wet; -1 when the reading looks like a loose cable.""" + return self.percent_from(self.raw()) + + def percent_from(self, raw): + if raw < 50: + return -1 + pct = (self.DRY - raw) * 100 // (self.DRY - self.WET) + return max(0, min(100, pct)) + + def read(self): + return self.percent() + + +class Ultrasonic(_Part): + NAME = "distance sensor" + KINDS = ("ultra",) + DEFAULT = "D5" + WHERE = "D5" + + def _setup(self): + self._trig = Pin(self._gpio("trig"), Pin.OUT, value=0) + # Echo stays an input: driving it heats the module. + self._echo = Pin(self._gpio("echo"), Pin.IN) + + def cm(self): + """Distance in cm (2-400), or -1 when there is no valid echo.""" + self._trig.value(0) + time.sleep_us(2) + self._trig.value(1) + time.sleep_us(10) + self._trig.value(0) + us = machine.time_pulse_us(self._echo, 1, ULTRA_TIMEOUT_US) + if us <= 0: + return -1 + cm = us // 58 + return cm if 2 <= cm <= 400 else -1 + + def read(self): + return self.cm() + + +def _time_to_look(part): + """True when a missing part should be looked for now (at most every FIND_AGAIN_MS).""" + now = time.ticks_ms() + if part._looked_at is not None and time.ticks_diff(now, part._looked_at) < FIND_AGAIN_MS: + return False + part._looked_at = now + return True + + +class Rfid(_Part): + """RC522 card reader on 3D.""" + NAME = "RFID reader" + KINDS = ("spi",) + DEFAULT = "3D" + WHERE = "3D" + + def _setup(self): + self._ss = Pin(self._gpio("ss"), Pin.OUT, value=1) + self._rst = Pin(self._gpio("rst"), Pin.OUT, value=1) + self._dev = None + self._looked_at = None + + def _reader(self): + if self._dev is None and _time_to_look(self): + from .rc522 import RC522 + + spi = machine.SPI(2, baudrate=RFID_SPI_HZ, polarity=0, phase=0, sck=Pin(self._gpio("sck")), + mosi=Pin(self._gpio("mosi")), miso=Pin(self._gpio("miso"))) + dev = RC522(spi, self._ss, self._rst) + if dev.begin(): + self._dev = dev + else: + _say_once("rfid", "RFID reader not found - check the 3D cable.") + return self._dev + + def card(self): + """The UID of a card just put on the reader, as hex ("04a3b2c1"), else "". + A card left on the reader is read once.""" + dev = self._reader() + if dev is None: + return "" + uid = dev.read_uid() + if uid is None: + if not dev.present(): + self._dev = None + self._looked_at = time.ticks_ms() + return "" + return "".join("%02x" % b for b in uid) + + def read(self): + return self.card() + + +class DHT11(_Part): + NAME = "DHT11" + DEFAULT = "A1" + + def _setup(self): + import dht + self._dev = dht.DHT11(Pin(self._gpio())) + self._at = None + self._t = -1 + self._h = -1 + + def _measure(self): + now = time.ticks_ms() + if self._at is not None and time.ticks_diff(now, self._at) < DHT_PERIOD_MS: + return + self._at = now + try: + self._dev.measure() + self._t = self._dev.temperature() + self._h = self._dev.humidity() + except OSError: + self._t = -1 + self._h = -1 + _say_once("dht", "DHT11 not answering: plug it into A1 and check the cable.") + + def temperature(self): + self._measure() + return self._t + + def humidity(self): + self._measure() + return self._h + + def read(self): + return self.temperature() + + +def i2c(): + """The shared I2C bus (I2C and I2C1 jacks), created once at 100 kHz.""" + global _i2c + if _i2c is None: + pins = board.JACKS["I2C"]["pins"] + _i2c = machine.I2C(0, scl=Pin(pins["scl"]), sda=Pin(pins["sda"]), freq=board.I2C_FREQ) + return _i2c + + +class _I2CPart(_Part): + KINDS = ("i2c",) + DEFAULT = "I2C" + WHERE = "I2C or I2C1" + SHARED_BUS = True + + +class Oled(_I2CPart): + NAME = "OLED screen" + ADDR = 0x3C + + def _setup(self): + self._dev = None + self._lines = [""] * 8 + + def _screen(self): + if self._dev is None: + import ssd1306 + try: + self._dev = ssd1306.SSD1306_I2C(128, 64, i2c(), addr=self.ADDR) + except OSError: + _fail("OLED screen not found on I2C: check the cable.") + return self._dev + + def text(self, message, line=0): + line = max(0, min(7, int(line))) + self._lines[line] = str(message)[:16] + self._draw() + + def number(self, value, line=0): + self.text(value, line) + + def show(self, message): + """Clear the screen and write the message from the top, wrapping every 16 characters.""" + s = str(message) + self._lines = [s[i * 16:(i + 1) * 16] for i in range(8)] + self._draw() + + def clear(self): + self._lines = [""] * 8 + self._draw() + + def _draw(self): + dev = self._screen() + dev.fill(0) + for i, s in enumerate(self._lines): + if s: + dev.text(s, 0, i * 8) + dev.show() + + +class Motion(_I2CPart): + """MPU6050 with plain I2C reads (same math as Beginner Studio).""" + NAME = "MPU6050" + + def _setup(self): + self._addr = 0x68 + self._ready = False + self._retry_at = None + self._tilt = 0 + self._shake = -1 + + def _write(self, reg, value): + i2c().writeto_mem(self._addr, reg, bytes([value])) + + def _begin(self): + for addr in (0x68, 0x69): + self._addr = addr + try: + # Wake up, +-2 g, +-250 deg/s, 44 Hz filter. + self._write(0x6B, 0) + self._write(0x1C, 0) + self._write(0x1B, 0) + self._write(0x1A, 3) + time.sleep_ms(50) + return True + except OSError: + pass + self._addr = 0x68 + return False + + def _sample(self): + if not self._ready: + now = time.ticks_ms() + if self._retry_at is not None and time.ticks_diff(now, self._retry_at) < MPU_RETRY_MS: + return None + self._retry_at = now + self._ready = self._begin() + if not self._ready: + _say_once("mpu", "MPU6050 not found - check the I2C cable") + return None + try: + raw = i2c().readfrom_mem(self._addr, 0x3B, 14) + except OSError: + self._ready = False + self._retry_at = time.ticks_ms() + return None + v = [] + for i in range(7): + n = (raw[2 * i] << 8) | raw[2 * i + 1] + v.append(n - 65536 if n & 0x8000 else n) + return (v[0] / 16384, v[1] / 16384, v[2] / 16384, v[4] / 131, v[5] / 131, v[6] / 131) + + def update(self): + import math + sx = sy = sz = 0.0 + peak = 0.0 + n = 0 + for _ in range(10): + s = self._sample() + if s is not None: + sx += s[0] + sy += s[1] + sz += s[2] + g = math.sqrt(s[0] * s[0] + s[1] * s[1] + s[2] * s[2]) + spin = math.sqrt(s[3] * s[3] + s[4] * s[4] + s[5] * s[5]) + jolt = abs(g - 1.0) * 100 + spin / 5 + if jolt > peak: + peak = jolt + n += 1 + elif not self._ready: + break + time.sleep_ms(5) + if not n: + self._tilt = 0 + self._shake = -1 + return + self._tilt = int(round(math.atan2(sx, math.sqrt(sy * sy + sz * sz)) * 57.2958)) + self._shake = int(min(100.0, peak)) + + def tilt(self): + self.update() + return self._tilt + + def shake(self): + self.update() + return self._shake + + def read(self): + """(tilt, shake) from one measurement; shake is -1 when the sensor is not answering.""" + self.update() + return self._tilt, self._shake + + +class Heartbeat(_I2CPart): + """HW-605 (MAX30102) pulse sensor: put a fingertip on it and keep still.""" + NAME = "heartbeat sensor" + # IR below this means no finger on the sensor (same rule as the Arduino code). + NO_FINGER = 50000 + # SparkFun's getIR() waits this long for a new sample. + WAIT_MS = 250 + + def _setup(self): + self._dev = None + self._looked_at = None + self._bpm = 0 + + def _sensor(self): + if self._dev is None and _time_to_look(self): + from .max30102 import MAX30102, BeatDetector + + dev = MAX30102(i2c()) + try: + found = dev.begin() + except OSError: + found = False + if found: + self._dev = dev + self._beats = BeatDetector() + self._count = 0 + self._last_beat = None + else: + _say_once("pulse", "Heartbeat sensor (HW-605) not found - check the I2C cable and 3.3V.") + return self._dev + + def bpm(self): + """Beats per minute from the last two beats; 0 with no finger on the sensor, -1 while + the sensor is not answering.""" + from .max30102 import SAMPLE_MS + + dev = self._sensor() + if dev is None: + return -1 + try: + samples, lost = dev.read_ir() + end = time.ticks_add(time.ticks_ms(), self.WAIT_MS) + while not samples and time.ticks_diff(end, time.ticks_ms()) > 0: + time.sleep_ms(SAMPLE_MS) + samples, lost = dev.read_ir() + except OSError: + self._dev = None + self._looked_at = time.ticks_ms() + return -1 + # Beats are timed by sample number (one every SAMPLE_MS), so a slow loop does not skew them. + self._count += lost + for ir in samples: + self._count += 1 + if self._beats.check(ir): + if self._last_beat is not None: + self._bpm = 60000 // ((self._count - self._last_beat) * SAMPLE_MS) + self._last_beat = self._count + if samples and samples[-1] < self.NO_FINGER: + self._bpm = 0 + return self._bpm + + def read(self): + return self.bpm() + + +class HC05(_Part): + """HC-05 on the UART jack. It shares UART0 with USB serial and the REPL, so a program + that uses it runs from Upload only and Stop needs a hard reset.""" + NAME = "HC-05" + KINDS = ("uart",) + DEFAULT = "UART" + WHERE = "UART" + BAUD = 9600 + + def _setup(self): + import micropython + import select + # Bytes from the phone must reach the program, not stop it. + micropython.kbd_intr(-1) + # Only the baud rate changes: the REPL keeps the UART and its receive buffer, + # so reads go through sys.stdin. + machine.UART(board.JACKS[self.jack]["uart"], baudrate=self.BAUD) + self._poll = select.poll() + self._poll.register(sys.stdin, select.POLLIN) + self._buf = "" + + def send(self, text): + sys.stdout.write(str(text) + "\n") + + def read_line(self): + """The next full line from the phone, or None when nothing complete arrived yet.""" + while self._poll.poll(0): + ch = sys.stdin.read(1) + if not ch: + break + if ch == "\n": + line, self._buf = self._buf.strip("\r"), "" + return line + self._buf += ch + return None + + +class Ble(_Part): + """Bluetooth LE built into the board, with the service phone apps used with the Arduino + code. Cloud and Bluetooth never run together.""" + NAME = "Bluetooth" + KINDS = ("onboard",) + DEFAULT = "ESP" + WHERE = "ESP (built in)" + + def _setup(self): + self._dev = None + self._peripheral() + + def _peripheral(self): + if self._dev is None: + bluetooth(True) + from .ble import Peripheral + + self._dev = Peripheral() + return self._dev + + def advertise(self, name="TinkerBit"): + """Show up on phones as name (up to 29 bytes).""" + self._peripheral().advertise(name) + + def send(self, text): + """Send text to a connected phone (the first 20 bytes).""" + return self._peripheral().send(text) + + def connected(self): + return self._dev is not None and self._dev.connected() + + def _stop(self): + if self._dev is not None: + self._dev.close() + self._dev = None + bluetooth(False) diff --git a/prototypes/micropython/lib/tinkerbit/ble.py b/prototypes/micropython/lib/tinkerbit/ble.py new file mode 100644 index 00000000000..18e91c17f75 --- /dev/null +++ b/prototypes/micropython/lib/tinkerbit/ble.py @@ -0,0 +1,97 @@ +# Bluetooth LE peripheral with the same service as Beginner Studio's Arduino code, so phone +# apps that worked with it keep working: one characteristic (read, write, notify), at most +# 20 bytes a value, starting at "ready". +import bluetooth + +SERVICE = "4fafc201-1fb5-459e-8fcc-c5c9c331914b" +CHARACTERISTIC = "beb5483e-36e1-4688-b7f5-ea07361b26a8" +VALUE_MAX = 20 +NAME_MAX = 29 + +_FLAG_READ = 0x0002 +_FLAG_WRITE = 0x0008 +_FLAG_NOTIFY = 0x0010 + +_IRQ_CENTRAL_CONNECT = 1 +_IRQ_CENTRAL_DISCONNECT = 2 + +_ADV_INTERVAL_US = 100000 + + +def _field(kind, value): + return bytes((len(value) + 1, kind)) + value + + +def clip_utf8(text, limit): + """text as UTF-8, at most limit bytes, never cut inside a character.""" + data = str(text).encode() + if len(data) <= limit: + return data + end = limit + while end > 0 and data[end] & 0xC0 == 0x80: + end -= 1 + return data[:end] + + +class Peripheral: + def __init__(self): + self._ble = bluetooth.BLE() + self._ble.active(True) + self._ble.irq(self._irq) + ((self._handle,),) = self._ble.gatts_register_services(( + (bluetooth.UUID(SERVICE), ((bluetooth.UUID(CHARACTERISTIC), _FLAG_READ | _FLAG_WRITE | _FLAG_NOTIFY),)), + )) + self._ble.gatts_write(self._handle, b"ready") + self._conns = set() + self._name = None + self._advertising = False + + def _irq(self, event, data): + if event == _IRQ_CENTRAL_CONNECT: + self._conns.add(data[0]) + self._advertising = False + elif event == _IRQ_CENTRAL_DISCONNECT: + self._conns.discard(data[0]) + if self._name is not None: + self._advertise() + + def _advertise(self): + name = clip_utf8(self._name, NAME_MAX) + self._ble.config(gap_name=name) + adv = _field(0x01, b"\x06") + _field(0x07, bytes(bluetooth.UUID(SERVICE))) + # The name goes in the scan response: next to the 128-bit service UUID it would only fit 8 bytes. + self._ble.gap_advertise(_ADV_INTERVAL_US, adv_data=adv, resp_data=_field(0x09, name)) + self._advertising = True + + def advertise(self, name): + """Show up on phones as name. A connected phone stays connected; a new name + shows after it disconnects.""" + name = str(name) + if name == self._name and (self._advertising or self._conns): + return + self._name = name + if not self._conns: + self._advertise() + + def send(self, text): + """Set the value (first 20 bytes) and notify connected phones.""" + data = clip_utf8(text, VALUE_MAX) + self._ble.gatts_write(self._handle, data) + for conn in list(self._conns): + try: + self._ble.gatts_notify(conn, self._handle, data) + except OSError: + self._conns.discard(conn) + return data + + def connected(self): + return bool(self._conns) + + def close(self): + try: + self._ble.gap_advertise(None) + except OSError: + pass + self._ble.active(False) + self._conns = set() + self._advertising = False diff --git a/prototypes/micropython/lib/tinkerbit/board.py b/prototypes/micropython/lib/tinkerbit/board.py new file mode 100644 index 00000000000..1cb6bad07b5 --- /dev/null +++ b/prototypes/micropython/lib/tinkerbit/board.py @@ -0,0 +1,51 @@ +# TinkerBit Maker ESP32 RJ11 hub: the only file that knows GPIO numbers. +# Source of truth: ARCHITECTURE.md section 3 (jack map and rules). + +BOARD = "TinkerBit Maker ESP32" +REV = "rj11-1" +MCU = "ESP32-WROOM-32" + +# I2C runs at 100 kHz: the MAX30102 heartbeat sensor fails at 400 kHz. +I2C_FREQ = 100000 + +# kind: what the jack can carry. +# io one signal wire: on/off parts, PWM, DHT (D13 and A1-A4) +# ultra HC-SR04 only (trig + echo) +# i2c shared I2C bus +# spi RFID RC522 +# motor L293D or 4-ch relay (active-low) +# stepper 4-wire stepper +# uart HC-05, shares UART0 with USB serial and the REPL +# onboard BLE / WiFi, no wire +# adc2: the jack reads through ADC2, which stops working while WiFi is on. +# strap: a strapping pin, its level at reset changes how the chip boots. +# boot: GPIO 0, holding it LOW at reset enters download mode. +JACKS = { + "D13": {"kind": "io", "pins": {"sig": 33}, "shares": ("3D",)}, + "3D": {"kind": "spi", "pins": {"ss": 32, "rst": 33, "miso": 34, "sck": 16, "mosi": 23}, "shares": ("D13",)}, + "D5": {"kind": "ultra", "pins": {"trig": 26, "echo": 25}}, + "ST": {"kind": "stepper", "pins": {"in1": 12, "in2": 13, "in3": 14, "in4": 27}, "strap": True}, + "MD": {"kind": "motor", "pins": {"a1": 17, "a2": 5, "b1": 18, "b2": 19}, "active_low": True}, + "I2C": {"kind": "i2c", "pins": {"sda": 21, "scl": 22}, "bus": "I2C"}, + "I2C1": {"kind": "i2c", "pins": {"sda": 21, "scl": 22}, "bus": "I2C"}, + "A1": {"kind": "io", "pins": {"sig": 4}, "adc2": True}, + "A2": {"kind": "io", "pins": {"sig": 15}, "adc2": True, "strap": True}, + "A3": {"kind": "io", "pins": {"sig": 2}, "adc2": True, "strap": True}, + "A4": {"kind": "io", "pins": {"sig": 0}, "adc2": True, "strap": True, "boot": True}, + "UART": {"kind": "uart", "pins": {"rx": 3, "tx": 1}, "uart": 0}, + "ESP": {"kind": "onboard", "pins": {}}, +} + +# Pins driven HIGH at begin() and stop_all(): the 4-ch relay is active-low, and HIGH on +# both L293D inputs brakes the motors. +SAFE_HIGH = ("MD",) + +JACK_NAMES = tuple(JACKS) + + +def jack(name): + return JACKS.get(name) + + +def pin(name, role="sig"): + return JACKS[name]["pins"][role] diff --git a/prototypes/micropython/lib/tinkerbit/cloud.py b/prototypes/micropython/lib/tinkerbit/cloud.py new file mode 100644 index 00000000000..a54df131636 --- /dev/null +++ b/prototypes/micropython/lib/tinkerbit/cloud.py @@ -0,0 +1,226 @@ +# TinkerBit Cloud (Stage B firmware): WiFi from Python, MQTT over TLS in the tbcloud C module. +# Same topics, telemetry, dashboard controls, alerts and printed checklist lines as the +# Arduino Cloud firmware. Settings and secrets come from /config.json on the board, never +# from main.py, and are never printed. See README.md for the file format. +import json + +import tinkerbit + +CONFIG = "/config.json" +FW = "mpy-1" +INTERVAL_S = 10 +MIN_INTERVAL_S = 5 + +# Let's Encrypt roots (ISRG Root X1 and X2), same as Beginner Studio's cloudCerts.js. +ISRG_ROOTS = """-----BEGIN CERTIFICATE----- +MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw +TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh +cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4 +WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu +ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY +MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc +h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+ +0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U +A5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sW +T8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyH +B5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UC +B5iPNgiV5+I3lg02dZ77DnKxHZu8A/lJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUv +KBds0pjBqAlkd25HN7rOrFleaJ1/ctaJxQZBKT5ZPt0m9STJEadao0xAH0ahmbWn +OlFuhjuefXKnEgV4We0+UXgVCwOPjdAvBbI+e0ocS3MFEvzG6uBQE3xDk3SzynTn +jh8BCNAw1FtxNrQHusEwMFxIt4I7mKZ9YIqioymCzLq9gwQbooMDQaHWBfEbwrbw +qHyGO0aoSCqI3Haadr8faqU9GY/rOPNk3sgrDQoo//fb4hVC1CLQJ13hef4Y53CI +rU7m2Ys6xt0nUW7/vGT1M0NPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV +HRMBAf8EBTADAQH/MB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkq +hkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaS/V9lZL +ubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ +3BebYhtF8GaV0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KK +NFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5 +ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7Ur +TkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdC +jNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc +oyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq +4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA +mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d +emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc= +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIICGzCCAaGgAwIBAgIQQdKd0XLq7qeAwSxs6S+HUjAKBggqhkjOPQQDAzBPMQsw +CQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJuZXQgU2VjdXJpdHkgUmVzZWFyY2gg +R3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBYMjAeFw0yMDA5MDQwMDAwMDBaFw00 +MDA5MTcxNjAwMDBaME8xCzAJBgNVBAYTAlVTMSkwJwYDVQQKEyBJbnRlcm5ldCBT +ZWN1cml0eSBSZXNlYXJjaCBHcm91cDEVMBMGA1UEAxMMSVNSRyBSb290IFgyMHYw +EAYHKoZIzj0CAQYFK4EEACIDYgAEzZvVn4CDCuwJSvMWSj5cz3es3mcFDR0HttwW ++1qLFNvicWDEukWVEYmO6gbf9yoWHKS5xcUy4APgHoIYOIvXRdgKam7mAHf7AlF9 +ItgKbppbd9/w+kHsOdx1ymgHDB/qo0IwQDAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0T +AQH/BAUwAwEB/zAdBgNVHQ4EFgQUfEKWrt5LSDv6kviejM9ti6lyN5UwCgYIKoZI +zj0EAwMDaAAwZQIwe3lORlCEwkSHRhtFcP9Ymd70/aTSVaYgLXTWNLxBo1BfASdW +tL4ndQavEi51mI38AjEAi/V3bNTIZargCyzuFJ0nN6T5U6VR5CmD1/iQMVtCnwr1 +/q4AaOeMSQ+2b1tbFfLn +-----END CERTIFICATE----- +""" + +STATES = ("stopped", "waiting for WiFi", "connecting", "connected") + +_started = False +_wlan = None + + +def _config(): + try: + with open(CONFIG) as f: + cfg = json.load(f) + except OSError: + raise tinkerbit.TinkerBitError("Cloud settings missing: put config.json on the board (see README).") + except ValueError: + raise tinkerbit.TinkerBitError("config.json is not valid JSON.") + for key in ("wifi_ssid", "host", "device_id"): + if not cfg.get(key): + raise tinkerbit.TinkerBitError("config.json needs '%s'." % key) + return cfg + + +def _ca(cfg): + path = cfg.get("ca_file") + if not path: + return ISRG_ROOTS + with open(path) as f: + return f.read() + + +def _seconds(value, default, low): + try: + n = int(round(float(value))) + except (TypeError, ValueError): + return default + return max(low, min(3600, n)) + + +def begin(ssid=None, pw=None, host=None, device_id=None, token=None): + """Start WiFi and the cloud connection. Missing arguments come from /config.json.""" + global _started, _wlan + try: + import tbcloud + except ImportError: + raise tinkerbit.TinkerBitError("Cloud needs TinkerBit firmware (Stage B).") + if tinkerbit._ble: + raise tinkerbit.TinkerBitError("Cloud and Bluetooth can't run together. Turn Bluetooth off first.") + for part in tinkerbit._parts.values(): + spec = tinkerbit.board.jack(part.jack) or {} + if spec.get("adc2"): + raise tinkerbit.TinkerBitError("A ports are off while Cloud/WiFi is on. Move the {} from {} to D13.".format(part.NAME, part.jack)) + cfg = _config() if None in (ssid, host, device_id) else {} + ssid = ssid or cfg["wifi_ssid"] + pw = pw if pw is not None else cfg.get("wifi_password", "") + host = host or cfg["host"] + device_id = device_id or cfg["device_id"] + token = token if token is not None else cfg.get("token", "") + min_gap = _seconds(cfg.get("min_interval_sec"), MIN_INTERVAL_S, 1) + interval = _seconds(cfg.get("interval_sec"), INTERVAL_S, min_gap) + + import network + + print('Cloud: joining WiFi "%s"' % ssid) + tinkerbit.radio(True) + _wlan = network.WLAN(network.STA_IF) + _wlan.active(True) + try: + # Modem sleep delays incoming packets and can miss broker pings. + _wlan.config(pm=_wlan.PM_NONE) + except Exception: + pass + # Started before connect() so the WiFi events (wrong password, name not found) are seen. + tbcloud.start( + host, + int(cfg.get("port", 8883)), + int(cfg.get("ws_port", 443)), + device_id, + token, + _ca(cfg), + ws_path=cfg.get("ws_path", "/mqtt"), + interval_ms=interval * 1000, + min_gap_ms=min_gap * 1000, + fw=FW, + ) + _started = True + if pw: + _wlan.connect(ssid, pw) + else: + _wlan.connect(ssid) + + +def _cloud(): + if not _started: + raise tinkerbit.TinkerBitError("Call cloud.begin() first.") + import tbcloud + + return tbcloud + + +def set(name, value): + """Report a reading on the dashboard (number or True/False; None stops reporting it). + The board sends every reading on its interval, even while the program waits.""" + return _cloud().set(name, value) + + +def send(values=None): + """Set several readings and send them as soon as the minimum gap allows. + Returns False while not connected (the values still go out once it connects).""" + c = _cloud() + for name, value in (values or {}).items(): + c.set(name, value) + c.send_now() + return connected() + + +def alert(text): + """Send a notification: at most one every 10 s, kept until the board is online.""" + text = str(text) + result = _cloud().alert(text) + if result == 0: + print('Cloud: alert "%s"%s' % (text, "" if connected() else " (sends when connected)")) + elif result == 1: + print("Cloud: alert skipped (at most one every 10 s)") + return result == 0 + + +def switch(n=1): + """Dashboard switch 1 to 4: 1 on, 0 off.""" + return _cloud().get("switch%d" % n) + + +def slider(n=1): + """Dashboard slider 1 or 2: 0 to 100.""" + return _cloud().get("slider%d" % n) + + +def connected(): + import tbcloud + + return tbcloud.status()[0] == 3 + + +def status(): + import tbcloud + + st = tbcloud.status() + return { + "state": STATES[st[0]] if 0 <= st[0] < len(STATES) else st[0], + "reconnects": st[1], + "transport": st[2], + "last_error": st[3], + "wifi_restarts": st[4], + "fresh_starts": st[5], + "sent": st[6], + "wifi": bool(_wlan and _wlan.isconnected()), + } + + +def end(): + global _started + import tbcloud + + tbcloud.stop() + _started = False + if _wlan is not None: + _wlan.active(False) + tinkerbit.radio(False) diff --git a/prototypes/micropython/lib/tinkerbit/max30102.py b/prototypes/micropython/lib/tinkerbit/max30102.py new file mode 100644 index 00000000000..a94fa7483eb --- /dev/null +++ b/prototypes/micropython/lib/tinkerbit/max30102.py @@ -0,0 +1,150 @@ +# MAX30102 (HW-605) pulse sensor on I2C, and the beat detector from the SparkFun MAX3010x +# library (heartRate.cpp, Maxim's PBA algorithm) that Beginner Studio's Arduino code used. +import time + +ADDR = 0x57 + +_FIFO_WR = 0x04 +_FIFO_OVF = 0x05 +_FIFO_RD = 0x06 +_FIFO_DATA = 0x07 +_FIFO_CONFIG = 0x08 +_MODE_CONFIG = 0x09 +_SPO2_CONFIG = 0x0A +_LED_RED = 0x0C +_LED_IR = 0x0D +_PART_ID = 0xFF +_MAX30102_ID = 0x15 + +# Red + IR (6 bytes a sample). The SparkFun setup() asked for a green LED the MAX30102 does not have. +_MODE_SPO2 = 0x03 +_RESET = 0x40 +# 4 samples averaged, FIFO rolls over when full. +_FIFO_SETUP = 0x50 +# ADC range 4096 nA, 400 samples/s, 411 us pulses: SparkFun's setup() defaults. +_SPO2_SETUP = 0x2F +_RED_POWER = 0x0A +_IR_POWER = 0x1F + +# 400 samples/s averaged by 4. +SAMPLE_MS = 10 +FIFO_DEPTH = 32 + + +def _s16(v): + v &= 0xFFFF + return v - 0x10000 if v & 0x8000 else v + + +def _s32(v): + v &= 0xFFFFFFFF + return v - 0x100000000 if v & 0x80000000 else v + + +_FIR = (172, 321, 579, 927, 1360, 1858, 2390, 2916, 3391, 3768, 4012, 4096) + + +class BeatDetector: + """checkForBeat() from heartRate.cpp, with its C integer sizes (int16/uint16/int32 wrap + the same way), so the same samples give the same beats as the Arduino code.""" + + def __init__(self): + self.ac_max = 20 + self.ac_min = -20 + self.cur = 0 + self.prev = 0 + self.sig_min = 0 + self.sig_max = 0 + self.pos = False + self.neg = False + self._avg_reg = 0 + self._cbuf = [0] * 32 + self._offset = 0 + + def _average(self, x): + # averageDCEstimator(int32_t *p, uint16_t x) + x &= 0xFFFF + self._avg_reg = _s32(self._avg_reg + ((_s32(x << 15) - self._avg_reg) >> 4)) + return _s16(self._avg_reg >> 15) + + def _low_pass(self, din): + cb = self._cbuf + o = self._offset + cb[o] = din + z = _FIR[11] * cb[(o - 11) & 0x1F] + for i in range(11): + z += _FIR[i] * cb[(o - i) & 0x1F] + z += _FIR[i] * cb[(o - 22 + i) & 0x1F] + self._offset = (o + 1) % 32 + return _s16(_s32(z) >> 15) + + def check(self, sample): + beat = False + self.prev = self.cur + avg = self._average(sample) + self.cur = self._low_pass(_s16(sample - avg)) + if self.prev < 0 and self.cur >= 0: + self.ac_max = self.sig_max + self.ac_min = self.sig_min + self.pos = True + self.neg = False + self.sig_max = 0 + if 20 < self.ac_max - self.ac_min < 1000: + beat = True + if self.prev > 0 and self.cur <= 0: + self.pos = False + self.neg = True + self.sig_min = 0 + if self.pos and self.cur > self.prev: + self.sig_max = self.cur + if self.neg and self.cur < self.prev: + self.sig_min = self.cur + return beat + + +class MAX30102: + def __init__(self, i2c, addr=ADDR): + self._i2c = i2c + self._addr = addr + + def _write(self, reg, value): + self._i2c.writeto_mem(self._addr, reg, bytes((value,))) + + def _read(self, reg): + return self._i2c.readfrom_mem(self._addr, reg, 1)[0] + + def begin(self): + """Reset and start sampling. False when no MAX30102 answers (OSError is passed on).""" + if self._read(_PART_ID) != _MAX30102_ID: + return False + self._write(_MODE_CONFIG, _RESET) + end = time.ticks_add(time.ticks_ms(), 100) + while self._read(_MODE_CONFIG) & _RESET: + if time.ticks_diff(end, time.ticks_ms()) <= 0: + return False + time.sleep_ms(1) + self._write(_FIFO_CONFIG, _FIFO_SETUP) + self._write(_MODE_CONFIG, _MODE_SPO2) + self._write(_SPO2_CONFIG, _SPO2_SETUP) + self._write(_LED_RED, _RED_POWER) + self._write(_LED_IR, _IR_POWER) + self._write(_FIFO_WR, 0) + self._write(_FIFO_OVF, 0) + self._write(_FIFO_RD, 0) + return True + + def read_ir(self): + """(IR samples since the last call, oldest first; samples lost to a full FIFO).""" + wr = self._read(_FIFO_WR) + lost = self._read(_FIFO_OVF) + rd = self._read(_FIFO_RD) + n = (wr - rd) & (FIFO_DEPTH - 1) + if n == 0 and lost: + n = FIFO_DEPTH + if not n: + return [], 0 + raw = self._i2c.readfrom_mem(self._addr, _FIFO_DATA, n * 6) + out = [] + for i in range(0, len(raw) - 5, 6): + out.append(((raw[i + 3] << 16) | (raw[i + 4] << 8) | raw[i + 5]) & 0x3FFFF) + return out, lost diff --git a/prototypes/micropython/lib/tinkerbit/rc522.py b/prototypes/micropython/lib/tinkerbit/rc522.py new file mode 100644 index 00000000000..09f6408f8d2 --- /dev/null +++ b/prototypes/micropython/lib/tinkerbit/rc522.py @@ -0,0 +1,181 @@ +# MFRC522 (RC522) card reader on SPI: just enough of ISO 14443-A to read a card's UID, +# in the same steps as the Arduino MFRC522 library (PICC_IsNewCardPresent, PICC_ReadCardSerial, +# PICC_HaltA). Pins come from the caller (tinkerbit.Rfid reads them from board.py). +import time + +_COMMAND = 0x01 +_COM_IRQ = 0x04 +_DIV_IRQ = 0x05 +_ERROR = 0x06 +_FIFO_DATA = 0x09 +_FIFO_LEVEL = 0x0A +_CONTROL = 0x0C +_BIT_FRAMING = 0x0D +_COLL = 0x0E +_MODE = 0x11 +_TX_MODE = 0x12 +_RX_MODE = 0x13 +_TX_CONTROL = 0x14 +_TX_ASK = 0x15 +_CRC_H = 0x21 +_CRC_L = 0x22 +_MOD_WIDTH = 0x24 +_T_MODE = 0x2A +_T_PRESCALER = 0x2B +_T_RELOAD_H = 0x2C +_T_RELOAD_L = 0x2D +_VERSION = 0x37 + +_IDLE = 0x00 +_CALC_CRC = 0x03 +_TRANSCEIVE = 0x0C +_SOFT_RESET = 0x0F + +_REQA = 0x26 +_HALT = 0x50 +_CASCADE_TAG = 0x88 +_SELECT = (0x93, 0x95, 0x97) + +# Genuine chips report 0x91 or 0x92; common clones 0x88, 0x12 or 0xB2. 0x00 and 0xFF mean no reader. +_NO_READER = (0x00, 0xFF) + +# The chip's own timer gives up after 25 ms; this is the Python-side limit on top of it. +_WAIT_MS = 40 + + +class RC522: + def __init__(self, spi, cs, rst): + self._spi = spi + self._cs = cs + self._rst = rst + self._buf = bytearray(2) + self._out = bytearray(2) + + def _write(self, reg, value): + self._out[0] = (reg << 1) & 0x7E + self._out[1] = value & 0xFF + self._cs.value(0) + self._spi.write(self._out) + self._cs.value(1) + + def _read(self, reg): + self._out[0] = ((reg << 1) & 0x7E) | 0x80 + self._out[1] = 0 + self._cs.value(0) + self._spi.write_readinto(self._out, self._buf) + self._cs.value(1) + return self._buf[1] + + def _set(self, reg, mask): + self._write(reg, self._read(reg) | mask) + + def _clear(self, reg, mask): + self._write(reg, self._read(reg) & ~mask) + + def begin(self): + """Reset and set up the reader like PCD_Init. False when no reader answers.""" + self._rst.value(0) + time.sleep_ms(2) + self._rst.value(1) + time.sleep_ms(50) + if self._read(_VERSION) in _NO_READER: + return False + self._write(_COMMAND, _SOFT_RESET) + time.sleep_ms(50) + self._write(_TX_MODE, 0x00) + self._write(_RX_MODE, 0x00) + self._write(_MOD_WIDTH, 0x26) + # Timer: starts after every send, gives up after 25 ms. + self._write(_T_MODE, 0x80) + self._write(_T_PRESCALER, 0xA9) + self._write(_T_RELOAD_H, 0x03) + self._write(_T_RELOAD_L, 0xE8) + self._write(_TX_ASK, 0x40) + self._write(_MODE, 0x3D) + self._set(_TX_CONTROL, 0x03) + return True + + def present(self): + """False when the reader stopped answering (cable pulled).""" + return self._read(_VERSION) not in _NO_READER + + def _crc(self, data): + self._write(_COMMAND, _IDLE) + self._write(_DIV_IRQ, 0x04) + self._write(_FIFO_LEVEL, 0x80) + for b in data: + self._write(_FIFO_DATA, b) + self._write(_COMMAND, _CALC_CRC) + end = time.ticks_add(time.ticks_ms(), _WAIT_MS) + while not self._read(_DIV_IRQ) & 0x04: + if time.ticks_diff(end, time.ticks_ms()) <= 0: + return None + self._write(_COMMAND, _IDLE) + return bytes((self._read(_CRC_L), self._read(_CRC_H))) + + def _transceive(self, data, bits=0): + """Send to the card and return its answer, or None (no card, timeout or a garbled answer).""" + self._write(_COMMAND, _IDLE) + self._write(_COM_IRQ, 0x7F) + self._write(_FIFO_LEVEL, 0x80) + for b in data: + self._write(_FIFO_DATA, b) + self._write(_BIT_FRAMING, bits) + self._write(_COMMAND, _TRANSCEIVE) + self._set(_BIT_FRAMING, 0x80) + end = time.ticks_add(time.ticks_ms(), _WAIT_MS) + while True: + irq = self._read(_COM_IRQ) + if irq & 0x30: + break + if irq & 0x01 or time.ticks_diff(end, time.ticks_ms()) <= 0: + self._clear(_BIT_FRAMING, 0x80) + return None + self._clear(_BIT_FRAMING, 0x80) + # Buffer overflow, parity, protocol or collision error. + if self._read(_ERROR) & 0x1B: + return None + n = self._read(_FIFO_LEVEL) + return bytes([self._read(_FIFO_DATA) for _ in range(n)]) + + def _select(self, level, part): + frame = bytes((_SELECT[level], 0x70)) + part + crc = self._crc(frame) + if crc is None: + return None + sak = self._transceive(frame + crc) + return sak[0] if sak and len(sak) == 3 else None + + def read_uid(self): + """UID bytes of a card that was just put on the reader, else None. The card is then + halted, so a card left on the reader is read once, as with the Arduino library.""" + self._clear(_COLL, 0x80) + atqa = self._transceive(bytes((_REQA,)), 0x07) + if not atqa or len(atqa) != 2: + return None + uid = b"" + for level in range(3): + self._write(_BIT_FRAMING, 0x00) + part = self._transceive(bytes((_SELECT[level], 0x20))) + if not part or len(part) != 5 or part[0] ^ part[1] ^ part[2] ^ part[3] != part[4]: + return None + sak = self._select(level, part) + if sak is None: + return None + if not sak & 0x04: + uid += part[:4] + break + if part[0] != _CASCADE_TAG: + return None + uid += part[1:4] + else: + return None + self.halt() + return uid + + def halt(self): + frame = bytes((_HALT, 0x00)) + crc = self._crc(frame) + if crc is not None: + # A halted card does not answer: the timeout is the expected result. + self._transceive(frame + crc) diff --git a/prototypes/micropython/main.py b/prototypes/micropython/main.py new file mode 100644 index 00000000000..d40c94f3c75 --- /dev/null +++ b/prototypes/micropython/main.py @@ -0,0 +1,6 @@ +# Default TinkerBit program: short blink, report the board, exit (under 1 s). +import tinkerbit + +led = tinkerbit.Led("D13") +led.blink(100, 2) +tinkerbit.info() diff --git a/prototypes/micropython/package-lock.json b/prototypes/micropython/package-lock.json new file mode 100644 index 00000000000..872182609b7 --- /dev/null +++ b/prototypes/micropython/package-lock.json @@ -0,0 +1,76 @@ +{ + "name": "tinkerbit-micropython-prototype", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "tinkerbit-micropython-prototype", + "devDependencies": { + "@playwright/test": "1.49.1" + } + }, + "node_modules/@playwright/test": { + "version": "1.49.1", + "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.49.1.tgz", + "integrity": "sha512-Ky+BVzPz8pL6PQxHqNRW1k3mIyv933LML7HktS8uik0bUXNCdPhoS/kLihiO1tMf/egaJb4IutXd7UywvXEW+g==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright": "1.49.1" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/fsevents": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", + "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/playwright": { + "version": "1.49.1", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.49.1.tgz", + "integrity": "sha512-VYL8zLoNTBxVOrJBbDuRgDWa3i+mfQgDTrL8Ah9QXZ7ax4Dsj0MSq5bYgytRnDVVe+njoKnfsYkH3HzqVj5UZA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright-core": "1.49.1" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "fsevents": "2.3.2" + } + }, + "node_modules/playwright-core": { + "version": "1.49.1", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.49.1.tgz", + "integrity": "sha512-BzmpVcs4kE2CH15rWfzpjzVGhWERJfmnXmniSyKeRZUs9Ws65m+RGIi7mjJK/euCegfn3i7jvqWeWyHe9y3Vgg==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=18" + } + } + } +} diff --git a/prototypes/micropython/package.json b/prototypes/micropython/package.json new file mode 100644 index 00000000000..bc62f2b3256 --- /dev/null +++ b/prototypes/micropython/package.json @@ -0,0 +1,13 @@ +{ + "name": "tinkerbit-micropython-prototype", + "private": true, + "description": "Browser tests for the MicroPython prototype (kept apart from the root package.json).", + "scripts": { + "test:sim": "python -m pytest tests -q", + "test:e2e": "playwright test", + "bridge": "python sim/bridge.py" + }, + "devDependencies": { + "@playwright/test": "1.49.1" + } +} diff --git a/prototypes/micropython/playwright.config.js b/prototypes/micropython/playwright.config.js new file mode 100644 index 00000000000..f1b793a411c --- /dev/null +++ b/prototypes/micropython/playwright.config.js @@ -0,0 +1,24 @@ +// Headless Chrome (the installed browser, no download) against sim/bridge.py. +const {defineConfig} = require('@playwright/test'); + +const HTTP_PORT = Number(process.env.TB_HTTP_PORT) || 8796; +const WS_PORT = HTTP_PORT - 1; // fake-serial.js connects one port below the page + +module.exports = defineConfig({ + testDir: './tests/e2e', + timeout: 60000, + workers: 1, + fullyParallel: false, + reporter: [['list']], + use: { + baseURL: `http://127.0.0.1:${HTTP_PORT}`, + channel: process.env.PW_CHANNEL || 'chrome', + headless: true + }, + webServer: { + command: `python sim/bridge.py --ws-port ${WS_PORT} --http-port ${HTTP_PORT}`, + url: `http://127.0.0.1:${HTTP_PORT}/__sim/state`, + reuseExistingServer: false, + timeout: 30000 + } +}); diff --git a/prototypes/micropython/sim/board_sim.py b/prototypes/micropython/sim/board_sim.py new file mode 100644 index 00000000000..2a606108ea3 --- /dev/null +++ b/prototypes/micropython/sim/board_sim.py @@ -0,0 +1,1198 @@ +"""TinkerBit ESP32 board simulator (CPython). + +Models what the test page talks to over USB serial: + * the ESP32 auto-reset circuit (EN low iff RTS and not DTR, IO0 low iff DTR and not RTS), + ROM boot text and download mode; + * the MicroPython v1.24.1 boot sequence from ports/esp32/main.c: frozen _boot.py, boot.py, + then main.py only in friendly-REPL mode when boot.py finished without an exception; + * the friendly REPL, raw REPL and raw-paste protocol from shared/runtime/pyexec.c, + including the 128-byte flow-control window (violations are counted); + * the REPL UART receive interrupt (ports/esp32/uart.c): the interrupt character raises + KeyboardInterrupt in running code, everything else goes to a 260-byte stdin ring buffer; + * UART0 baud changes (machine.UART(0, baudrate=...)) that survive soft reset, and garbled + bytes when host and board baud rates differ; + * flash as a host folder. +Python code runs in CPython with fake machine/network/dht/... modules (sim/mocks.py). +""" +import builtins +import codeop +import ctypes +import importlib +import math +import os +import re +import threading +import time +import traceback +import types + +try: + from . import mocks +except ImportError: + import mocks + +HERE = os.path.dirname(os.path.abspath(__file__)) +PROTO = os.path.dirname(HERE) +LIB_DIR = os.path.join(PROTO, "lib") +FROZEN_BOOT = os.path.join(PROTO, "firmware", "frozen", "_boot.py") + +CTRL_A, CTRL_B, CTRL_C, CTRL_D, CTRL_E = 1, 2, 3, 4, 5 +FORCED_EXIT = 0x100 +STDIN_RINGBUF = 260 +PASTE_WINDOW = 128 +CLOUD_KEYS = ("switch1", "switch2", "switch3", "switch4", "slider1", "slider2") + +ROM_BOOT = ( + "ets Jul 29 2019 12:21:46\r\n\r\n" + "rst:0x1 (POWERON_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)\r\n" + "configsip: 0, SPIWP:0xee\r\n" + "clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00\r\n" + "mode:DIO, clock div:2\r\nload:0x3fff0030,len:4728\r\nload:0x40078000,len:14876\r\n" + "ho 0 tail 12 room 4\r\nload:0x40080400,len:3368\r\nentry 0x400805cc\r\n" +) +ROM_DOWNLOAD = ( + "ets Jul 29 2019 12:21:46\r\n\r\n" + "rst:0x1 (POWERON_RESET),boot:0x3 (DOWNLOAD_BOOT(UART0/UART1/SDIO_REI_REO_V2))\r\n" + "waiting for download\r\n" +) +BANNER = 'MicroPython v1.24.1 on 2024-11-29; Generic ESP32 module with ESP32\r\nType "help()" for more information.\r\n' +DEFAULT_BOOT_PY = ( + "# This file is executed on every boot (including wake-boot from deepsleep)\n" + "#import esp\n#esp.osdebug(None)\n#import webrepl\n#webrepl.start()\n" +) + +# CPython modules that behave like their MicroPython counterparts for our purposes. +REAL_MODULES = { + "json": "json", "ujson": "json", "math": "math", "cmath": "cmath", "array": "array", + "binascii": "binascii", "ubinascii": "binascii", "struct": "struct", "ustruct": "struct", + "random": "random", "re": "re", "errno": "errno", "io": "io", "hashlib": "hashlib", + "collections": "collections", "heapq": "heapq", +} + + +class HardReset(BaseException): + """Raised inside the MicroPython thread of a board that was reset.""" + + +def _async_raise(tid, exc): + return ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_ulong(tid), ctypes.py_object(exc) if exc else None) + + +class _Stdin: + def __init__(self, board): + self._b = board + self.buffer = types.SimpleNamespace(read=lambda n=1: bytes(board.rx_chr() for _ in range(n))) + + def read(self, n=1): + return "".join(chr(self._b.rx_chr()) for _ in range(n)) + + def readline(self): + s = "" + while not s.endswith("\n"): + s += chr(self._b.rx_chr()) + return s + + +class _Stdout: + def __init__(self, board): + self._b = board + self.buffer = types.SimpleNamespace(write=lambda b: (board.out_raw(bytes(b)), len(b))[1]) + + def write(self, s): + self._b.out_text(str(s)) + return len(s) + + def flush(self): + pass + + +class Board: + def __init__(self, flash_dir, firmware="stage_a", on_output=None, boot_ms=700, uid=b"\x24\x6f\x28\xa1\xb2\xc3"): + if firmware not in ("stage_a", "stage_b", "none"): + raise ValueError(firmware) + self.flash_dir = os.path.abspath(flash_dir) + os.makedirs(self.flash_dir, exist_ok=True) + self.firmware = firmware + self.on_output = on_output or (lambda b: None) + self.boot_ms = boot_ms + self.uid = uid + self._fresh = not os.listdir(self.flash_dir) + + self._lock = threading.RLock() + self._rx = bytearray() + self._rx_cv = threading.Condition(self._lock) + self._tls = threading.local() + self._gen = 0 + self._thread = None + self.dtr = False + self.rts = False + self.in_reset = False + self.host_baud = 115200 + self.uart_baud = 115200 + self.interrupt_char = -1 + self.mode = "friendly" + self.paste_credit = None + self.overflow_wait = 0.5 + self.boot_epoch = time.monotonic() + self.boot_epoch_us = time.perf_counter() + self.reset_cause = mocks.PWRON_RESET + + # Counters and logs for tests. + self.resets = 0 + self.boots = 0 + # Tests can make the program's sleeps shorter (ticks stay real time). + self.time_scale = 1.0 + self.soft_reboots = 0 + self.paste_violations = 0 + self.rx_overflow = 0 + + # Hardware the fake modules read and write. + self.pins = {} + self.inputs = {} + self.analog = {} + self.pwm = {} + self.pin_log = [] + self.uarts = {} + self.wifi = {} + self.wifi_connected = False + self.echo_us = 1160 + self.dht = {} + self.dht_default = (24, 55) + self.i2c_devices = {0x3C: OledDevice(), 0x68: Mpu6050Device(), 0x57: Max30102Device(self)} + self.i2c_freq = None + self.spi_device = Rc522Device() + self.ble = _ble_state() + self.screen = [] + self.neopixels = [] + self.heap_total = 113664 + self.heap_free = 98000 + self.idf_heap_free = 61000 + self.flash_blocks = 512 + self.cloud = {} + self.cloud_sent = [] + self.cloud_lines = [] + self.cloud_skew_ms = 0 + self.cloud_broker_down = False + self.cwd = "/" + + self.modules = {} + self._mocks = {} + self.globals = {} + self._user_files = set() + self._builtins = dict(builtins.__dict__) + self._builtins.update(__import__=self._import, print=self.print, open=self.open, input=self.input) + self.stdin = _Stdin(self) + self.stdout = _Stdout(self) + + # ================= host side ================= + def power_on(self): + with self._lock: + self._start(mocks.PWRON_RESET) + + def shutdown(self): + with self._lock: + self._kill() + + def host_write(self, data): + with self._lock: + if self.in_reset or self._thread is None: + return + garbled = self.host_baud != self.uart_baud + for b in data: + if garbled: + b = _garble(b) + if self.paste_credit is not None and b not in (CTRL_C, CTRL_D): + if self.paste_credit <= 0: + self.paste_violations += 1 + continue + self.paste_credit -= 1 + if b == self.interrupt_char: + _async_raise(self._thread.ident, KeyboardInterrupt) + continue + if len(self._rx) >= STDIN_RINGBUF: + # The real wire (11.5 KB/s) is slower than a board that is reading, so + # wait for the reader; a board that stays busy loses the bytes. + self._rx_cv.notify_all() + deadline = time.monotonic() + self.overflow_wait + while len(self._rx) >= STDIN_RINGBUF and time.monotonic() < deadline and not self.in_reset: + self._rx_cv.wait(0.01) + if len(self._rx) < STDIN_RINGBUF: + self._rx.append(b) + else: + self.rx_overflow += 1 + self._rx_cv.notify_all() + + def set_signals(self, dtr=None, rts=None): + with self._lock: + if dtr is not None: + self.dtr = bool(dtr) + if rts is not None: + self.rts = bool(rts) + en_low = self.rts and not self.dtr + if en_low and not self.in_reset: + self.in_reset = True + self.resets += 1 + self._kill() + elif not en_low and self.in_reset: + self.in_reset = False + self._start(mocks.PWRON_RESET, download=self.dtr and not self.rts) + + def set_host_baud(self, baud): + with self._lock: + self.host_baud = int(baud) + + # ================= threads ================= + def _start(self, cause, download=False): + self._kill() + self._gen += 1 + gen = self._gen + t = threading.Thread(target=self._mp_task, args=(gen, cause, download), daemon=True) + self._thread = t + t.start() + + def _kill(self): + self._gen += 1 + t = self._thread + if t is not None and t.is_alive() and t is not threading.current_thread(): + _async_raise(t.ident, HardReset) + self.interrupt_char = -1 + self.paste_credit = None + + def _alive(self): + return getattr(self._tls, "gen", None) == self._gen + + def check(self): + if not self._alive(): + raise HardReset() + + def machine_reset(self): + with self._lock: + self._start(mocks.SOFT_RESET) + raise HardReset() + + # ================= board side primitives ================= + def ticks_ms(self): + return int((time.monotonic() - self.boot_epoch) * 1000) + + def ticks_us(self): + return int((time.perf_counter() - self.boot_epoch_us) * 1e6) + + def sleep(self, seconds): + end = time.monotonic() + max(0.0, seconds) * self.time_scale + while True: + self.check() + left = end - time.monotonic() + if left <= 0: + return + time.sleep(min(left, 0.01)) + + def rx_chr(self): + with self._rx_cv: + while not self._rx: + self.check() + self._rx_cv.wait(0.02) + c = self._rx.pop(0) + if len(self._rx) == STDIN_RINGBUF - 1: + self._rx_cv.notify_all() + return c + + def stdin_ready(self): + return bool(self._rx) + + def out_raw(self, data): + with self._lock: + self.check() + if self.host_baud != self.uart_baud: + data = bytes(_garble(b) for b in data) + self.on_output(bytes(data)) + + def out_text(self, s): + self.out_raw(s.replace("\n", "\r\n").encode("utf-8")) + + def print(self, *args, sep=" ", end="\n", file=None): + text = sep.join(str(a) for a in args) + end + if file is not None and file is not self.stdout: + file.write(text) + else: + self.out_text(text) + + def input(self, prompt=""): + self.out_text(prompt) + line = "" + while True: + c = chr(self.rx_chr()) + if c == "\r": + self.out_text("\n") + return line + line += c + self.out_text(c) + + def set_interrupt_char(self, c): + with self._lock: + self.interrupt_char = c + + def set_uart_baud(self, baud): + with self._lock: + self.uart_baud = int(baud) + + def set_raw_mode(self): + self.mode = "raw" + + def ble_connect(self, conn=1): + """A phone connects (the IRQ runs on the board's thread in MicroPython; here, on the caller's).""" + self.ble["conns"].add(conn) + self.ble["advertising"] = None + if self.ble["irq"]: + self.ble["irq"](1, (conn, 0, b"\x00" * 6)) + + def ble_disconnect(self, conn=1): + self.ble["conns"].discard(conn) + if self.ble["irq"]: + self.ble["irq"](2, (conn, 0, b"\x00" * 6)) + + @property + def wifi_on(self): + return any(self.wifi.values()) + + # ================= flash ================= + def norm(self, path): + path = str(path).replace("\\", "/") + if not path.startswith("/"): + path = self.cwd.rstrip("/") + "/" + path + parts = [] + for p in path.split("/"): + if p in ("", "."): + continue + if p == "..": + if parts: + parts.pop() + continue + parts.append(p) + return "/" + "/".join(parts) + + def real_path(self, path): + return os.path.join(self.flash_dir, *self.norm(path).split("/")[1:]) + + def open(self, path, mode="r", *args, **kw): + real = self.real_path(path) + try: + if "b" in mode: + return builtins.open(real, mode) + return builtins.open(real, mode, encoding="utf-8", newline="") + except FileNotFoundError: + raise OSError(2, "ENOENT") + + def files(self): + """Every file on the fake flash as a sorted list of '/path' strings.""" + out = [] + for root, _dirs, names in os.walk(self.flash_dir): + for n in names: + rel = os.path.relpath(os.path.join(root, n), self.flash_dir).replace("\\", "/") + out.append("/" + rel) + return sorted(out) + + def read_file(self, path): + with open(self.real_path(path), encoding="utf-8") as f: + return f.read() + + # ================= import system ================= + def _search_dirs(self): + dirs = [] + for p in self._mocks["sys"].path: + if p == "": + dirs.append(self.real_path(self.cwd)) + elif p == ".frozen": + if self.firmware == "stage_b": + dirs.append(LIB_DIR) + elif p.startswith("/"): + dirs.append(self.real_path(p)) + return dirs + + def _import(self, name, globals=None, locals=None, fromlist=(), level=0): + if level: + pkg = (globals or {}).get("__package__") or "" + if not pkg: + raise ImportError("can't perform relative import") + bits = pkg.split(".") + if level > 1: + bits = bits[: -(level - 1)] + full = ".".join(bits) + ("." + name if name else "") + else: + full = name + mod = self._load(full) + if fromlist: + for item in fromlist: + if item != "*" and not hasattr(mod, item) and hasattr(mod, "__path__"): + try: + self._load(full + "." + item) + except ImportError: + pass + return mod + return self._load(full.split(".")[0]) + + def _load(self, full): + if full in self.modules: + return self.modules[full] + parts = full.split(".") + parent = None + if len(parts) > 1: + parent = self._load(".".join(parts[:-1])) + search = getattr(parent, "__path__", []) + else: + # Built-in modules: like MicroPython, they never appear in sys.modules. + if full in self._mocks: + return self._mocks[full] + if full in REAL_MODULES: + return importlib.import_module(REAL_MODULES[full]) + search = self._search_dirs() + leaf = parts[-1] + for d in search: + pkg_init = os.path.join(d, leaf, "__init__.py") + if os.path.isfile(pkg_init): + return self._exec_module(full, pkg_init, os.path.join(d, leaf), parent, leaf) + path = os.path.join(d, leaf + ".py") + if os.path.isfile(path): + return self._exec_module(full, path, None, parent, leaf) + raise ImportError("no module named '%s'" % full) + + def _shown_name(self, real): + real = os.path.abspath(real) + if real.startswith(self.flash_dir): + return "/" + os.path.relpath(real, self.flash_dir).replace("\\", "/") + return os.path.relpath(real, LIB_DIR).replace("\\", "/") + + def _exec_module(self, full, path, pkgdir, parent, leaf): + m = types.ModuleType(full) + shown = self._shown_name(path) + m.__file__ = shown + m.__dict__["__builtins__"] = self._builtins + if pkgdir: + m.__path__ = [pkgdir] + m.__package__ = full + else: + m.__package__ = full.rpartition(".")[0] + self.modules[full] = m + try: + with builtins.open(path, encoding="utf-8") as f: + src = f.read() + self._user_files.add(shown) + exec(compile(src, shown, "exec"), m.__dict__) + except BaseException: + self.modules.pop(full, None) + raise + if parent is not None: + setattr(parent, leaf, m) + return m + + # ================= execution ================= + def print_exception(self, e): + lines = ["Traceback (most recent call last):"] + for frame, lineno in traceback.walk_tb(e.__traceback__): + fn = frame.f_code.co_filename + if fn in self._user_files: + lines.append(' File "%s", line %d, in %s' % (fn, lineno, frame.f_code.co_name)) + if isinstance(e, SyntaxError): + lines.append(' File "%s", line %s' % (e.filename, e.lineno)) + msg = e.msg + elif isinstance(e, OSError) and len(e.args) >= 2: + msg = "[Errno %s] %s" % (e.args[0], e.args[1]) + else: + msg = ", ".join(str(a) for a in e.args) if len(e.args) != 1 else str(e.args[0]) + lines.append("%s: %s" % (type(e).__name__, msg)) + self.out_text("\n".join(lines) + "\n") + + def _pce(self, src, filename, kind, print_eof): + """parse_compile_execute: returns 1 ok, 0 exception, FORCED_EXIT on SystemExit.""" + self._user_files.add(filename) + ret = 0 + try: + try: + code = None + if kind == "single": + try: + code = compile(src, filename, "eval") + except SyntaxError: + code = None + is_expr = code is not None + if code is None: + code = compile(src, filename, "exec") + with self._lock: + self.interrupt_char = CTRL_C + if is_expr: + value = eval(code, self.globals) + if value is not None: + self.out_text(repr(value) + "\n") + else: + exec(code, self.globals) + finally: + with self._lock: + self.interrupt_char = -1 + _async_raise(threading.get_ident(), None) + ret = 1 + if print_eof: + self.out_raw(b"\x04") + except HardReset: + raise + except SystemExit: + if print_eof: + self.out_raw(b"\x04") + ret = FORCED_EXIT + except BaseException as e: + if print_eof: + self.out_raw(b"\x04") + self.print_exception(e) + ret = 0 + if print_eof: + self.out_raw(b"\x04") + return ret + + def _exec_file(self, name): + real = self.real_path(name) + if not os.path.isfile(real): + return 1 + with builtins.open(real, encoding="utf-8") as f: + src = f.read() + return self._pce(src, name, "exec", False) + + def _new_session(self): + self.modules = {} + self._mocks = mocks.build(self) + self._mocks.update(self._boot_mocks()) + self.globals = {"__name__": "__main__", "__builtins__": self._builtins} + self.pins.clear() + self.pwm.clear() + self.wifi.clear() + self.wifi_connected = False + # A soft reset turns Bluetooth off (mp_bluetooth_deinit). + self.ble = _ble_state() + self.cwd = "/" + self.interrupt_char = -1 + + def _boot_mocks(self): + board = self + + def setup(): + with builtins.open(board.real_path("/boot.py"), "w", encoding="utf-8", newline="") as f: + f.write(DEFAULT_BOOT_PY) + + return { + "vfs": mocks._module("vfs", mount=lambda bdev, path: None), + "flashbdev": mocks._module("flashbdev", bdev=object()), + "inisetup": mocks._module("inisetup", setup=setup), + } + + def _mp_task(self, gen, cause, download): + self._tls.gen = gen + try: + with self._lock: + self.uart_baud = 115200 + self.interrupt_char = -1 + self._rx.clear() + self.boot_epoch = time.monotonic() + self.boot_epoch_us = time.perf_counter() + self.reset_cause = cause + self.mode = "friendly" + self.boots += 1 + if download: + self.out_text(ROM_DOWNLOAD.replace("\r\n", "\n")) + while True: + self.sleep(1) + self.out_raw(ROM_BOOT.encode()) + self.sleep(self.boot_ms / 1000) + with self._lock: + # uart_stdout_init() resets the RX FIFO: bytes sent during boot are lost. + self._rx.clear() + if self.firmware == "none": + while True: + self.out_raw(b"sensor=512\r\n") + self.sleep(1) + if self._fresh: + self._fresh = False + with builtins.open(self.real_path("/boot.py"), "w", encoding="utf-8", newline="") as f: + f.write(DEFAULT_BOOT_PY) + while True: + self._new_session() + if self.firmware == "stage_b" and os.path.isfile(FROZEN_BOOT): + with builtins.open(FROZEN_BOOT, encoding="utf-8") as f: + self._pce(f.read(), "_boot.py", "exec", False) + ret = self._exec_file("boot.py") + if not ret & FORCED_EXIT and self.mode == "friendly" and ret != 0: + ret = self._exec_file("main.py") + if not ret & FORCED_EXIT: + while True: + r = self._raw_repl() if self.mode == "raw" else self._friendly_repl() + if r != 0: + break + self.soft_reboots += 1 + self.out_text("MPY: soft reboot\n") + except HardReset: + return + + # ================= REPLs ================= + def _readline(self, prompt): + self.out_text(prompt) + line = "" + while True: + c = self.rx_chr() + if CTRL_A <= c <= CTRL_E and (not line or c == CTRL_C): + return line, c + if c == 0x0D: + self.out_text("\n") + return line, None + if c in (0x08, 0x7F): + if line: + line = line[:-1] + self.out_raw(b"\x08 \x08") + continue + if c == 0x0A or c < 0x20: + continue + line += chr(c) + self.out_raw(bytes([c])) + + def _friendly_repl(self): + self.out_raw(BANNER.encode()) + while True: + line, ctrl = self._readline(">>> ") + if ctrl == CTRL_A: + self.out_text("\n") + self.mode = "raw" + return 0 + if ctrl == CTRL_B: + self.out_text("\n") + self.out_raw(BANNER.encode()) + continue + if ctrl == CTRL_C: + self.out_text("\n") + continue + if ctrl == CTRL_D: + self.out_text("\n") + return FORCED_EXIT + if ctrl == CTRL_E: + self.out_text("\npaste mode; Ctrl-C to cancel, Ctrl-D to finish\n=== ") + buf = bytearray() + cancelled = False + while True: + c = self.rx_chr() + if c == CTRL_C: + self.out_text("\n") + cancelled = True + break + if c == CTRL_D: + self.out_text("\n") + break + buf.append(c) + self.out_text("\n=== " if c == 0x0D else chr(c)) + if not cancelled: + r = self._pce(buf.decode("utf-8", "replace").replace("\r", "\n"), "", "exec", False) + if r & FORCED_EXIT: + return r + continue + if not line: + continue + src = line + cancelled = False + while _needs_more(src): + more, ctrl = self._readline("... ") + if ctrl == CTRL_C: + self.out_text("\n") + cancelled = True + break + if ctrl == CTRL_D: + break + src += "\n" + more + if not more: + break + if cancelled: + continue + r = self._pce(src + "\n", "", "single", False) + if r & FORCED_EXIT: + return r + + def _raw_repl(self): + self.out_raw(b"raw REPL; CTRL-B to exit\r\n") + while True: + line = bytearray() + self.out_raw(b">") + while True: + c = self.rx_chr() + if c == CTRL_A: + if len(line) == 2 and line[0] == CTRL_E: + ret = self._raw_paste(line[1]) + if ret & FORCED_EXIT: + return ret + line = bytearray() + self.out_raw(b">") + continue + self.out_raw(b"raw REPL; CTRL-B to exit\r\n") + line = bytearray() + self.out_raw(b">") + continue + if c == CTRL_B: + self.out_raw(b"\r\n") + self.mode = "friendly" + return 0 + if c == CTRL_C: + line = bytearray() + elif c == CTRL_D: + break + else: + line.append(c) + self.out_raw(b"OK") + if not line: + self.out_raw(b"\r\n") + return FORCED_EXIT + ret = self._pce(line.decode("utf-8", "replace"), "", "exec", True) + if ret & FORCED_EXIT: + return ret + + def _raw_paste(self, c): + if c != ord("A"): + self.out_raw(b"R\x00") + return 0 + with self._lock: + self.paste_credit = 2 * PASTE_WINDOW + self.out_raw(b"R\x01" + bytes([PASTE_WINDOW & 0xFF, PASTE_WINDOW >> 8, 0x01])) + src = bytearray() + remain = PASTE_WINDOW + interrupted = False + try: + while True: + b = self.rx_chr() + if b in (CTRL_C, CTRL_D): + self.out_raw(b"\x04") + interrupted = b == CTRL_C + break + src.append(b) + remain -= 1 + if remain == 0: + with self._lock: + self.paste_credit += PASTE_WINDOW + self.out_raw(b"\x01") + remain = PASTE_WINDOW + finally: + with self._lock: + self.paste_credit = None + if interrupted: + self.out_raw(b"\x04") + self.out_text("Traceback (most recent call last):\nKeyboardInterrupt: \n") + self.out_raw(b"\x04") + return 0 + return self._pce(src.decode("utf-8", "replace"), "", "exec", True) + + # ================= Cloud (fake tbcloud C module) ================= + def cloud_now(self): + return self.ticks_ms() + self.cloud_skew_ms + + def cloud_publish(self, suffix, payload, retain=False): + self.cloud_sent.append(("tb/%s/%s" % (self.cloud["device_id"], suffix), payload)) + if retain: + self.cloud["retained"][suffix] = payload + + def cloud_message(self, key, body): + """The broker delivers tb//state/ (what the dashboard sends).""" + c = self.cloud + if not c.get("connected") or key not in CLOUD_KEYS: + return + + def number(name): + m = re.search(r'"%s":(-?\d+)' % name, body) + return int(m.group(1)) if m else None + + v, ver = number("v"), number("ver") + if v is None or ver is None: + return + fs, fv = number("fs"), number("fv") + idx = CLOUD_KEYS.index(key) + top = 1 if idx < 4 else 100 + c["values"][idx] = max(0, min(top, v)) + c["failsafe_sec"][idx] = max(0, min(3600, 120 if fs is None else fs)) + c["failsafe_value"][idx] = max(0, min(top, fv or 0)) + c["failsafe_on"][idx] = False + self.cloud_publish("ack", '{"key":"%s","ver":%d}' % (key, ver)) + self.cloud_lines.append("Cloud: %s = %d" % (key, c["values"][idx])) + + def cloud_tick(self): + """One pass of the C supervisor task.""" + c = self.cloud + if not c: + return + now = self.cloud_now() + if self.wifi_connected and not c["wifi_noted"]: + c["wifi_noted"] = True + self.cloud_lines.append("Cloud: WiFi connected (RSSI -55)") + if c["connected"] and self.cloud_broker_down: + c["connected"] = False + c["state"] = 2 + c["reconnects"] += 1 + c["down_since"] = now + self.cloud_lines.append("Cloud: disconnected - retrying") + if not c["connected"] and self.wifi_connected and not self.cloud_broker_down: + if not c["client"]: + c["client"] = True + self.cloud_lines.append("Cloud: connecting to mqtts://%s:%d" % (c["host"], c["port"])) + c["connected"] = True + c["state"] = 3 + self.cloud_publish("status", '{"s":"online","fw":"%s","rssi":-55,"boot":"%s","tr":"mqtts"}' % (c["fw"], c["boot"]), retain=True) + c["subscribed"] = "tb/%s/state/#" % c["device_id"] + self.cloud_lines.append("Cloud: connected (port %d)" % c["port"]) + if not c["connected"]: + down = now - c["down_since"] + for i, key in enumerate(CLOUD_KEYS): + fs = c["failsafe_sec"][i] + if fs > 0 and not c["failsafe_on"][i] and down >= fs * 1000: + c["failsafe_on"][i] = True + c["values"][i] = c["failsafe_value"][i] + self.cloud_lines.append("Cloud: offline %ds - %s set to safe value %d" % (fs, key, c["failsafe_value"][i])) + return + if c["alert"] is not None: + self.cloud_publish("alert", c["alert"]) + c["alert"] = None + since = now - c["last_send"] if c["last_send"] is not None else None + if since is None or since >= c["interval_ms"] or (c["send_now"] and since >= c["min_gap_ms"]): + c["send_now"] = False + c["last_send"] = now + parts = [] + for key, (value, is_int) in c["readings"].items(): + if isinstance(value, float) and (value != value or value in (float("inf"), float("-inf"))): + continue + parts.append('"%s":%d' % (key, value) if is_int else '"%s":%.2f' % (key, value)) + c["seq"] += 1 + self.cloud_publish("telemetry", '{"seq":%d,"boot":"%s","v":{%s}}' % (c["seq"], c["boot"], ",".join(parts))) + + def fake_cloud_module(self): + board = self + + # Same API as firmware/cmodules/tbcloud. The supervisor task runs (cloud_tick) and its + # scheduled lines are printed whenever Python calls into the module. + def run(): + board.cloud_tick() + while board.cloud_lines: + board.out_text(board.cloud_lines.pop(0) + "\n") + + def start(host, port, ws_port, device_id, token, ca, *, ws_path=None, interval_ms=10000, min_gap_ms=5000, fw=None): + if not board.wifi_on: + raise OSError("WiFi is off") + if "BEGIN CERTIFICATE" not in ca: + raise ValueError("ca must be PEM") + board.cloud = { + "host": host, "port": port, "ws_port": ws_port, "device_id": device_id, + "ws_path": ws_path or "/mqtt", "interval_ms": interval_ms, "min_gap_ms": min_gap_ms, + "fw": fw or "mpy-1", "boot": "%08x" % (hash(device_id) & 0xFFFFFFFF), + "has_token": bool(token), "state": 1, "connected": False, "client": False, + "wifi_noted": False, "reconnects": 0, "down_since": board.cloud_now(), + "last_send": None, "send_now": False, "seq": 0, "readings": {}, + "values": [0] * 6, "failsafe_sec": [120] * 6, "failsafe_value": [0] * 6, + "failsafe_on": [False] * 6, "alert": None, "alert_at": None, "alert_note_at": None, + "retained": {}, "subscribed": None, + } + + def set(key, value): + if not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]{0,22}", str(key)): + raise ValueError("reading names use letters, digits and _ (up to 23)") + r = board.cloud["readings"] + if value is None: + r.pop(key, None) + run() + return True + if isinstance(value, (bool, int)): + entry = (int(value), True) + elif isinstance(value, float): + entry = (value, False) + else: + raise TypeError("readings are numbers") + if key not in r and len(r) >= 24: + run() + return False + r[key] = entry + run() + return True + + def send_now(): + board.cloud["send_now"] = True + run() + + def alert(text): + c = board.cloud + now = board.cloud_now() + if c["alert"] is not None or (c["alert_at"] is not None and now - c["alert_at"] < 10000): + if c["alert_note_at"] is None or now - c["alert_note_at"] >= 10000: + c["alert_note_at"] = now + result = 1 + else: + result = 2 + else: + c["alert"] = str(text)[:483] + c["alert_at"] = now + result = 0 + run() + return result + + def get(key): + if key not in CLOUD_KEYS: + raise ValueError("dashboard controls are switch1-4 and slider1-2") + run() + return board.cloud["values"][CLOUD_KEYS.index(key)] + + def status(): + run() + c = board.cloud + return (c.get("state", 0), c.get("reconnects", 0), "mqtts", 0, 0, 0, c.get("seq", 0)) + + def stop(): + c = board.cloud + if c and c["connected"]: + board.cloud_publish("status", "offline", retain=True) + board.cloud = {} + board.cloud_lines.clear() + + return mocks._module("tbcloud", start=start, set=set, send_now=send_now, alert=alert, get=get, + status=status, stop=stop) + + +def _needs_more(src): + try: + return codeop.compile_command(src, "", "single") is None + except (SyntaxError, ValueError, OverflowError): + return False + + +def _garble(b): + # Bytes read at the wrong baud rate come out as different bytes; never as the + # REPL control characters, so a mismatch cannot accidentally drive the REPL. + g = ((b * 37) ^ 0xA5) & 0xFF + return g | 0x80 if g < 0x20 else g + + +class OledDevice: + def __init__(self): + self.writes = 0 + + def write(self, data): + self.writes += 1 + + def write_mem(self, reg, data): + self.writes += 1 + + def read(self, reg, n): + return bytes(n) + + +def _ble_state(): + return {"active": False, "name": None, "advertising": None, "adverts": 0, "values": {}, "conns": set(), + "notified": [], "irq": None, "next_handle": 0} + + +def crc_a(data): + """ISO 14443-A CRC, low byte first (what the RC522 puts in CRCResultReg).""" + crc = 0x6363 + for b in data: + b ^= crc & 0xFF + b = (b ^ (b << 4)) & 0xFF + crc = (crc >> 8) ^ (b << 8) ^ (b << 3) ^ (b >> 4) + return bytes((crc & 0xFF, crc >> 8)) + + +class Rc522Device: + """RC522 reader with at most one card. put_card(uid) is a card placed on the reader; + a halted card answers again only after take_card() and put_card(), like lifting it off.""" + + def __init__(self): + self.version = 0x92 + self.card = None + self.halted = False + self.regs = [0] * 64 + self.fifo = [] + self.selected = 0 + + def put_card(self, uid): + self.card = bytes(uid) + self.halted = False + + def take_card(self): + self.card = None + self.halted = False + + def transfer(self, data): + addr = data[0] + reg = (addr >> 1) & 0x3F + out = bytearray(len(data)) + if addr & 0x80: + for i in range(1, len(data)): + out[i] = self._read(reg) + else: + for b in data[1:]: + self._write(reg, b) + return bytes(out) + + def _read(self, reg): + if reg == 0x37: + return self.version + if reg == 0x09: + return self.fifo.pop(0) if self.fifo else 0 + if reg == 0x0A: + return len(self.fifo) + return self.regs[reg] + + def _write(self, reg, v): + if reg == 0x09: + self.fifo.append(v) + elif reg == 0x0A: + if v & 0x80: + self.fifo = [] + elif reg in (0x04, 0x05): + # Bit 7 set: the other marked bits are set; clear: they are cleared. + self.regs[reg] = self.regs[reg] | (v & 0x7F) if v & 0x80 else self.regs[reg] & ~v & 0x7F + else: + self.regs[reg] = v + if reg == 0x01: + self._command(v & 0x0F) + elif reg == 0x0D and v & 0x80 and self.regs[0x01] & 0x0F == 0x0C: + self._transceive(v & 0x07) + + def _command(self, cmd): + if cmd == 0x0F: + self.regs = [0] * 64 + self.fifo = [] + elif cmd == 0x03: + crc = crc_a(bytes(self.fifo)) + self.regs[0x22], self.regs[0x21] = crc[0], crc[1] + self.regs[0x05] |= 0x04 + + def _transceive(self, bits): + data = bytes(self.fifo) + self.fifo = [] + self.regs[0x06] = 0 + answer = self._answer(data, bits) + if answer is None: + self.regs[0x04] |= 0x01 + else: + self.fifo = list(answer) + self.regs[0x04] |= 0x30 + + def _part(self, level): + c = self.card + if len(c) == 4: + return c + return bytes((0x88,)) + c[:3] if level == 0 else c[3:7] + + def _answer(self, data, bits): + c = self.card + if c is None: + return None + if bits == 7 and data == b"\x26": + if self.halted: + return None + return b"\x44\x00" if len(c) == 7 else b"\x04\x00" + if len(data) == 2 and data[1] == 0x20 and data[0] in (0x93, 0x95): + part = self._part((0x93, 0x95).index(data[0])) + return part + bytes((part[0] ^ part[1] ^ part[2] ^ part[3],)) + if len(data) == 9 and data[1] == 0x70 and data[0] in (0x93, 0x95) and crc_a(data[:7]) == data[7:]: + level = (0x93, 0x95).index(data[0]) + sak = 0x04 if len(c) == 7 and level == 0 else 0x08 + if sak == 0x08: + self.selected += 1 + return bytes((sak,)) + crc_a(bytes((sak,))) + if data[:2] == b"\x50\x00": + self.halted = True + return None + + +class Max30102Device: + """MAX30102 making 100 samples a second in real time. With finger_bpm set, IR is a pulse wave + at that rate on top of a fingertip's DC level; with None, no finger (low IR).""" + + DEPTH = 32 + + def __init__(self, board): + self.board = board + self.finger_bpm = None + self.mode = 0 + self.regs = {} + self._restart() + + def _restart(self): + self.queue = [] + self.rd = 0 + self.lost = 0 + self._t0 = None + self._made = 0 + + def _ir(self, t_ms): + if self.finger_bpm is None: + return 2000 + return int(80000 + 200 * math.sin(2 * math.pi * t_ms * self.finger_bpm / 60000.0)) + + def _fill(self): + now = self.board.ticks_ms() + if self._t0 is None: + self._t0 = now + while self._made < (now - self._t0) // 10: + self._made += 1 + if len(self.queue) >= self.DEPTH: + self.queue.pop(0) + self.rd = (self.rd + 1) % self.DEPTH + self.lost = min(0x1F, self.lost + 1) + self.queue.append(self._ir(self._made * 10)) + + def write(self, data): + if data: + self.write_mem(data[0], data[1:]) + + def write_mem(self, reg, data): + v = data[0] if data else 0 + if reg == 0x09: + # The reset bit clears itself at once. + self.mode = v & ~0x40 + self._restart() + elif reg in (0x04, 0x05, 0x06): + self._restart() + else: + self.regs[reg] = v + + def read(self, reg, n): + if reg == 0xFF: + return bytes((0x15,))[:n] + if reg == 0x09: + return bytes((self.mode,))[:n] + self._fill() + if reg == 0x04: + return bytes(((self.rd + len(self.queue)) % self.DEPTH,))[:n] + if reg == 0x05: + return bytes((self.lost,))[:n] + if reg == 0x06: + return bytes((self.rd,))[:n] + if reg == 0x07: + out = b"" + for _ in range(n // 6): + ir = self.queue.pop(0) if self.queue else 0 + self.rd = (self.rd + 1) % self.DEPTH + out += b"\x00\x10\x00" + ir.to_bytes(3, "big") + self.lost = 0 + return out + return bytes((self.regs.get(reg, 0),))[:n] + + +class Mpu6050Device: + """Flat and still: 1 g on Z, no rotation. Tests can set accel/gyro (raw counts).""" + + def __init__(self): + self.awake = False + self.accel = (0, 0, 16384) + self.gyro = (0, 0, 0) + + def write(self, data): + if data: + self.write_mem(data[0], data[1:]) + + def write_mem(self, reg, data): + if reg == 0x6B and data and data[0] == 0: + self.awake = True + + def read(self, reg, n): + if reg == 0x75: + return bytes([0x68])[:n] + if reg == 0x3B: + vals = list(self.accel) + [0] + list(self.gyro) + raw = b"".join((v & 0xFFFF).to_bytes(2, "big") for v in vals) + return raw[:n] + return bytes(n) diff --git a/prototypes/micropython/sim/bridge.py b/prototypes/micropython/sim/bridge.py new file mode 100644 index 00000000000..eb1669730cb --- /dev/null +++ b/prototypes/micropython/sim/bridge.py @@ -0,0 +1,220 @@ +"""Bridge for the browser tests. + + ws://127.0.0.1: one connection per FakePort.open(): binary frames are serial + bytes, text frames are JSON {t: baud|signals} + http://127.0.0.1: serves prototypes/micropython/ (index.html and the library) + plus a control API for tests: + POST /__sim/reset {"firmware": "stage_a", "boot_ms": 300, "install_library": true, + "files": {"/main.py": "..."}} + GET /__sim/state counters, flash file list, baud rates, jack output values + GET /__sim/file?path=/main.py +""" +import argparse +import asyncio +import importlib.util +import json +import os +import queue +import shutil +import sys +import tempfile +import threading +from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer +from urllib.parse import parse_qs, urlparse + +from websockets.asyncio.server import serve + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +sys.dont_write_bytecode = True +from board_sim import PROTO, Board # noqa: E402 + +LIBRARY = { + "/lib/tinkerbit/__init__.py": "lib/tinkerbit/__init__.py", + "/lib/tinkerbit/board.py": "lib/tinkerbit/board.py", + "/lib/ssd1306.py": "lib/ssd1306.py", + "/boot.py": "boot.py", + "/main.py": "main.py", +} + + +def _board_map(): + spec = importlib.util.spec_from_file_location("tb_board_map", os.path.join(PROTO, "lib", "tinkerbit", "board.py")) + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + return mod + + +class Bridge: + def __init__(self): + self.loop = None + self.tmp = tempfile.mkdtemp(prefix="tbsim-") + self.count = 0 + self.board = None + self.ws = None + self.outq = None + self.inq = queue.Queue() + self.map = _board_map() + self.lock = threading.Lock() + threading.Thread(target=self._feeder, daemon=True).start() + + # Serial bytes and signal changes go through one queue so they keep their order; + # host_write can block while the simulated board drains its stdin buffer. + def _feeder(self): + while True: + board, kind, value = self.inq.get() + if board is not self.board: + continue + if kind == "data": + board.host_write(value) + elif kind == "signals": + board.set_signals(dtr=value.get("dtr"), rts=value.get("rts")) + elif kind == "baud": + board.set_host_baud(value) + + def reset(self, opts): + with self.lock: + if self.board is not None: + self.board.shutdown() + self.count += 1 + flash = os.path.join(self.tmp, "flash%d" % self.count) + os.makedirs(flash) + files = {} + if opts.get("install_library"): + for dest, src in LIBRARY.items(): + with open(os.path.join(PROTO, src), encoding="utf-8") as f: + files[dest] = f.read() + files.update(opts.get("files") or {}) + for dest, text in files.items(): + real = os.path.join(flash, *dest.strip("/").split("/")) + os.makedirs(os.path.dirname(real), exist_ok=True) + with open(real, "w", encoding="utf-8", newline="") as f: + f.write(text) + board = Board(flash, firmware=opts.get("firmware", "stage_a"), on_output=self._out, boot_ms=opts.get("boot_ms", 300)) + board.dtr = board.rts = False + self.board = board + board.power_on() + + def _out(self, data): + q, loop = self.outq, self.loop + if q is not None and loop is not None: + loop.call_soon_threadsafe(q.put_nowait, data) + + def state(self): + b = self.board + jacks = {} + for name, spec in self.map.JACKS.items(): + gpio = spec["pins"].get("sig") + if gpio is not None and gpio in b.pins: + jacks[name] = b.pins[gpio]["value"] + return { + "firmware": b.firmware, + "files": b.files(), + "resets": b.resets, + "boots": b.boots, + "soft_reboots": b.soft_reboots, + "paste_violations": b.paste_violations, + "rx_overflow": b.rx_overflow, + "uart_baud": b.uart_baud, + "host_baud": b.host_baud, + "mode": b.mode, + "wifi_on": b.wifi_on, + "jacks": jacks, + "pwm_pins": len(b.pwm), + } + + async def handler(self, ws): + if self.ws is not None: + await self.ws.close() + q = asyncio.Queue() + self.ws, self.outq = ws, q + sender = asyncio.create_task(self._sender(ws, q)) + try: + async for msg in ws: + board = self.board + if isinstance(msg, bytes): + self.inq.put((board, "data", msg)) + continue + m = json.loads(msg) + if m.get("t") == "signals": + self.inq.put((board, "signals", m)) + elif m.get("t") == "baud": + self.inq.put((board, "baud", int(m["baud"]))) + except Exception: + pass + finally: + sender.cancel() + if self.ws is ws: + self.ws, self.outq = None, None + + async def _sender(self, ws, q): + while True: + data = await q.get() + await ws.send(data) + + +def make_http_handler(bridge): + class Handler(SimpleHTTPRequestHandler): + def __init__(self, *a, **kw): + super().__init__(*a, directory=PROTO, **kw) + + def log_message(self, *a): + pass + + def _json(self, obj, code=200): + body = json.dumps(obj).encode() + self.send_response(code) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def end_headers(self): + self.send_header("Cache-Control", "no-store") + super().end_headers() + + def do_GET(self): + url = urlparse(self.path) + if url.path == "/__sim/state": + return self._json(bridge.state()) + if url.path == "/__sim/file": + path = parse_qs(url.query).get("path", [""])[0] + real = bridge.board.real_path(path) + if not os.path.isfile(real): + return self._json({"error": "missing"}, 404) + with open(real, encoding="utf-8") as f: + return self._json({"path": path, "text": f.read()}) + return super().do_GET() + + def do_POST(self): + url = urlparse(self.path) + length = int(self.headers.get("Content-Length") or 0) + opts = json.loads(self.rfile.read(length) or b"{}") + if url.path == "/__sim/reset": + bridge.reset(opts) + return self._json({"ok": True}) + return self._json({"error": "unknown"}, 404) + + return Handler + + +async def main(args): + bridge = Bridge() + bridge.loop = asyncio.get_running_loop() + bridge.reset({"firmware": args.firmware}) + httpd = ThreadingHTTPServer(("127.0.0.1", args.http_port), make_http_handler(bridge)) + threading.Thread(target=httpd.serve_forever, daemon=True).start() + print("bridge: ws://127.0.0.1:%d http://127.0.0.1:%d/index.html" % (args.ws_port, args.http_port), flush=True) + try: + async with serve(bridge.handler, "127.0.0.1", args.ws_port, max_size=None): + await asyncio.Future() + finally: + httpd.shutdown() + shutil.rmtree(bridge.tmp, ignore_errors=True) + + +if __name__ == "__main__": + p = argparse.ArgumentParser() + p.add_argument("--ws-port", type=int, default=8765) + p.add_argument("--http-port", type=int, default=8766) + p.add_argument("--firmware", default="stage_a", choices=["stage_a", "stage_b", "none"]) + asyncio.run(main(p.parse_args())) diff --git a/prototypes/micropython/sim/host.py b/prototypes/micropython/sim/host.py new file mode 100644 index 00000000000..f13dc30b323 --- /dev/null +++ b/prototypes/micropython/sim/host.py @@ -0,0 +1,178 @@ +"""Host side of the serial protocol, in Python, for the simulator tests. + +Mirrors what index.html does over Web Serial: raw REPL, raw-paste with flow control, +EN reset through RTS and serial safe mode. +""" +import threading +import time + + +class Timeout(AssertionError): + pass + + +class Host: + def __init__(self, board): + self.board = board + self.buf = bytearray() + self.log = bytearray() + self.cv = threading.Condition() + board.on_output = self._on_output + + def _on_output(self, data): + with self.cv: + self.buf += data + self.log += data + self.cv.notify_all() + + def write(self, data): + if isinstance(data, str): + data = data.encode() + self.board.host_write(data) + + def clear(self): + with self.cv: + self.buf.clear() + + def text(self): + with self.cv: + return bytes(self.buf).decode("utf-8", "replace") + + def read_until(self, token, timeout=5.0): + if isinstance(token, str): + token = token.encode() + end = time.monotonic() + timeout + with self.cv: + while token not in self.buf: + left = end - time.monotonic() + if left <= 0: + raise Timeout("waited for %r, got %r" % (token, bytes(self.buf[-300:]))) + self.cv.wait(left) + i = self.buf.index(token) + len(token) + out = bytes(self.buf[:i]) + del self.buf[:i] + return out + + def read_exact(self, n, timeout=5.0): + end = time.monotonic() + timeout + with self.cv: + while len(self.buf) < n: + left = end - time.monotonic() + if left <= 0: + raise Timeout("waited for %d bytes, got %r" % (n, bytes(self.buf))) + self.cv.wait(left) + out = bytes(self.buf[:n]) + del self.buf[:n] + return out + + def pending(self): + with self.cv: + return len(self.buf) + + # ---------------- raw REPL ---------------- + def enter_raw(self, timeout=5.0): + self.write(b"\r\x03\x03\x03") + time.sleep(0.05) + self.clear() + self.write(b"\x01") + self.read_until(b"raw REPL; CTRL-B to exit\r\n>", timeout) + + def exec_raw(self, code, timeout=10.0): + self.write(code.encode() + b"\x04") + self.read_until(b"OK", timeout) + return self._result(timeout) + + def _result(self, timeout): + out = self.read_until(b"\x04", timeout)[:-1].decode("utf-8", "replace") + err = self.read_until(b"\x04", timeout)[:-1].decode("utf-8", "replace") + self.read_until(b">", timeout) + return out, err + + def exec_paste(self, code, honor_flow=True, timeout=10.0): + """Raw-paste mode. Returns (out, err), or None if the board does not support it.""" + data = code.encode() + self.write(b"\x05A\x01") + self.read_until(b"R", timeout) + if self.read_exact(1, timeout) == b"\x00": + return None + w = self.read_exact(2, timeout) + window = w[0] | (w[1] << 8) + credit = 0 + i = 0 + while i < len(data): + while credit == 0 or (honor_flow and self.pending()): + if not honor_flow: + credit = len(data) + break + c = self.read_exact(1, timeout) + if c == b"\x01": + credit += window + elif c == b"\x04": + self.write(b"\x04") + return self._result(timeout) + n = min(credit, len(data) - i) + self.write(data[i:i + n]) + i += n + credit -= n + self.write(b"\x04") + while self.read_exact(1, timeout) != b"\x04": + pass + return self._result(timeout) + + def exit_raw(self): + self.write(b"\x02") + self.read_until(b"\r\n") + + def soft_reset_run_main(self, timeout=10.0): + """Friendly-REPL soft reset: boot.py then main.py run (raw-REPL Ctrl-D skips main.py).""" + self.write(b"\x02") + time.sleep(0.05) + self.clear() + self.write(b"\x04") + self.read_until(b"MPY: soft reboot\r\n", timeout) + + # ---------------- reset / recover ---------------- + def open_port(self, glitch=False): + """What the page does on open: Chrome asserts DTR+RTS, the page drops both (RTS first).""" + if glitch: + self.board.set_signals(rts=True) + self.board.set_signals(dtr=True) + else: + self.board.set_signals(dtr=True, rts=True) + self.board.set_signals(rts=False) + self.board.set_signals(dtr=False) + + def hard_reset(self): + self.board.set_signals(dtr=False, rts=True) + time.sleep(0.1) + self.board.set_signals(rts=False) + + def recover(self, timeout=3.0): + self.clear() + self.hard_reset() + end = time.monotonic() + timeout + while time.monotonic() < end: + self.write(b"TB_SAFE\n") + time.sleep(0.05) + if b"TB_SAFE_OK" in self.buf: + self.read_until(b"TB_SAFE_OK") + return True + return False + + def install_files(self, files): + """files: {board path: text}. Writes through the raw REPL the way the page does.""" + for path, text in files.items(): + raw = text.encode() + parts = path.strip("/").split("/") + code = "import os\n" + for k in range(1, len(parts)): + code += "try:\n os.mkdir(%r)\nexcept OSError:\n pass\n" % ("/" + "/".join(parts[:k])) + code += "f=open(%r,'wb')\n" % (path + ".tmp") + for j in range(0, len(raw), 512): + code += "f.write(bytes.fromhex(%r))\n" % raw[j:j + 512].hex() + code += "f.close()\n" + code += "try:\n os.remove(%r)\nexcept OSError:\n pass\n" % path + code += "os.rename(%r,%r)\n" % (path + ".tmp", path) + out, err = self.exec_raw(code) + if err: + raise AssertionError("install %s failed: %s" % (path, err)) diff --git a/prototypes/micropython/sim/mocks.py b/prototypes/micropython/sim/mocks.py new file mode 100644 index 00000000000..ac3e66bcbe6 --- /dev/null +++ b/prototypes/micropython/sim/mocks.py @@ -0,0 +1,698 @@ +"""Fake MicroPython modules for the CPython board simulator. + +Each Board builds a fresh set at every soft reset (MicroPython clears sys.modules then too). +Behaviour follows MicroPython v1.24.1 on a classic ESP32 closely enough for the protocol and +library tests; electrical behaviour is not modelled. +""" +import errno +import os as _os +import types + +# ESP32 (classic) GPIO facts used by the fake machine module. +VALID_GPIO = set(range(0, 6)) | set(range(12, 20)) | {21, 22, 23, 25, 26, 27} | set(range(32, 40)) +INPUT_ONLY = set(range(34, 40)) +ADC1_GPIO = set(range(32, 40)) +ADC2_GPIO = {0, 2, 4, 12, 13, 14, 15, 25, 26, 27} + +PWRON_RESET, HARD_RESET, WDT_RESET, DEEPSLEEP_RESET, SOFT_RESET = 1, 2, 3, 4, 5 + + +def _module(name, **attrs): + m = types.ModuleType(name) + for k, v in attrs.items(): + setattr(m, k, v) + return m + + +def _oserror(code): + return OSError(code, errno.errorcode.get(code, str(code))) + + +def build(board): + """Return {module name: module} for one soft-reset session of `board`.""" + mods = {} + + # ---------------- time ---------------- + def ticks_ms(): + return board.ticks_ms() & 0x3FFFFFFF + + def ticks_us(): + return board.ticks_us() & 0x3FFFFFFF + + def ticks_diff(a, b): + d = (a - b) & 0x3FFFFFFF + return d - 0x40000000 if d & 0x20000000 else d + + def ticks_add(a, b): + return (a + b) & 0x3FFFFFFF + + import time as _time + + mods["time"] = _module( + "time", + sleep=lambda s: board.sleep(s), + sleep_ms=lambda ms: board.sleep(ms / 1000), + sleep_us=lambda us: board.sleep(us / 1e6), + ticks_ms=ticks_ms, + ticks_us=ticks_us, + ticks_cpu=ticks_us, + ticks_diff=ticks_diff, + ticks_add=ticks_add, + time=lambda: int(_time.time()), + time_ns=_time.time_ns, + localtime=_time.localtime, + gmtime=_time.gmtime, + mktime=lambda t: int(_time.mktime(t)), + ) + + # ---------------- machine ---------------- + class Pin: + IN, OUT, OPEN_DRAIN = 1, 3, 7 + PULL_UP, PULL_DOWN = 1, 2 + IRQ_RISING, IRQ_FALLING = 1, 2 + + def __init__(self, id, mode=-1, pull=-1, *, value=None, drive=None): + if isinstance(id, Pin): + id = id.id + if id not in VALID_GPIO: + raise ValueError("invalid pin") + self.id = id + self.init(mode, pull, value=value) + + def init(self, mode=-1, pull=-1, *, value=None, drive=None): + st = board.pins.setdefault(self.id, {"mode": None, "pull": None, "value": 0}) + if mode != -1 and mode is not None: + if mode in (Pin.OUT, Pin.OPEN_DRAIN) and self.id in INPUT_ONLY: + raise ValueError("pin can only be input") + st["mode"] = "out" if mode in (Pin.OUT, Pin.OPEN_DRAIN) else "in" + if pull != -1: + st["pull"] = {Pin.PULL_UP: "up", Pin.PULL_DOWN: "down"}.get(pull) + if value is not None: + self.value(value) + + def value(self, v=None): + st = board.pins[self.id] + if v is None: + if st["mode"] == "out": + return st["value"] + if self.id in board.inputs: + return board.inputs[self.id] + return 1 if st["pull"] == "up" else 0 + st["value"] = 1 if v else 0 + board.pin_log.append((self.id, st["value"])) + del board.pin_log[:-200] + return None + + def __call__(self, v=None): + return self.value(v) + + def on(self): + self.value(1) + + def off(self): + self.value(0) + + def irq(self, handler=None, trigger=3): + return None + + def __repr__(self): + return "Pin(%d)" % self.id + + # ESP32 LEDC: 16 channels, and 8 timers (4 per speed mode), so at most 8 different + # frequencies at once. Approximates ports/esp32/machine_pwm.c. + PWM_CHANNELS = 16 + PWM_TIMERS = 8 + + class PWM: + def __init__(self, dest, freq=None, duty=None, duty_u16=None, duty_ns=None): + self.pin = dest if isinstance(dest, Pin) else Pin(dest) + self._freq = freq or 5000 + self._duty = 0 + others = {k: v for k, v in board.pwm.items() if k != self.pin.id} + if len(others) >= PWM_CHANNELS: + raise ValueError("out of PWM channels:%d" % PWM_CHANNELS) + if self._freq not in {p._freq for p in others.values()} and \ + len({p._freq for p in others.values()}) >= PWM_TIMERS: + raise ValueError("out of PWM timers:%d" % PWM_TIMERS) + board.pwm[self.pin.id] = self + st = board.pins.setdefault(self.pin.id, {"mode": None, "pull": None, "value": 0}) + st["mode"] = "pwm" + if duty_u16 is not None: + self.duty_u16(duty_u16) + elif duty_ns is not None: + self.duty_ns(duty_ns) + elif duty is not None: + self.duty(duty) + + def freq(self, f=None): + if f is None: + return self._freq + self._freq = f + + def duty_ns(self, ns=None): + period = 1000000000 // self._freq + if ns is None: + return self._duty * period // 65535 + self.duty_u16(int(ns) * 65535 // period) + + def duty_u16(self, d=None): + if d is None: + return self._duty + self._duty = max(0, min(65535, int(d))) + + def duty(self, d=None): + if d is None: + return self._duty >> 6 + self.duty_u16(int(d) << 6) + + def deinit(self): + if board.pwm.get(self.pin.id) is self: + del board.pwm[self.pin.id] + board.pins[self.pin.id]["mode"] = "out" + board.pins[self.pin.id]["value"] = 0 + + class ADC: + ATTN_0DB, ATTN_2_5DB, ATTN_6DB, ATTN_11DB = 0, 1, 2, 3 + WIDTH_9BIT, WIDTH_10BIT, WIDTH_11BIT, WIDTH_12BIT = 9, 10, 11, 12 + + def __init__(self, pin, *, atten=None): + gpio = pin.id if isinstance(pin, Pin) else int(pin) + if gpio not in ADC1_GPIO and gpio not in ADC2_GPIO: + raise ValueError("invalid Pin for ADC") + self.gpio = gpio + + def atten(self, a): + pass + + def width(self, w): + pass + + def read_u16(self): + if self.gpio in ADC2_GPIO and board.wifi_on: + # ESP-IDF adc2_get_raw() times out while the WiFi driver owns ADC2. + raise OSError("ESP_ERR_TIMEOUT") + return (board.analog.get(self.gpio, 2048) << 4) & 0xFFFF + + def read(self): + return self.read_u16() >> 4 + + def read_uv(self): + return self.read() * 3_300_000 // 4095 + + class I2C: + def __init__(self, id=0, *, scl=None, sda=None, freq=400000, timeout=50000): + self.freq = freq + board.i2c_freq = freq + + def _dev(self, addr): + dev = board.i2c_devices.get(addr) + if dev is None: + raise _oserror(errno.ENODEV) + return dev + + def scan(self): + return sorted(board.i2c_devices) + + def writeto(self, addr, buf, stop=True): + self._dev(addr).write(bytes(buf)) + return 1 + + def writevto(self, addr, vector, stop=True): + self._dev(addr).write(b"".join(bytes(v) for v in vector)) + return 1 + + def readfrom(self, addr, n, stop=True): + return self._dev(addr).read(None, n) + + def readfrom_mem(self, addr, reg, n, addrsize=8): + return self._dev(addr).read(reg, n) + + def readfrom_mem_into(self, addr, reg, buf, addrsize=8): + buf[:] = self.readfrom_mem(addr, reg, len(buf)) + + def writeto_mem(self, addr, reg, buf, addrsize=8): + self._dev(addr).write_mem(reg, bytes(buf)) + + class SPI: + """Hardware SPI 1 or 2 on any pins (GPIO matrix); talks to board.spi_device.""" + MSB, LSB = 0, 1 + + def __init__(self, id, baudrate=1000000, *, polarity=0, phase=0, bits=8, firstbit=0, + sck=None, mosi=None, miso=None): + if id not in (1, 2): + raise ValueError("SPI(%d) doesn't exist" % id) + for p in (sck, mosi): + if p is not None and (p.id if isinstance(p, Pin) else p) in INPUT_ONLY: + raise ValueError("pin can only be input") + self.baudrate = baudrate + + def _xfer(self, data): + dev = board.spi_device + # Nothing on the bus: MISO idles low. + return dev.transfer(bytes(data)) if dev is not None else bytes(len(data)) + + def write(self, buf): + self._xfer(buf) + + def read(self, n, write=0): + return self._xfer(bytes([write]) * n) + + def readinto(self, buf, write=0): + buf[:] = self.read(len(buf), write) + + def write_readinto(self, out, into): + into[:] = self._xfer(out) + + def deinit(self): + pass + + class UART: + def __init__(self, id, baudrate=None, **kw): + self.id = id + self.init(baudrate, **kw) + + def init(self, baudrate=None, **kw): + if baudrate: + if self.id == 0: + board.set_uart_baud(baudrate) + else: + board.uarts[self.id] = baudrate + + def write(self, buf): + if self.id == 0: + board.out_raw(bytes(buf)) + return len(buf) + + def read(self, n=-1): + # UART0 RX belongs to the REPL interrupt handler (ports/esp32/uart.c), so the + # driver buffer behind this object never sees data. + return None + + def any(self): + return 0 + + def deinit(self): + pass + + def time_pulse_us(pin, level, timeout_us=1000000): + us = board.echo_us + if us is None or us > timeout_us: + return -1 + return us + + def reset(): + board.machine_reset() + + def soft_reset(): + raise SystemExit + + mods["machine"] = _module( + "machine", + Pin=Pin, + PWM=PWM, + ADC=ADC, + I2C=I2C, + SoftI2C=I2C, + SPI=SPI, + SoftSPI=SPI, + UART=UART, + time_pulse_us=time_pulse_us, + reset=reset, + soft_reset=soft_reset, + reset_cause=lambda: board.reset_cause, + unique_id=lambda: board.uid, + freq=lambda f=None: 160000000 if f is None else None, + idle=lambda: board.sleep(0.001), + disable_irq=lambda: 0, + enable_irq=lambda state=0: None, + PWRON_RESET=PWRON_RESET, + HARD_RESET=HARD_RESET, + WDT_RESET=WDT_RESET, + DEEPSLEEP_RESET=DEEPSLEEP_RESET, + SOFT_RESET=SOFT_RESET, + ) + + # ---------------- micropython / gc / esp ---------------- + def kbd_intr(c): + board.set_interrupt_char(c) + + mods["micropython"] = _module( + "micropython", + const=lambda x: x, + kbd_intr=kbd_intr, + opt_level=lambda level=None: 0, + alloc_emergency_exception_buf=lambda n: None, + mem_info=lambda verbose=None: board.print("stack: 736 out of 15360\ngc: total: %d, used: %d, free: %d" % (board.heap_total, board.heap_total - board.heap_free, board.heap_free)), + qstr_info=lambda verbose=None: None, + stack_use=lambda: 736, + heap_lock=lambda: 0, + heap_unlock=lambda: 0, + schedule=lambda f, a: f(a), + ) + mods["gc"] = _module( + "gc", + collect=lambda: None, + mem_free=lambda: board.heap_free, + mem_alloc=lambda: board.heap_total - board.heap_free, + enable=lambda: None, + disable=lambda: None, + isenabled=lambda: True, + threshold=lambda n=None: -1, + ) + mods["esp"] = _module( + "esp", + flash_size=lambda: 4 * 1024 * 1024, + flash_user_start=lambda: 0x200000, + osdebug=lambda *a: None, + ) + mods["esp32"] = _module( + "esp32", + HEAP_DATA=4, + HEAP_EXEC=1, + idf_heap_info=lambda caps: [(board.idf_heap_free + 20000, board.idf_heap_free, board.idf_heap_free // 2, board.idf_heap_free - 4000)], + raw_temperature=lambda: 120, + ) + + # ---------------- network ---------------- + class WLAN: + def __init__(self, iface=0): + self.iface = iface + + def active(self, v=None): + if v is None: + return board.wifi.get(self.iface, False) + board.wifi[self.iface] = bool(v) + if not v and self.iface == 0: + board.wifi_connected = False + return None + + def connect(self, ssid=None, key=None, **kw): + if not board.wifi.get(self.iface): + raise OSError("Wifi Not Started") + board.wifi_connected = True + + def disconnect(self): + board.wifi_connected = False + + def isconnected(self): + return board.wifi_connected and board.wifi.get(self.iface, False) + + def status(self, *a): + return 1010 if self.isconnected() else 1000 + + def ifconfig(self, *a): + return ("192.168.4.20", "255.255.255.0", "192.168.4.1", "192.168.4.1") + + def config(self, *a, **kw): + if a and a[0] == "mac": + return bytes(board.uid) + return None + + def scan(self): + return [] + + mods["network"] = _module("network", WLAN=WLAN, STA_IF=0, AP_IF=1, hostname=lambda n=None: "tinkerbit") + + # ---------------- bluetooth ---------------- + class UUID: + def __init__(self, value): + if isinstance(value, UUID): + self._b = value._b + elif isinstance(value, int): + self._b = value.to_bytes(2, "little") + else: + self._b = bytes.fromhex(str(value).replace("-", ""))[::-1] + + def __bytes__(self): + return self._b + + def __eq__(self, other): + return isinstance(other, UUID) and other._b == self._b + + def __hash__(self): + return hash(self._b) + + class BLE: + """State lives in board.ble, so tests can play the phone (Board.ble_connect).""" + + def _need_active(self): + if not board.ble["active"]: + raise _oserror(errno.EPERM) + + def active(self, v=None): + if v is None: + return board.ble["active"] + board.ble["active"] = bool(v) + if not v: + board.ble.update(advertising=None, values={}, conns=set()) + + def config(self, *a, **kw): + if "gap_name" in kw: + name = kw["gap_name"] + board.ble["name"] = name.encode() if isinstance(name, str) else bytes(name) + if a and a[0] == "gap_name": + return board.ble["name"] + return None + + def irq(self, handler): + board.ble["irq"] = handler + + def gatts_register_services(self, services): + self._need_active() + out = [] + for _uuid, chars in services: + handles = [] + for _c in chars: + board.ble["next_handle"] += 2 + handles.append(board.ble["next_handle"]) + board.ble["values"][board.ble["next_handle"]] = b"" + out.append(tuple(handles)) + return tuple(out) + + def gatts_write(self, handle, data, send_update=False): + # The default attribute buffer is 20 bytes; longer writes are cut. + board.ble["values"][handle] = bytes(data)[:20] + + def gatts_read(self, handle): + return board.ble["values"][handle] + + def gatts_notify(self, conn, handle, data=None): + if conn not in board.ble["conns"]: + raise _oserror(errno.ENOTCONN) + board.ble["notified"].append((conn, bytes(data if data is not None else board.ble["values"][handle]))) + + def gap_advertise(self, interval_us, adv_data=None, resp_data=None, connectable=True): + self._need_active() + if interval_us is None: + board.ble["advertising"] = None + else: + if len(adv_data or b"") > 31 or len(resp_data or b"") > 31: + raise _oserror(errno.EINVAL) + board.ble["advertising"] = {"adv": bytes(adv_data or b""), "resp": bytes(resp_data or b"")} + board.ble["adverts"] += 1 + + mods["bluetooth"] = _module("bluetooth", BLE=BLE, UUID=UUID, FLAG_READ=0x0002, FLAG_WRITE=0x0008, FLAG_NOTIFY=0x0010) + + # ---------------- dht / neopixel / framebuf ---------------- + class _DHT: + def __init__(self, pin): + self.gpio = pin.id + + def measure(self): + reading = board.dht.get(self.gpio, board.dht_default) + if reading is None: + raise _oserror(errno.ETIMEDOUT) + self._t, self._h = reading + + def temperature(self): + return self._t + + def humidity(self): + return self._h + + mods["dht"] = _module("dht", DHT11=type("DHT11", (_DHT,), {}), DHT22=type("DHT22", (_DHT,), {})) + + class NeoPixel: + def __init__(self, pin, n, bpp=3, timing=1): + self.n = n + self.buf = [(0,) * bpp for _ in range(n)] + + def __len__(self): + return self.n + + def __setitem__(self, i, v): + self.buf[i] = tuple(v) + + def __getitem__(self, i): + return self.buf[i] + + def fill(self, v): + self.buf = [tuple(v)] * self.n + + def write(self): + board.neopixels = list(self.buf) + + mods["neopixel"] = _module("neopixel", NeoPixel=NeoPixel) + + class FrameBuffer: + def __init__(self, buf, width, height, fmt, stride=None): + self._w, self._h = width, height + self._texts = [] + + def fill(self, c): + self._texts = [] + board.screen = [] + + def text(self, s, x, y, c=1): + self._texts.append((str(s), x, y)) + board.screen = list(self._texts) + + def pixel(self, x, y, c=None): + return 0 if c is None else None + + def hline(self, *a): + pass + + vline = line = rect = fill_rect = ellipse = poly = blit = scroll = hline + + mods["framebuf"] = _module("framebuf", FrameBuffer=FrameBuffer, MONO_VLSB=0, RGB565=1, GS4_HMSB=2, MONO_HLSB=3, MONO_HMSB=4, GS2_HMSB=5, GS8=6) + + # ---------------- os ---------------- + def _st_mode(real): + return 0x4000 if _os.path.isdir(real) else 0x8000 + + def listdir(path=""): + real = board.real_path(path or board.cwd) + if not _os.path.isdir(real): + raise _oserror(errno.ENOENT) + return sorted(_os.listdir(real)) + + def ilistdir(path=""): + real = board.real_path(path or board.cwd) + for name in listdir(path): + full = _os.path.join(real, name) + yield (name, _st_mode(full), 0, _os.path.getsize(full) if _os.path.isfile(full) else 0) + + def _wrap(fn): + def inner(*a): + try: + return fn(*a) + except FileNotFoundError: + raise _oserror(errno.ENOENT) + except FileExistsError: + raise _oserror(errno.EEXIST) + except IsADirectoryError: + raise _oserror(errno.EISDIR) + except OSError as e: + raise _oserror(e.errno or errno.EIO) + return inner + + def stat(path): + real = board.real_path(path) + s = _os.stat(real) + return (_st_mode(real), 0, 0, 0, 0, 0, s.st_size if _st_mode(real) == 0x8000 else 0, 0, int(s.st_mtime), 0) + + def rename(a, b): + # LittleFS (the ESP32 default) replaces an existing target. + _os.replace(board.real_path(a), board.real_path(b)) + + def statvfs(path="/"): + bsize = 4096 + total = board.flash_blocks + used = 0 + for root, dirs, files in _os.walk(board.flash_dir): + used += 1 + sum((_os.path.getsize(_os.path.join(root, f)) + bsize - 1) // bsize for f in files) + free = max(0, total - used) + return (bsize, bsize, total, free, free, 0, 0, 0, 0, 255) + + def chdir(path): + real = board.real_path(path) + if not _os.path.isdir(real): + raise _oserror(errno.ENOENT) + board.cwd = board.norm(path) + + mods["os"] = _module( + "os", + listdir=_wrap(listdir), + ilistdir=_wrap(ilistdir), + mkdir=_wrap(lambda p: _os.mkdir(board.real_path(p))), + rmdir=_wrap(lambda p: _os.rmdir(board.real_path(p))), + remove=_wrap(lambda p: _os.remove(board.real_path(p))), + rename=_wrap(rename), + stat=_wrap(stat), + statvfs=statvfs, + getcwd=lambda: board.cwd, + chdir=_wrap(chdir), + sync=lambda: None, + uname=lambda: ("esp32", "esp32", "1.24.1", "v1.24.1 on 2024-11-29", "Generic ESP32 module with ESP32"), + urandom=_os.urandom, + dupterm=lambda *a: None, + sep="/", + ) + + # ---------------- sys ---------------- + impl = types.SimpleNamespace(name="micropython", version=(1, 24, 1, ""), _machine="Generic ESP32 module with ESP32", _mpy=10502) + + def sys_exit(code=0): + raise SystemExit(code) + + mods["sys"] = _module( + "sys", + modules=board.modules, + path=["", ".frozen", "/lib"], + argv=[], + implementation=impl, + platform="esp32", + version="3.4.0; MicroPython v1.24.1 on 2024-11-29", + version_info=(3, 4, 0), + byteorder="little", + maxsize=2**31 - 1, + stdin=board.stdin, + stdout=board.stdout, + stderr=board.stdout, + exit=sys_exit, + print_exception=lambda e, file=None: board.print_exception(e), + ) + + # ---------------- select ---------------- + class _Poll: + def __init__(self): + self._objs = {} + + def register(self, obj, mask=1): + self._objs[id(obj)] = (obj, mask) + + def unregister(self, obj): + self._objs.pop(id(obj), None) + + def modify(self, obj, mask): + self._objs[id(obj)] = (obj, mask) + + def poll(self, timeout=-1): + return list(self.ipoll(timeout)) + + def ipoll(self, timeout=-1, flags=0): + deadline = None if timeout is None or timeout < 0 else board.ticks_ms() + timeout + while True: + ready = [(o, 1) for o, m in self._objs.values() if o is board.stdin and board.stdin_ready()] + if ready or (deadline is not None and board.ticks_ms() >= deadline): + return iter(ready) + board.sleep(0.002) + + mods["select"] = _module("select", poll=_Poll, POLLIN=1, POLLOUT=4, POLLERR=8, POLLHUP=16) + + # ---------------- Stage B native modules ---------------- + if board.firmware == "stage_b": + def sample(adc, buf, rate_hz): + # Same signature and result shape as firmware/cmodules/tbsys; no real timing. + for i in range(len(buf)): + buf[i] = adc.read_u16() >> 4 + return (int(rate_hz), 0.0, 0.0, 0) + + mods["tbsys"] = _module("tbsys", sample=sample, skip_main=lambda: board.set_raw_mode()) + mods["tbcloud"] = board.fake_cloud_module() + + # MicroPython's old u-prefixed names still resolve. + for name in ("time", "os", "sys", "select"): + mods["u" + name] = mods[name] + return mods diff --git a/prototypes/micropython/tests/conftest.py b/prototypes/micropython/tests/conftest.py new file mode 100644 index 00000000000..087d81b014e --- /dev/null +++ b/prototypes/micropython/tests/conftest.py @@ -0,0 +1,75 @@ +import importlib.util +import os +import sys + +import pytest + +HERE = os.path.dirname(os.path.abspath(__file__)) +PROTO = os.path.dirname(HERE) +sys.path.insert(0, os.path.join(PROTO, "sim")) +# Loading board.py from lib/ must not leave __pycache__ next to the board files. +sys.dont_write_bytecode = True + +from board_sim import Board # noqa: E402 +from host import Host # noqa: E402 + + +def _load_board_map(): + spec = importlib.util.spec_from_file_location("tb_board_map", os.path.join(PROTO, "lib", "tinkerbit", "board.py")) + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + return mod + + +BOARD_MAP = _load_board_map() + + +def gpio(jack, role="sig"): + """GPIO number of a jack, read from board.py (the only file allowed to hold them).""" + return BOARD_MAP.pin(jack, role) + + +def read(rel): + with open(os.path.join(PROTO, rel), encoding="utf-8") as f: + return f.read() + + +LIBRARY_MODULES = ("__init__", "board", "rc522", "max30102", "ble") + + +def library_files(with_main=True): + files = {"/lib/tinkerbit/%s.py" % m: read("lib/tinkerbit/%s.py" % m) for m in LIBRARY_MODULES} + files.update({ + "/lib/ssd1306.py": read("lib/ssd1306.py"), + "/boot.py": read("boot.py"), + }) + if with_main: + files["/main.py"] = read("main.py") + return files + + +@pytest.fixture +def make_board(tmp_path): + boards = [] + + def make(firmware="stage_a", boot_ms=50, power=True): + b = Board(str(tmp_path / ("flash%d" % len(boards))), firmware=firmware, boot_ms=boot_ms) + h = Host(b) + boards.append(b) + if power: + b.power_on() + return b, h + + yield make + for b in boards: + b.shutdown() + + +@pytest.fixture +def board(make_board): + """Stage A board with the TinkerBit library installed, sitting in the raw REPL.""" + b, h = make_board() + h.read_until(">>> ") + h.enter_raw() + h.install_files(library_files(with_main=False)) + return b, h diff --git a/prototypes/micropython/tests/e2e/fake-serial.js b/prototypes/micropython/tests/e2e/fake-serial.js new file mode 100644 index 00000000000..292c918e7cb --- /dev/null +++ b/prototypes/micropython/tests/e2e/fake-serial.js @@ -0,0 +1,106 @@ +// Replaces navigator.serial with one fake CP210x port wired to sim/bridge.py over WebSocket. +// Injected with page.addInitScript before the page runs. +(() => { + // bridge.py listens for WebSockets one port below its HTTP port. + const WS_URL = `ws://127.0.0.1:${Number(location.port) - 1}`; + const control = { + log: [], + requests: 0, + busy: false, + noBoard: false, + openGlitch: false + }; + + class FakePort { + constructor () { + this.readable = null; + this.writable = null; + this.ws = null; + } + + getInfo () { + return {usbVendorId: 0x10c4, usbProductId: 0xea60}; + } + + async open ({baudRate}) { + if (this.ws) throw new DOMException('The port is already open.', 'InvalidStateError'); + if (control.busy) throw new DOMException('Failed to open serial port.', 'NetworkError'); + const ws = new WebSocket(WS_URL); + ws.binaryType = 'arraybuffer'; + await new Promise((resolve, reject) => { + ws.onopen = resolve; + ws.onerror = () => reject(new DOMException('Failed to open serial port.', 'NetworkError')); + }); + this.ws = ws; + ws.send(JSON.stringify({t: 'baud', baud: baudRate})); + // Drivers commonly assert DTR and RTS when a port opens. openGlitch models an + // adapter that raises RTS before DTR, which pulses EN. + if (control.openGlitch) { + ws.send(JSON.stringify({t: 'signals', rts: true})); + ws.send(JSON.stringify({t: 'signals', dtr: true})); + } else { + ws.send(JSON.stringify({t: 'signals', dtr: true, rts: true})); + } + let ctrl; + this.readable = new ReadableStream({start (c) { ctrl = c; }}); + ws.onmessage = e => { + try { ctrl.enqueue(new Uint8Array(e.data)); } catch (err) { /* stream closed */ } + }; + ws.onclose = () => { + try { ctrl.close(); } catch (err) { /* already closed */ } + if (this.ws === ws) this.readable = null; + }; + this.writable = new WritableStream({ + write: chunk => { + if (ws.readyState === WebSocket.OPEN) ws.send(chunk); + } + }); + control.log.push({t: 'open', baud: baudRate}); + } + + async setSignals (s) { + if (!this.ws) throw new DOMException('The port is closed.', 'InvalidStateError'); + const m = {t: 'signals'}; + if ('dataTerminalReady' in s) m.dtr = s.dataTerminalReady; + if ('requestToSend' in s) m.rts = s.requestToSend; + this.ws.send(JSON.stringify(m)); + control.log.push(m); + } + + async close () { + if (!this.ws) throw new DOMException('The port is already closed.', 'InvalidStateError'); + if ((this.readable && this.readable.locked) || (this.writable && this.writable.locked)) { + throw new DOMException('Cannot close a port with locked streams.', 'InvalidStateError'); + } + const ws = this.ws; + this.ws = null; + this.readable = null; + this.writable = null; + ws.close(); + control.log.push({t: 'close'}); + } + } + + const port = new FakePort(); + let granted = false; + const listeners = {connect: new Set(), disconnect: new Set()}; + const serial = { + async requestPort () { + control.requests++; + if (control.noBoard) throw new DOMException('No port selected by the user.', 'NotFoundError'); + granted = true; + return port; + }, + async getPorts () { + return granted ? [port] : []; + }, + addEventListener (type, fn) { + if (listeners[type]) listeners[type].add(fn); + }, + removeEventListener (type, fn) { + if (listeners[type]) listeners[type].delete(fn); + } + }; + Object.defineProperty(Navigator.prototype, 'serial', {get: () => serial, configurable: true}); + window.__fakeSerial = control; +})(); diff --git a/prototypes/micropython/tests/e2e/page.spec.js b/prototypes/micropython/tests/e2e/page.spec.js new file mode 100644 index 00000000000..b010d3209d1 --- /dev/null +++ b/prototypes/micropython/tests/e2e/page.spec.js @@ -0,0 +1,293 @@ +// index.html driven in headless Chrome; navigator.serial is fake-serial.js -> sim/bridge.py. +const path = require('path'); +const {test, expect} = require('@playwright/test'); + +const FAKE_SERIAL = path.join(__dirname, 'fake-serial.js'); +let errors = []; + +async function resetSim (request, opts = {}) { + const res = await request.post('/__sim/reset', {data: opts}); + expect(res.ok()).toBeTruthy(); +} + +async function simState (request) { + return (await request.get('/__sim/state')).json(); +} + +async function simFile (request, p) { + return (await request.get(`/__sim/file?path=${encodeURIComponent(p)}`)).json(); +} + +async function openPage (page, {fake = true, query = ''} = {}) { + errors = []; + page.on('console', m => { + if (m.type() === 'error') errors.push(m.text()); + }); + page.on('pageerror', e => errors.push(e.message)); + if (fake) await page.addInitScript({path: FAKE_SERIAL}); + await page.goto(`/index.html${query}`); +} + +const status = page => page.locator('#status'); +const consoleText = page => page.locator('#console'); + +async function connectReady (page) { + await page.click('#connectBtn'); + await expect(status(page)).toHaveText('Ready', {timeout: 20000}); +} + +async function setProgram (page, code) { + await page.fill('#editor', code); +} + +test.afterEach(async ({request}) => { + expect(errors, 'console errors').toEqual([]); + const s = await simState(request); + expect(s.files.filter(f => f.endsWith('.tmp')), 'leftover .tmp files').toEqual([]); + expect(s.paste_violations, 'raw-paste flow-control violations').toBe(0); +}); + +test('probe with the library missing, install, then TB_INFO OK', async ({page, request}) => { + await resetSim(request); + await openPage(page); + await page.click('#connectBtn'); + await expect(status(page)).toHaveText('Library missing', {timeout: 15000}); + await expect(page.locator('#errorHint')).toContainText('Install library'); + await page.click('#installLibBtn'); + await expect(status(page)).toHaveText('Ready', {timeout: 30000}); + await expect(consoleText(page)).toContainText('TB_INFO OK'); + await expect(page.locator('#boardInfo')).toContainText('TinkerBit Maker ESP32'); + const s = await simState(request); + for (const f of ['/boot.py', '/main.py', '/lib/tinkerbit/__init__.py', '/lib/tinkerbit/board.py', '/lib/ssd1306.py']) { + expect(s.files).toContain(f); + } + expect(s.resets, 'opening the port must not reset the board').toBe(0); +}); + +test('Run streams output while the program runs', async ({page, request}) => { + await resetSim(request, {install_library: true}); + await openPage(page); + await connectReady(page); + await setProgram(page, "import time\nprint('start')\ntime.sleep(2)\nprint('end')\n"); + await page.click('#runBtn'); + await expect(consoleText(page)).toContainText('start', {timeout: 5000}); + await expect(status(page)).toHaveText('Running'); + await expect(consoleText(page)).not.toContainText('end'); + await expect(consoleText(page)).toContainText('end', {timeout: 5000}); + await expect(status(page)).toHaveText('Ready'); +}); + +test('Upload writes main.py and it runs after the reset', async ({page, request}) => { + await resetSim(request, {install_library: true}); + await openPage(page); + await connectReady(page); + const code = "import tinkerbit\nprint('hello from main')\n"; + await setProgram(page, code); + await page.click('#uploadBtn'); + await expect(consoleText(page)).toContainText('hello from main', {timeout: 10000}); + await expect(consoleText(page)).toContainText('Program finished', {timeout: 10000}); + await expect(status(page)).toHaveText('Ready'); + expect((await simFile(request, '/main.py')).text).toBe(code); +}); + +test('Upload with base64 and chunked transfer', async ({page, request}) => { + await resetSim(request, {install_library: true}); + await openPage(page); + await connectReady(page); + await page.selectOption('#transferMode', 'chunked'); + await page.selectOption('#encoding', 'base64'); + const code = `# ${'x'.repeat(5000)}\nprint('big upload ok')\n`; + await setProgram(page, code); + await page.click('#uploadBtn'); + await expect(consoleText(page)).toContainText('big upload ok', {timeout: 15000}); + expect((await simFile(request, '/main.py')).text).toBe(code); +}); + +test('Stop breaks an infinite loop started with Run', async ({page, request}) => { + await resetSim(request, {install_library: true}); + await openPage(page); + await connectReady(page); + await setProgram(page, 'while True:\n pass\n'); + await page.click('#runBtn'); + await expect(status(page)).toHaveText('Running'); + await page.waitForTimeout(300); + await page.click('#stopBtn'); + await expect(status(page)).toHaveText('Ready', {timeout: 5000}); + await expect(page.locator('#errorHint')).toHaveText('Stopped.'); +}); + +test('Stop breaks an uploaded infinite loop', async ({page, request}) => { + await resetSim(request, {install_library: true}); + await openPage(page); + await connectReady(page); + await setProgram(page, "import time\nwhile True:\n print('tick')\n time.sleep_ms(200)\n"); + await page.click('#uploadBtn'); + await expect(consoleText(page)).toContainText('tick', {timeout: 10000}); + await page.click('#stopBtn'); + await expect(status(page)).toHaveText('Ready', {timeout: 5000}); +}); + +test('safe mode recovers a stuck main.py (Ctrl-C disabled) on connect and with Recover', async ({page, request}) => { + const stuck = "import micropython\nmicropython.kbd_intr(-1)\nopen('/stuck', 'w').close()\nwhile True:\n pass\n"; + await resetSim(request, {install_library: true, files: {'/main.py': stuck}}); + // Connecting while main.py is still starting lets Ctrl-C in before kbd_intr(-1). + await expect.poll(async () => (await simState(request)).files, {timeout: 10000}).toContain('/stuck'); + await openPage(page); + await page.click('#connectBtn'); + await expect(status(page)).toHaveText('Ready', {timeout: 20000}); + await expect(consoleText(page)).toContainText('Safe mode: main.py skipped'); + await page.click('#recoverBtn'); + await expect(consoleText(page)).toContainText('Safe mode: main.py skipped'); + await expect(status(page)).toHaveText('Ready', {timeout: 20000}); + const s = await simState(request); + expect(s.resets).toBeGreaterThanOrEqual(2); +}); + +test('Stop falls back to hard reset + safe mode when Ctrl-C is ignored', async ({page, request}) => { + await resetSim(request, {install_library: true}); + await openPage(page); + await connectReady(page); + await setProgram(page, 'import micropython, time\nmicropython.kbd_intr(-1)\nwhile True:\n time.sleep_ms(10)\n'); + await page.click('#uploadBtn'); + await expect(status(page)).toHaveText('Running', {timeout: 10000}); + await page.waitForTimeout(800); + await page.click('#stopBtn'); + await expect(consoleText(page)).toContainText('hard reset into safe mode', {timeout: 5000}); + await expect(status(page)).toHaveText('Ready', {timeout: 15000}); +}); + +test('Stop turns motors and tones off after Run and after Upload', async ({page, request}) => { + const spin = "import tinkerbit, time\nm = tinkerbit.Motors()\nm.speed('A', 200)\ntinkerbit.Buzzer('A3').tone(440)\nprint('spinning')\nwhile True:\n time.sleep_ms(50)\n"; + await resetSim(request, {install_library: true}); + await openPage(page); + await connectReady(page); + await setProgram(page, spin); + await page.click('#runBtn'); + await expect(consoleText(page)).toContainText('spinning', {timeout: 10000}); + expect((await simState(request)).pwm_pins).toBeGreaterThan(0); + await page.click('#stopBtn'); + await expect(status(page)).toHaveText('Ready', {timeout: 5000}); + await expect.poll(async () => (await simState(request)).pwm_pins, {timeout: 5000}).toBe(0); + + await page.click('#uploadBtn'); + await expect(status(page)).toHaveText('Running', {timeout: 10000}); + await expect.poll(async () => (await simState(request)).pwm_pins, {timeout: 10000}).toBeGreaterThan(0); + await page.click('#stopBtn'); + await expect(status(page)).toHaveText('Ready', {timeout: 5000}); + await expect.poll(async () => (await simState(request)).pwm_pins, {timeout: 5000}).toBe(0); + const boot = await simFile(request, '/tb_boot.json'); + expect(JSON.parse(boot.text).off).toEqual(['A3']); +}); + +test('jack conflict and ADC2 + WiFi show friendly text', async ({page, request}) => { + await resetSim(request, {install_library: true}); + await openPage(page); + await connectReady(page); + await setProgram(page, "import tinkerbit\ntinkerbit.Led('D13')\ntinkerbit.Rfid('3D')\n"); + await page.click('#runBtn'); + await expect(page.locator('#errorLine')).toContainText("3D and D13 can't be used together", {timeout: 5000}); + await expect(status(page)).toHaveText('Ready'); + await setProgram(page, "import tinkerbit, network\nnetwork.WLAN(network.STA_IF).active(True)\nprint(tinkerbit.Pot('A1').read())\n"); + await page.click('#runBtn'); + await expect(page.locator('#errorLine')).toContainText('A ports are off while Cloud/WiFi is on', {timeout: 5000}); + await setProgram(page, "import tinkerbit\ntinkerbit.Led('D5')\n"); + await page.click('#runBtn'); + await expect(page.locator('#errorLine')).toContainText('D5 is only for the distance sensor', {timeout: 5000}); +}); + +test('Live commands', async ({page, request}) => { + await resetSim(request, {install_library: true}); + await openPage(page); + await connectReady(page); + const live = page.locator('#liveInput'); + await live.fill('1 + 2'); + await live.press('Enter'); + await expect(consoleText(page)).toContainText('>>> 1 + 2\n3', {timeout: 5000}); + await expect(live).toBeEnabled(); + await live.fill('import tinkerbit'); + await live.press('Enter'); + await expect(live).toBeEnabled({timeout: 5000}); + await live.fill("tinkerbit.Led('D13').on()"); + await live.press('Enter'); + await expect(live).toBeEnabled({timeout: 5000}); + await expect.poll(async () => (await simState(request)).jacks.D13).toBe(1); + await live.fill("tinkerbit.Led('D13').value()"); + await live.press('Enter'); + await expect(consoleText(page)).toContainText("tinkerbit.Led('D13').value()\n1", {timeout: 5000}); + await live.fill('nope('); + await live.press('Enter'); + await expect(page.locator('#errorLine')).toContainText('SyntaxError', {timeout: 5000}); +}); + +test('stale .tmp files are removed on connect', async ({page, request}) => { + await resetSim(request, {install_library: true, files: {'/main.py.tmp': 'half written', '/lib/x.py.tmp': 'half'}}); + await openPage(page); + await connectReady(page); + await expect(consoleText(page)).toContainText('Removed unfinished files'); +}); + +test('HC-05 program: Upload only, 9600 monitor, Stop returns to 115200', async ({page, request}) => { + await resetSim(request, {install_library: true}); + await openPage(page); + await connectReady(page); + const prog = "import tinkerbit, time\nbt = tinkerbit.HC05()\nbt.send('ready')\nwhile True:\n l = bt.read_line()\n if l is not None:\n bt.send('echo:' + l)\n time.sleep_ms(10)\n"; + await setProgram(page, prog); + await page.click('#runBtn'); + await expect(page.locator('#errorLine')).toHaveText('HC-05 programs run with Upload only.'); + await page.click('#uploadBtn'); + await expect(status(page)).toHaveText('HC-05 at 9600', {timeout: 10000}); + await expect(consoleText(page)).toContainText('ready', {timeout: 5000}); + expect((await simState(request)).host_baud).toBe(9600); + await page.locator('#liveInput').fill('ping'); + await page.locator('#liveInput').press('Enter'); + await expect(consoleText(page)).toContainText('echo:ping', {timeout: 5000}); + await page.click('#stopBtn'); + await expect(status(page)).toHaveText('Ready', {timeout: 15000}); + const s = await simState(request); + expect(s.host_baud).toBe(115200); + expect(s.uart_baud).toBe(115200); +}); + +test('busy port names the apps to close', async ({page, request}) => { + await resetSim(request); + await openPage(page); + await page.evaluate(() => { window.__fakeSerial.busy = true; }); + await page.click('#connectBtn'); + await expect(page.locator('#errorLine')).toContainText('Arduino IDE, Thonny, PuTTY or other TinkerBit tabs'); + await expect(status(page)).toHaveText('Disconnected'); +}); + +test('cancelled picker suggests a data cable', async ({page, request}) => { + await resetSim(request); + await openPage(page); + await expect(page.locator('text=No board listed? Try a data cable')).toBeVisible(); + await page.evaluate(() => { window.__fakeSerial.noBoard = true; }); + await page.click('#connectBtn'); + await expect(page.locator('#errorHint')).toContainText('data cable'); +}); + +test('browser without Web Serial', async ({page, request}) => { + await resetSim(request); + await page.addInitScript(() => { delete Navigator.prototype.serial; }); + await openPage(page, {fake: false}); + await expect(page.locator('#unsupported')).toBeVisible(); + await expect(page.locator('#unsupported')).toContainText('Use desktop Chrome or Edge'); + await expect(page.locator('#connectBtn')).toBeDisabled(); +}); + +test('no MicroPython on the board offers firmware install', async ({page, request}) => { + await resetSim(request, {firmware: 'none'}); + await openPage(page); + await page.click('#connectBtn'); + await expect(status(page)).toHaveText('No MicroPython', {timeout: 20000}); + await expect(page.locator('#installFwBtn')).toBeVisible(); +}); + +test('Stage B firmware: frozen library, safe mode into raw REPL', async ({page, request}) => { + const stuck = 'import micropython\nmicropython.kbd_intr(-1)\nwhile True:\n pass\n'; + await resetSim(request, {firmware: 'stage_b', files: {'/main.py': stuck}}); + await openPage(page); + await page.click('#connectBtn'); + await expect(status(page)).toHaveText('Ready', {timeout: 20000}); + await expect(page.locator('#boardInfo')).toContainText('(tinkerbit)'); +}); diff --git a/prototypes/micropython/tests/test_checks.py b/prototypes/micropython/tests/test_checks.py new file mode 100644 index 00000000000..14ee7bcb0a7 --- /dev/null +++ b/prototypes/micropython/tests/test_checks.py @@ -0,0 +1,57 @@ +"""The hardware check scripts run end to end in the simulator (numbers are meaningless here).""" +import json +import os +import re + +from conftest import PROTO, read +from test_cloud import CONFIG + + +def mic_records(out): + return [json.loads(l[len("TB_MIC "):]) for l in out.splitlines() if l.startswith("TB_MIC ")] + + +def test_check2_stage_a_reports_python_rates_only(board): + b, h = board + out, err = h.exec_paste(read("checks/check2_mic_rate.py"), timeout=60) + assert err == "" + kinds = {r["kind"]: r for r in mic_records(out)} + assert set(kinds) == {"python_free_running", "python_paced", "c_sampler"} + assert "error" in kinds["c_sampler"] + + +def test_check2_stage_b_runs_c_sampler(make_board): + b, h = make_board(firmware="stage_b") + h.read_until(">>> ") + h.enter_raw() + out, err = h.exec_paste(read("checks/check2_mic_rate.py"), timeout=60) + assert err == "" + c = [r for r in mic_records(out) if r["kind"] == "c_sampler"][0] + assert c["rate_hz"] == 8000 and c["result"] == "PASS" + + +def test_check1_reaches_mqtt_record(make_board): + b, h = make_board(firmware="stage_b") + h.read_until(">>> ") + h.enter_raw() + h.install_files({"/config.json": json.dumps(CONFIG)}) + h.write(read("checks/check1_cloud_memory.py").encode() + b"\x04") + h.read_until(b"OK") + h.read_until(b'"tag": "mqtt"', timeout=20) + h.write(b"\x03") + out, err = h._result(5) + assert "KeyboardInterrupt" in err + assert CONFIG["wifi_password"] not in h.log.decode("utf-8", "replace") + + +def test_gpio_numbers_only_in_board_py(): + paths = [os.path.join(PROTO, "index.html"), os.path.join(PROTO, "firmware", "frozen", "_boot.py")] + for folder in ("checks", os.path.join("lib", "tinkerbit")): + for name in os.listdir(os.path.join(PROTO, folder)): + if name.endswith(".py") and name != "board.py": + paths.append(os.path.join(PROTO, folder, name)) + for p in paths: + with open(p, encoding="utf-8") as f: + src = f.read() + assert not re.search(r"Pin\(\s*\d", src), p + assert not re.search(r"(?i)\bgpio\s*\d", src), p diff --git a/prototypes/micropython/tests/test_cloud.py b/prototypes/micropython/tests/test_cloud.py new file mode 100644 index 00000000000..ee0a2f9d507 --- /dev/null +++ b/prototypes/micropython/tests/test_cloud.py @@ -0,0 +1,185 @@ +"""tinkerbit.cloud wrapper against the simulated tbcloud module (Stage B).""" +import json + +from conftest import gpio, read + +CONFIG = { + "wifi_ssid": "test-ssid", + "wifi_password": "not-a-real-password", + "host": "test.mosquitto.org", + "port": 8886, + "ws_port": 8081, + "device_id": "proto-001", + "token": "not-a-real-token", +} +BEGIN = "from tinkerbit import cloud\ncloud.begin()\nprint(cloud.connected())\n" + + +def stage_b(make_board, config=True): + b, h = make_board(firmware="stage_b") + h.read_until(">>> ") + h.enter_raw() + if config: + h.install_files({"/config.json": json.dumps(CONFIG)}) + return b, h + + +def online(make_board): + b, h = stage_b(make_board) + out, err = h.exec_raw(BEGIN) + assert err == "" and out.splitlines()[-1] == "True" + return b, h, out + + +def sent(b, suffix): + return [p for t, p in b.cloud_sent if t == "tb/proto-001/" + suffix] + + +def test_cloud_begin_prints_the_checklist_lines(make_board): + b, h, out = online(make_board) + lines = out.splitlines() + assert lines[:5] == [ + 'Cloud: joining WiFi "test-ssid"', + "Cloud: WiFi connected (RSSI -55)", + "Cloud: connecting to mqtts://test.mosquitto.org:8886", + "Cloud: connected (port 8886)", + "True", + ] + assert b.cloud["port"] == 8886 and b.cloud["ws_port"] == 8081 and b.cloud["has_token"] + assert b.cloud["subscribed"] == "tb/proto-001/state/#" + status = json.loads(b.cloud["retained"]["status"]) + assert status["s"] == "online" and status["fw"] == "mpy-1" and status["tr"] == "mqtts" + # Secrets never reach the serial log. + log = h.log.decode("utf-8", "replace") + assert "not-a-real-password" not in log and "not-a-real-token" not in log + + +def test_cloud_heartbeat_then_readings_in_the_service_format(make_board): + b, h, out = online(make_board) + boot = b.cloud["boot"] + assert sent(b, "telemetry") == ['{"seq":1,"boot":"%s","v":{}}' % boot] + out, err = h.exec_raw("print(cloud.send({'temp': 21.456, 'moving': True, 'count': 3}))") + assert err == "" and out.strip() == "True" + # Within the 5 s minimum gap: waits. + assert len(sent(b, "telemetry")) == 1 + b.cloud_skew_ms += 5000 + h.exec_raw("cloud.status()") + assert sent(b, "telemetry")[-1] == '{"seq":2,"boot":"%s","v":{"temp":21.46,"moving":1,"count":3}}' % boot + # set() alone waits for the interval; None stops reporting; NaN is skipped. + h.exec_raw("cloud.set('count', None)\ncloud.set('temp', float('nan'))") + b.cloud_skew_ms += 10000 + h.exec_raw("cloud.status()") + assert sent(b, "telemetry")[-1] == '{"seq":3,"boot":"%s","v":{"moving":1}}' % boot + + +def test_cloud_reading_names_and_limit(make_board): + b, h, out = online(make_board) + out, err = h.exec_raw("cloud.set('bad name', 1)") + assert "reading names use letters, digits and _" in err + out, err = h.exec_raw("print([cloud.set('r%d' % i, i) for i in range(25)][-2:])") + assert out.strip() == "[True, False]" + + +def test_dashboard_controls_ack_and_failsafe(make_board): + b, h, out = online(make_board) + b.cloud_message("switch1", '{"v":1,"ver":7}') + b.cloud_message("slider2", '{"v":150,"ver":8,"fs":2,"fv":30}') + out, err = h.exec_raw("print(cloud.switch(1), cloud.slider(2), cloud.switch(3))") + assert err == "" + assert out.splitlines() == ["Cloud: switch1 = 1", "Cloud: slider2 = 100", "1 100 0"] + assert sent(b, "ack") == ['{"key":"switch1","ver":7}', '{"key":"slider2","ver":8}'] + # Broker gone: slider2 falls back after its 2 s, switch1 after the default 120 s. + b.cloud_broker_down = True + h.exec_raw("cloud.status()") + b.cloud_skew_ms += 2000 + out, err = h.exec_raw("print(cloud.switch(1), cloud.slider(2))") + assert out.splitlines() == ["Cloud: offline 2s - slider2 set to safe value 30", "1 30"] + b.cloud_skew_ms += 118000 + out, err = h.exec_raw("print(cloud.switch(1))") + lines = out.splitlines() + assert lines[0] == "Cloud: offline 120s - switch1 set to safe value 0" and lines[-1] == "0" + assert len(lines) == 6 # every control still on the default 120 s, like the Arduino firmware + + +def test_disconnect_and_reconnect_lines(make_board): + b, h, out = online(make_board) + b.cloud_broker_down = True + out, err = h.exec_raw("print(cloud.connected())") + assert out.splitlines() == ["Cloud: disconnected - retrying", "False"] + b.cloud_broker_down = False + out, err = h.exec_raw("print(cloud.connected(), cloud.status()['reconnects'])") + assert out.splitlines() == ["Cloud: connected (port 8886)", "True 1"] + + +def test_alerts_rate_limited_and_queued_offline(make_board): + b, h, out = online(make_board) + out, err = h.exec_raw("print(cloud.alert('Too hot'))\nprint(cloud.alert('Still hot'))\nprint(cloud.alert('Again'))") + assert out.splitlines() == ['Cloud: alert "Too hot"', "True", "Cloud: alert skipped (at most one every 10 s)", "False", "False"] + h.exec_raw("cloud.status()") + assert sent(b, "alert") == ["Too hot"] + b.cloud_broker_down = True + b.cloud_skew_ms += 10000 + out, err = h.exec_raw("print(cloud.alert('x' * 600))") + assert out.splitlines()[-1] == "True" + assert '(sends when connected)' in out + b.cloud_broker_down = False + h.exec_raw("cloud.status()") + assert sent(b, "alert")[-1] == "x" * 483 + + +def test_stop_all_ends_the_cloud(make_board): + b, h, out = online(make_board) + out, err = h.exec_raw("import tinkerbit\ntinkerbit.stop_all()\nprint(cloud.connected())") + assert err == "" and out.strip() == "False" + assert b.cloud == {} and not b.wifi_on + assert b.cloud_sent[-1] == ("tb/proto-001/status", "offline") + + +def test_cloud_before_begin(make_board): + b, h = stage_b(make_board) + out, err = h.exec_raw("from tinkerbit import cloud\ncloud.switch(1)") + assert "Call cloud.begin() first." in err + + +def test_cloud_locks_a_jacks(make_board): + b, h = stage_b(make_board) + out, err = h.exec_raw("import tinkerbit\nfrom tinkerbit import cloud\ncloud.begin()\ntinkerbit.Pot('A1')") + assert "A ports are off while Cloud/WiFi is on" in err + + +def test_cloud_refuses_when_a_jack_in_use(make_board): + b, h = stage_b(make_board) + out, err = h.exec_raw("import tinkerbit\nfrom tinkerbit import cloud\ntinkerbit.Pot('A2')\ncloud.begin()") + assert "Move the potentiometer from A2 to D13" in err + assert not b.wifi_on + + +def test_cloud_and_bluetooth_never_together(make_board): + b, h = stage_b(make_board) + out, err = h.exec_raw("import tinkerbit\nfrom tinkerbit import cloud\ncloud.begin()\ntinkerbit.bluetooth(True)") + assert "Cloud and Bluetooth can't run together" in err + + +def test_cloud_missing_config(make_board): + b, h = stage_b(make_board, config=False) + out, err = h.exec_raw("from tinkerbit import cloud\ncloud.begin()") + assert "Cloud settings missing" in err + + +def test_cloud_needs_stage_b(board): + b, h = board + h.install_files({"/lib/tinkerbit/cloud.py": read("lib/tinkerbit/cloud.py")}) + out, err = h.exec_raw("from tinkerbit import cloud\ncloud.begin()") + assert "Cloud needs TinkerBit firmware (Stage B)" in err + + +def test_c_sampler_shape(make_board): + b, h = stage_b(make_board, config=False) + b.analog[gpio("A1")] = 1234 + out, err = h.exec_raw( + "import array, machine, tbsys\nfrom tinkerbit import board\n" + "adc = machine.ADC(machine.Pin(board.pin('A1')), atten=machine.ADC.ATTN_11DB)\n" + "buf = array.array('h', bytes(200))\nr = tbsys.sample(adc, buf, 8000)\nprint(len(r), r[0], buf[0], buf[99])" + ) + assert err == "" + assert out.split() == ["4", "8000", "1234", "1234"] diff --git a/prototypes/micropython/tests/test_library.py b/prototypes/micropython/tests/test_library.py new file mode 100644 index 00000000000..b335c13a906 --- /dev/null +++ b/prototypes/micropython/tests/test_library.py @@ -0,0 +1,332 @@ +"""The tinkerbit library running inside the simulator, driven through the raw REPL.""" +import json +import os +import re +import time + +from conftest import BOARD_MAP, PROTO, gpio, library_files + + +def run(h, code): + out, err = h.exec_raw(code) + assert err == "", err + return out + + +def run_err(h, code): + out, err = h.exec_raw(code) + assert err, "expected an error, got output %r" % out + return err.strip().splitlines()[-1] + + +def test_info_prints_one_tb_info_line(board): + b, h = board + out = run(h, "import tinkerbit\ntinkerbit.info()") + lines = [l for l in out.splitlines() if l] + assert len(lines) == 1 and lines[0].startswith("TB_INFO ") + data = json.loads(lines[0][len("TB_INFO "):]) + for key in ("board", "rev", "mcu", "lib", "api", "jacks", "uid", "mpy", "flash_free", "heap_free", "reset", "up_ms"): + assert key in data, key + assert data["uid"] == b.uid.hex() + assert data["mpy"] == "1.24.1" + assert data["jacks"] == len(BOARD_MAP.JACKS) + assert data["reset"] == "power_on" + + +def test_default_main_blinks_reports_and_exits_fast(board): + b, h = board + h.install_files({"/main.py": library_files()["/main.py"]}) + t0 = time.monotonic() + h.soft_reset_run_main() + out = h.read_until(">>> ").decode() + assert "TB_INFO " in out + assert time.monotonic() - t0 < 1.5 + assert (gpio("D13"), 1) in b.pin_log and b.pins[gpio("D13")]["value"] == 0 + + +def test_boot_py_drives_relays_high_without_importing_library(board): + b, h = board + h.soft_reset_run_main() + h.read_until(">>> ") + for role in ("a1", "a2", "b1", "b2"): + assert b.pins[gpio("MD", role)]["value"] == 1 + h.enter_raw() + assert run(h, "import sys\nprint('tinkerbit' in sys.modules)").strip() == "False" + + +def test_begin_twice_and_relays_high(board): + b, h = board + run(h, "import tinkerbit\ntinkerbit.begin()\ntinkerbit.begin()") + for role in ("a1", "a2", "b1", "b2"): + assert b.pins[gpio("MD", role)]["value"] == 1 + + +def test_one_object_per_jack(board): + b, h = board + assert run(h, "import tinkerbit\nprint(tinkerbit.Led('D13') is tinkerbit.Led('D13'))").strip() == "True" + assert run(h, "print(tinkerbit.Oled('I2C') is tinkerbit.Oled('I2C1'))").strip() == "True" + + +def test_two_parts_on_one_jack(board): + b, h = board + run(h, "import tinkerbit\ntinkerbit.Led('A2')") + assert "A2 already has the LED" in run_err(h, "tinkerbit.Button('A2')") + + +def test_d13_and_3d_conflict(board): + b, h = board + run(h, "import tinkerbit\ntinkerbit.Led('D13')") + msg = run_err(h, "tinkerbit.Rfid('3D')") + assert "3D and D13 can't be used together" in msg and "TinkerBitError" in msg + + +def test_digital_part_on_d5(board): + b, h = board + msg = run_err(h, "import tinkerbit\ntinkerbit.Led('D5')") + assert "D5 is only for the distance sensor" in msg + + +def test_unknown_jack(board): + b, h = board + assert "There is no jack called Z9" in run_err(h, "import tinkerbit\ntinkerbit.Led('Z9')") + + +def test_analog_part_needs_a_jack(board): + b, h = board + assert "needs an A jack" in run_err(h, "import tinkerbit\ntinkerbit.Pot('D13')") + + +def test_a_jack_refused_while_cloud_on(board): + b, h = board + msg = run_err(h, "import tinkerbit\ntinkerbit.radio(True)\ntinkerbit.Pot('A1')") + assert "A ports are off while Cloud/WiFi is on" in msg + + +def test_a_jack_read_fails_friendly_when_program_starts_wifi(board): + b, h = board + run(h, "import tinkerbit\np = tinkerbit.Pot('A1')\nprint(p.read())") + msg = run_err(h, "import network\nnetwork.WLAN(network.STA_IF).active(True)\np.read()") + assert "A ports are off while Cloud/WiFi is on" in msg + + +def test_pot_average_and_soil_percent(board): + b, h = board + b.analog[gpio("A1")] = 1000 + b.analog[gpio("A2")] = 2200 + out = run(h, "import tinkerbit\nprint(tinkerbit.Pot('A1').read(), tinkerbit.Soil('A2').percent())") + assert out.split() == ["1000", "50"] + b.analog[gpio("A2")] = 0 + assert run(h, "print(tinkerbit.Soil('A2').percent())").strip() == "-1" + + +def test_on_off_sensors_follow_their_active_level(board): + b, h = board + run(h, "import tinkerbit\nir = tinkerbit.Obstacle('D13')\npir = tinkerbit.Pir('A1')") + b.inputs[gpio("D13")] = 0 + b.inputs[gpio("A1")] = 0 + assert run(h, "print(ir.detected(), pir.detected())").split() == ["True", "False"] + b.inputs[gpio("D13")] = 1 + b.inputs[gpio("A1")] = 1 + assert run(h, "print(ir.detected(), pir.detected())").split() == ["False", "True"] + assert b.pins[gpio("D13")]["mode"] == "in" + + +def test_soil_percent_from_one_reading(board): + b, h = board + out = run(h, "import tinkerbit\ns = tinkerbit.Soil('A2')\nprint(s.percent_from(2200), s.percent_from(10), s.percent_from(4000))") + assert out.split() == ["50", "-1", "0"] + + +def test_oled_show_clears_and_wraps(board): + b, h = board + run(h, "import tinkerbit\no = tinkerbit.Oled()\no.text('old', 3)\no.show('0123456789abcdefWRAP')") + assert b.screen == [("0123456789abcdef", 0, 0), ("WRAP", 0, 8)] + + +def test_motion_read_is_one_measurement(board): + b, h = board + b.i2c_devices[0x68].accel = (16384, 0, 0) + assert run(h, "import tinkerbit\nprint(tinkerbit.Motion().read())").strip() == "(90, 0)" + + +def test_ultrasonic_cm_and_invalid(board): + b, h = board + assert run(h, "import tinkerbit\nu = tinkerbit.Ultrasonic()\nprint(u.cm())").strip() == "20" + b.echo_us = None + assert run(h, "print(u.cm())").strip() == "-1" + assert b.pins[gpio("D5", "echo")]["mode"] == "in" + + +def test_dht11(board): + b, h = board + assert run(h, "import tinkerbit\nd = tinkerbit.DHT11('A1')\nprint(d.temperature(), d.humidity())").split() == ["24", "55"] + b.dht_default = None + out = run(h, "d2 = tinkerbit.DHT11('A3')\nprint(d2.temperature())") + assert out.strip().endswith("-1") and "DHT11 not answering" in out + + +def test_oled_text(board): + b, h = board + run(h, "import tinkerbit\no = tinkerbit.Oled()\no.text('Hello', 0)\no.number(42, 1)") + assert b.screen == [("Hello", 0, 0), ("42", 0, 8)] + assert b.i2c_freq == BOARD_MAP.I2C_FREQ + + +def test_oled_missing_is_friendly(board): + b, h = board + del b.i2c_devices[0x3C] + assert "OLED screen not found" in run_err(h, "import tinkerbit\ntinkerbit.Oled().text('x')") + + +def test_motion_flat_tilted_and_missing(board): + b, h = board + assert run(h, "import tinkerbit\nm = tinkerbit.Motion()\nprint(m.tilt(), m.shake())").split() == ["0", "0"] + b.i2c_devices[0x68].accel = (16384, 0, 0) + assert run(h, "print(m.tilt())").strip() == "90" + b.i2c_devices[0x68].accel = (0, 0, 16384) + b.i2c_devices[0x68].gyro = (131 * 250, 0, 0) + assert int(run(h, "print(m.shake())")) == 50 + del b.i2c_devices[0x68] + out = run(h, "m2 = tinkerbit.Motion('I2C1')\nprint(m2 is m)\nm._ready = False\nm._retry_at = None\nprint(m.shake())") + assert "MPU6050 not found" in out and out.strip().endswith("-1") + + +def test_led_brightness_and_stop_all(board): + b, h = board + run(h, "import tinkerbit\nl = tinkerbit.Led('D13')\nl.brightness(128)\nbz = tinkerbit.Buzzer('A3')\nbz.on()") + assert b.pwm[gpio("D13")].duty_u16() == 128 * 257 + run(h, "tinkerbit.stop_all()") + assert gpio("D13") not in b.pwm + assert b.pins[gpio("D13")]["value"] == 0 and b.pins[gpio("A3")]["value"] == 0 + for role in ("a1", "a2", "b1", "b2"): + assert b.pins[gpio("MD", role)]["value"] == 1 + + +def test_motion_parts_and_stop_all(board): + b, h = board + run(h, "import tinkerbit\n" + "sv = tinkerbit.Servo('D13')\n" + "m = tinkerbit.Motors('MD')\n" + "m.speed('A', 200)\n" + "m.speed('B', 100, forward=False)\n" + "bz = tinkerbit.Buzzer('A3')\n" + "bz.tone(440)\n" + "st = tinkerbit.Stepper('ST')\n") + # Servo starts at 90 degrees, like the Arduino sketch: 1450 us of a 20 ms period. + assert abs(b.pwm[gpio("D13")].duty_ns() - 1450000) < 1000 + assert run(h, "print(sv.angle(180))").strip() == "180" + assert abs(b.pwm[gpio("D13")].duty_ns() - 2400000) < 1000 + assert b.pwm[gpio("MD", "a1")].duty_u16() == 200 * 257 and b.pwm[gpio("MD", "a2")].duty_u16() == 0 + assert b.pwm[gpio("MD", "b1")].duty_u16() == 0 and b.pwm[gpio("MD", "b2")].duty_u16() == 100 * 257 + assert b.pwm[gpio("A3")].freq() == 440 + run(h, "st.move(8, 60)") + assert all(b.pins[gpio("ST", r)]["value"] == 0 for r in ("in1", "in2", "in3", "in4")) + # Stop: no PWM left anywhere, motor inputs braked HIGH, buzzer LOW. + run(h, "tinkerbit.stop_all()") + assert b.pwm == {} + for role in ("a1", "a2", "b1", "b2"): + assert b.pins[gpio("MD", role)]["value"] == 1 + assert b.pins[gpio("A3")]["value"] == 0 + + +def test_relay4_is_active_low(board): + b, h = board + run(h, "import tinkerbit\nr = tinkerbit.Relay4()\nr.channel(2, True)") + assert b.pins[gpio("MD", "a2")]["value"] == 0 and b.pins[gpio("MD", "a1")]["value"] == 1 + run(h, "r.all(True)") + assert all(b.pins[gpio("MD", r)]["value"] == 0 for r in ("a1", "a2", "b1", "b2")) + run(h, "tinkerbit.stop_all()") + assert all(b.pins[gpio("MD", r)]["value"] == 1 for r in ("a1", "a2", "b1", "b2")) + assert "MD already has the 4-channel relay" in run_err(h, "tinkerbit.Motors('MD')") + + +def test_pwm_timers_run_out_like_the_esp32(board): + b, h = board + pins = [gpio(j) for j in ("A1", "A2", "A3", "D13")] + [gpio("MD", r) for r in ("a1", "a2", "b1", "b2")] + pins.append(gpio("I2C", "sda")) + msg = run_err(h, "import machine\n" + "ps = [machine.PWM(machine.Pin(p), freq=100 + i) for i, p in enumerate(%r)]" % (pins,)) + assert "out of PWM timers" in msg + + +def test_pump_lock_buzzer_stay_off_from_boot(board): + b, h = board + h.install_files({"/main.py": ( + "import tinkerbit, time\n" + "p = tinkerbit.Pump('A2')\n" + "lk = tinkerbit.Lock('D13')\n" + "p.on()\n" + "time.sleep_ms(300)\n" + "print('pump on')\n" + )}) + h.soft_reset_run_main() + h.read_until("pump on") + h.read_until(">>> ") + assert json.loads(b.read_file("/tb_boot.json")) == {"off": ["A2", "D13"]} + # Next boot: boot.py drives both LOW before main.py runs, then main.py turns the pump on. + b.pin_log.clear() + h.soft_reset_run_main() + h.read_until(">>> ") + first = [entry for entry in b.pin_log if entry[0] in (gpio("A2"), gpio("D13"))][:2] + assert sorted(first) == sorted([(gpio("A2"), 0), (gpio("D13"), 0)]) + # A program without them drops them from the list once it records its own part. + h.enter_raw() + h.install_files({"/main.py": "import tinkerbit\ntinkerbit.Buzzer('A3')\n"}) + h.exit_raw() + h.soft_reset_run_main() + h.read_until(">>> ") + assert json.loads(b.read_file("/tb_boot.json")) == {"off": ["A3"]} + + +def test_button_pull_up(board): + b, h = board + assert run(h, "import tinkerbit\nbt = tinkerbit.Button('A2')\nprint(bt.pressed())").strip() == "False" + b.inputs[gpio("A2")] = 0 + assert run(h, "print(bt.pressed())").strip() == "True" + + +def test_a4_boot_pin_note(board): + b, h = board + assert "A4 is the BOOT pin" in run(h, "import tinkerbit\ntinkerbit.Button('A4')") + + +def test_hc05_upload_only_at_9600(board): + b, h = board + h.install_files({"/main.py": ( + "import tinkerbit, time\n" + "bt = tinkerbit.HC05()\n" + "bt.send('ready')\n" + "while True:\n" + " line = bt.read_line()\n" + " if line is not None:\n" + " bt.send('echo:' + line)\n" + " time.sleep_ms(10)\n" + )}) + h.soft_reset_run_main() + b.set_host_baud(9600) + h.read_until("ready\r\n") + h.write(b"hi\x03there\n") + assert "echo:hi\x03there" in h.read_until("there\r\n").decode() + # Ctrl-C is just data now: Stop needs a hard reset, then safe mode, then 115200. + h.write(b"\x03\x03") + time.sleep(0.2) + assert ">>>" not in h.text() + b.set_host_baud(115200) + for _ in range(10): + assert h.recover() + h.read_until(">>> ") + assert b.uart_baud == 115200 + + +def test_no_bare_except_and_gpio_only_in_board_py(): + lib = os.path.join(PROTO, "lib", "tinkerbit") + sources = {} + for root in (lib, PROTO): + for name in os.listdir(root): + if name.endswith(".py"): + with open(os.path.join(root, name), encoding="utf-8") as f: + sources[os.path.join(root, name)] = f.read() + for path, src in sources.items(): + assert not re.search(r"except\s*:", src), path + if not path.endswith("board.py"): + assert not re.search(r"Pin\(\s*\d", src), path diff --git a/prototypes/micropython/tests/test_parts_ported.py b/prototypes/micropython/tests/test_parts_ported.py new file mode 100644 index 00000000000..45b70495cca --- /dev/null +++ b/prototypes/micropython/tests/test_parts_ported.py @@ -0,0 +1,230 @@ +"""RFID (RC522), heartbeat (MAX30102) and Bluetooth LE in the tinkerbit library, on the simulated +board. The beat detector is also checked against a second implementation with C integer types.""" +import ctypes +import importlib.util +import math +import os + +from conftest import PROTO + + +def run(h, code): + out, err = h.exec_raw(code) + assert err == "", err + return out + + +def run_err(h, code): + out, err = h.exec_raw(code) + assert err, "expected an error, got output %r" % out + return err.strip().splitlines()[-1] + + +# ---------------- RFID ---------------- + +def test_rfid_no_card(board): + b, h = board + assert run(h, "import tinkerbit\nr = tinkerbit.Rfid('3D')\nprint(repr(r.card()))").strip() == "''" + + +def test_rfid_reads_a_card_once_until_it_is_put_back(board): + b, h = board + run(h, "import tinkerbit\nr = tinkerbit.Rfid('3D')") + b.spi_device.put_card(b"\xde\xad\x0b\xef") + assert run(h, "print(r.card())").strip() == "dead0bef" + # Halted: a card left on the reader is not read again (Arduino PICC_IsNewCardPresent). + assert run(h, "print(repr(r.card()))").strip() == "''" + b.spi_device.take_card() + b.spi_device.put_card(b"\xde\xad\x0b\xef") + assert run(h, "print(r.read())").strip() == "dead0bef" + + +def test_rfid_seven_byte_uid(board): + b, h = board + b.spi_device.put_card(bytes(range(1, 8))) + assert run(h, "import tinkerbit\nprint(tinkerbit.Rfid().card())").strip() == "01020304050607" + assert b.spi_device.selected == 1 + + +def test_rfid_missing_reader_says_so_once_and_is_found_later(board): + b, h = board + b.spi_device.version = 0x00 + out = run(h, "import tinkerbit\ntinkerbit.FIND_AGAIN_MS = 0\nr = tinkerbit.Rfid('3D')\n" + "print(repr(r.card()))\nprint(repr(r.card()))") + assert out.count("RFID reader not found - check the 3D cable.") == 1 + assert out.count("''") == 2 + b.spi_device.version = 0x92 + b.spi_device.put_card(b"\x01\x02\x03\x04") + assert run(h, "print(r.card())").strip() == "01020304" + + +def test_rfid_cable_pulled_while_running(board): + b, h = board + run(h, "import tinkerbit\ntinkerbit.FIND_AGAIN_MS = 0\nr = tinkerbit.Rfid('3D')\nr.card()") + b.spi_device = None + assert run(h, "print(repr(r.card()))\nprint(r._dev)").split() == ["''", "None"] + + +# ---------------- Heartbeat ---------------- + +def test_heartbeat_no_finger_is_zero(board): + b, h = board + assert run(h, "import tinkerbit\nprint(tinkerbit.Heartbeat('I2C1').bpm())").strip() == "0" + + +def test_heartbeat_counts_a_steady_pulse(board): + b, h = board + b.i2c_devices[0x57].finger_bpm = 72 + out = run(h, "import tinkerbit, time\nhb = tinkerbit.Heartbeat()\nv = []\n" + "for _ in range(35):\n v.append(hb.bpm())\n time.sleep_ms(100)\nprint(v[-1])") + assert 66 <= int(out.strip()) <= 78, out + + +def test_heartbeat_slow_loop_still_counts_right(board): + # Reads 250 ms apart: the FIFO keeps the samples in between, beats are timed by sample number. + b, h = board + b.i2c_devices[0x57].finger_bpm = 90 + out = run(h, "import tinkerbit, time\nhb = tinkerbit.Heartbeat()\n" + "for _ in range(16):\n v = hb.bpm()\n time.sleep_ms(250)\nprint(v)") + assert 82 <= int(out.strip()) <= 98, out + + +def test_heartbeat_finger_lifted_goes_to_zero(board): + b, h = board + b.i2c_devices[0x57].finger_bpm = 72 + run(h, "import tinkerbit, time\nhb = tinkerbit.Heartbeat()\nfor _ in range(30):\n hb.bpm()\n time.sleep_ms(100)") + b.i2c_devices[0x57].finger_bpm = None + assert run(h, "time.sleep_ms(50)\nprint(hb.bpm())").strip() == "0" + + +def test_heartbeat_missing_sensor(board): + b, h = board + del b.i2c_devices[0x57] + out = run(h, "import tinkerbit\ntinkerbit.FIND_AGAIN_MS = 0\nhb = tinkerbit.Heartbeat()\nprint(hb.bpm())\nprint(hb.bpm())") + assert out.count("Heartbeat sensor (HW-605) not found - check the I2C cable and 3.3V.") == 1 + assert out.split()[-2:] == ["-1", "-1"] + + +def _load_max30102(): + spec = importlib.util.spec_from_file_location("tb_max30102", os.path.join(PROTO, "lib", "tinkerbit", "max30102.py")) + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + return mod + + +class _ReferenceBeat: + """heartRate.cpp again, written with ctypes integer types instead of masks.""" + FIR = (172, 321, 579, 927, 1360, 1858, 2390, 2916, 3391, 3768, 4012, 4096) + + def __init__(self): + i16 = ctypes.c_int16 + self.ac_max, self.ac_min = i16(20), i16(-20) + self.cur, self.prev = i16(0), i16(0) + self.sig_min, self.sig_max = i16(0), i16(0) + self.pos = self.neg = 0 + self.reg = ctypes.c_int32(0) + self.cbuf = [i16(0) for _ in range(32)] + self.offset = 0 + + def check(self, sample): + beat = False + self.prev = ctypes.c_int16(self.cur.value) + x = ctypes.c_uint16(sample).value + self.reg = ctypes.c_int32(self.reg.value + ((ctypes.c_int32(x << 15).value - self.reg.value) >> 4)) + avg = ctypes.c_int16(self.reg.value >> 15).value + din = ctypes.c_int16(ctypes.c_int32(sample - avg).value) + self.cbuf[self.offset] = din + z = ctypes.c_int32(self.FIR[11] * self.cbuf[(self.offset - 11) & 0x1F].value) + for i in range(11): + z = ctypes.c_int32(z.value + self.FIR[i] * self.cbuf[(self.offset - i) & 0x1F].value) + z = ctypes.c_int32(z.value + self.FIR[i] * self.cbuf[(self.offset - 22 + i) & 0x1F].value) + self.offset = (self.offset + 1) % 32 + self.cur = ctypes.c_int16(z.value >> 15) + cur, prev = self.cur.value, self.prev.value + if prev < 0 and cur >= 0: + self.ac_max, self.ac_min = ctypes.c_int16(self.sig_max.value), ctypes.c_int16(self.sig_min.value) + self.pos, self.neg = 1, 0 + self.sig_max = ctypes.c_int16(0) + if 20 < self.ac_max.value - self.ac_min.value < 1000: + beat = True + if prev > 0 and cur <= 0: + self.pos, self.neg = 0, 1 + self.sig_min = ctypes.c_int16(0) + if self.pos and cur > prev: + self.sig_max = ctypes.c_int16(cur) + if self.neg and cur < prev: + self.sig_min = ctypes.c_int16(cur) + return beat + + +def test_beat_detector_matches_the_c_integer_rules(): + mod = _load_max30102() + ours, ref = mod.BeatDetector(), _ReferenceBeat() + beats = 0 + # DC levels across the 16-bit wrap points the C code truncates at, a pulse, and noise. + for n in range(6000): + dc = (60000, 65535, 98304, 131072, 250000)[n // 1200] + s = int(dc + 300 * math.sin(n * 2 * math.pi / 80) + ((n * 7919) % 41) - 20) + a, r = ours.check(s), ref.check(s) + assert a == r and ours.cur == ref.cur.value, n + beats += a + assert beats > 25 + + +# ---------------- Bluetooth LE ---------------- + +SERVICE_LE = bytes.fromhex("4fafc2011fb5459e8fccc5c9c331914b")[::-1] + + +def test_ble_advertises_the_arduino_service_and_name(board): + b, h = board + run(h, "import tinkerbit\nble = tinkerbit.Ble('ESP')\nble.advertise('Desk Lamp')") + adv = b.ble["advertising"] + assert SERVICE_LE in adv["adv"] + assert adv["resp"] == bytes((10, 0x09)) + b"Desk Lamp" + assert b.ble["name"] == b"Desk Lamp" + assert list(b.ble["values"].values()) == [b"ready"] + + +def test_ble_same_name_does_not_restart_advertising(board): + b, h = board + run(h, "import tinkerbit\nble = tinkerbit.Ble()\nfor _ in range(5):\n ble.advertise('TinkerBit')") + assert b.ble["adverts"] == 1 + run(h, "ble.advertise('Other')") + assert b.ble["adverts"] == 2 and b.ble["name"] == b"Other" + + +def test_ble_send_keeps_20_bytes_and_notifies_a_phone(board): + b, h = board + run(h, "import tinkerbit\nble = tinkerbit.Ble()\nble.advertise('TB')\nble.send('no phone yet')") + assert b.ble["notified"] == [] + b.ble_connect(1) + assert b.ble["advertising"] is None + out = run(h, "print(ble.connected())\nprint(ble.send('Hello from TinkerBit board'))") + assert out.split()[0] == "True" + assert b.ble["notified"] == [(1, b"Hello from TinkerBit")] + b.ble_disconnect(1) + assert b.ble["advertising"] is not None + assert run(h, "print(ble.connected())").strip() == "False" + + +def test_ble_long_name_is_cut_on_a_character_boundary(board): + b, h = board + run(h, "import tinkerbit\ntinkerbit.Ble().advertise('Jardin ' + '\u00e9' * 20)") + name = b.ble["name"] + assert len(name) <= 29 + name.decode("utf-8") + + +def test_ble_off_after_stop_all_and_on_again(board): + b, h = board + run(h, "import tinkerbit\nble = tinkerbit.Ble()\nble.advertise('TB')\ntinkerbit.stop_all()") + assert b.ble["active"] is False + run(h, "ble.advertise('TB')") + assert b.ble["active"] is True and b.ble["advertising"] is not None + + +def test_ble_refused_while_cloud_is_on(board): + b, h = board + msg = run_err(h, "import tinkerbit\ntinkerbit.radio(True)\ntinkerbit.Ble()") + assert "Cloud and Bluetooth can't run together" in msg diff --git a/prototypes/micropython/tests/test_sim.py b/prototypes/micropython/tests/test_sim.py new file mode 100644 index 00000000000..46dc8c5dc2d --- /dev/null +++ b/prototypes/micropython/tests/test_sim.py @@ -0,0 +1,224 @@ +"""Protocol and boot behaviour of the simulator (raw REPL, raw-paste, resets, safe mode).""" +import re +import time + +from conftest import library_files, read + + +def test_power_on_boots_to_friendly_repl_and_creates_boot_py(make_board): + b, h = make_board() + out = h.read_until(">>> ").decode() + assert "rst:0x1 (POWERON_RESET)" in out + assert "MicroPython v1.24.1" in out + assert "/boot.py" in b.files() + + +def test_raw_repl_exec_and_framing(make_board): + b, h = make_board() + h.read_until(">>> ") + h.enter_raw() + h.write(b"print(1+1)\x04") + assert h.read_until(b">") == b"OK2\r\n\x04\x04>" + + +def test_raw_repl_exception_goes_after_first_eof(make_board): + b, h = make_board() + h.read_until(">>> ") + h.enter_raw() + out, err = h.exec_raw("print('a')\nundefined_name") + assert out == "a\r\n" + assert err.startswith("Traceback (most recent call last):") + assert err.strip().endswith("NameError: name 'undefined_name' is not defined") + + +def test_globals_persist_between_raw_commands(make_board): + b, h = make_board() + h.read_until(">>> ") + h.enter_raw() + h.exec_raw("x = 41") + assert h.exec_raw("print(x + 1)") == ("42\r\n", "") + + +def test_raw_paste_honours_flow_control(make_board): + b, h = make_board() + h.read_until(">>> ") + h.enter_raw() + code = "\n".join("v%d = %d" % (i, i) for i in range(400)) + "\nprint(v399)\n" + assert len(code) > 4000 + assert h.exec_paste(code) == ("399\r\n", "") + assert b.paste_violations == 0 + + +def test_raw_paste_without_flow_control_is_detected(make_board): + b, h = make_board() + h.read_until(">>> ") + h.enter_raw() + code = "#" + "x" * 2000 + "\nprint('done')\n" + h.exec_paste(code, honor_flow=False) + assert b.paste_violations > 0 + + +def test_ctrl_c_stops_an_infinite_loop(make_board): + b, h = make_board() + h.read_until(">>> ") + h.enter_raw() + h.write(b"while True:\n pass\x04") + h.read_until(b"OK") + time.sleep(0.2) + h.write(b"\x03") + out, err = h._result(3) + assert "KeyboardInterrupt" in err + + +def test_ctrl_c_stops_sleep_loop(make_board): + b, h = make_board() + h.read_until(">>> ") + h.enter_raw() + h.write(b"import time\nwhile True:\n time.sleep(1)\x04") + h.read_until(b"OK") + time.sleep(0.2) + h.write(b"\x03") + assert "KeyboardInterrupt" in h._result(3)[1] + + +def test_friendly_soft_reset_runs_boot_then_main(make_board): + b, h = make_board() + h.read_until(">>> ") + h.enter_raw() + h.install_files({"/boot.py": "print('BOOT')\n", "/main.py": "print('MAIN')\n"}) + h.soft_reset_run_main() + out = h.read_until(">>> ").decode() + assert out.index("BOOT") < out.index("MAIN") + + +def test_raw_soft_reset_skips_main(make_board): + b, h = make_board() + h.read_until(">>> ") + h.enter_raw() + h.install_files({"/main.py": "print('MAIN')\n"}) + h.write(b"\x04") + out = h.read_until(b"raw REPL; CTRL-B to exit\r\n>").decode() + assert "soft reboot" in out and "MAIN" not in out + + +def test_boot_py_exception_skips_main(make_board): + b, h = make_board() + h.read_until(">>> ") + h.enter_raw() + h.install_files({"/boot.py": "raise Exception('stop')\n", "/main.py": "print('MAIN')\n"}) + h.soft_reset_run_main() + out = h.read_until(">>> ").decode() + assert "Exception: stop" in out and "MAIN" not in out + + +def test_open_without_glitch_does_not_reset(make_board): + b, h = make_board() + h.read_until(">>> ") + h.open_port(glitch=False) + assert b.resets == 0 + + +def test_open_with_rts_first_glitch_resets(make_board): + b, h = make_board() + h.read_until(">>> ") + h.open_port(glitch=True) + assert b.resets == 1 + + +def test_hard_reset_through_rts(make_board): + b, h = make_board() + h.read_until(">>> ") + h.clear() + h.hard_reset() + assert "POWERON_RESET" in h.read_until(">>> ").decode() + assert b.boots == 2 + + +def test_esptool_classic_sequence_enters_download_mode(make_board): + b, h = make_board() + h.read_until(">>> ") + b.set_signals(dtr=False, rts=True) + time.sleep(0.05) + b.set_signals(dtr=True, rts=False) + assert "waiting for download" in h.read_until("download").decode() + "download" + + +def _stuck_board(make_board, firmware): + b, h = make_board(firmware=firmware) + h.read_until(">>> ") + h.enter_raw() + files = library_files(with_main=False) + files["/main.py"] = "while True:\n pass\n" + h.install_files(files) + return b, h + + +def test_safe_mode_stage_a_recovers_stuck_main_10_of_10(make_board): + b, h = _stuck_board(make_board, "stage_a") + for _ in range(10): + assert h.recover() + h.read_until(">>> ") + h.enter_raw() + assert h.exec_raw("print('alive')") == ("alive\r\n", "") + assert b.rx_overflow == 0 + + +def test_safe_mode_stage_b_recovers_stuck_main_10_of_10(make_board): + b, h = _stuck_board(make_board, "stage_b") + for _ in range(10): + assert h.recover() + # Stage B lands directly in the raw REPL. + h.read_until(b"raw REPL; CTRL-B to exit\r\n>") + h.enter_raw() + assert h.exec_raw("print('alive')") == ("alive\r\n", "") + + +def test_without_safe_mode_stuck_main_ignores_ctrl_a(make_board): + b, h = _stuck_board(make_board, "stage_a") + h.clear() + h.hard_reset() + time.sleep(0.6) + h.write(b"\x01") + time.sleep(0.2) + assert "raw REPL" not in h.text() + # Ctrl-C still works for a plain loop. + h.enter_raw() + + +def test_uart0_baud_change_garbles_and_survives_soft_reset(make_board): + b, h = make_board() + h.read_until(">>> ") + h.enter_raw() + h.write(b"import machine\nmachine.UART(0, baudrate=9600)\nprint('at9600')\x04") + time.sleep(0.3) + assert "at9600" not in h.text() + b.set_host_baud(9600) + h.clear() + h.write(b"\x02") + h.read_until(b">>> ") + h.write(b"\x04") + h.read_until(b"MPY: soft reboot\r\n") + h.read_until(b">>> ") + assert b.uart_baud == 9600 + h.hard_reset() + b.set_host_baud(115200) + h.read_until(">>> ") + assert b.uart_baud == 115200 + + +def test_stage_b_has_native_modules_and_frozen_library(make_board): + b, h = make_board(firmware="stage_b") + h.read_until(">>> ") + h.enter_raw() + out, err = h.exec_raw("import tinkerbit, tbsys, tbcloud\nprint(tinkerbit.VERSION)") + version = re.search(r'^VERSION = "([^"]+)"', read("lib/tinkerbit/__init__.py"), re.M).group(1) + assert err == "" and out.strip() == version + assert not [f for f in b.files() if f.startswith("/lib/")] + + +def test_firmware_none_never_gives_a_repl(make_board): + b, h = make_board(firmware="none") + time.sleep(0.3) + h.write(b"\r\x03\x03\x01") + time.sleep(0.3) + assert "raw REPL" not in h.text() diff --git a/prototypes/micropython/tests/test_studio_programs.py b/prototypes/micropython/tests/test_studio_programs.py new file mode 100644 index 00000000000..a5c8adece14 --- /dev/null +++ b/prototypes/micropython/tests/test_studio_programs.py @@ -0,0 +1,127 @@ +"""The MicroPython Beginner Studio writes (src/beginner-studio/domain/pycodegen.js), run on the +simulated board with the tinkerbit library: every built-in template it fully supports must start, +loop with its sensors both idle and triggered, and stop on Ctrl-C without any error. Cloud +templates run on the TinkerBit firmware (Stage B) with the files Studio puts there: boot.py and +/config.json.""" +import json +import os +import re +import shutil +import subprocess +import time + +import pytest + +from conftest import PROTO, gpio, library_files, read + +# Test values only, like test_cloud.py: never a real network or device key. +CLOUD_CONFIG = { + "wifi_ssid": "test-ssid", + "wifi_password": "not-a-real-password", + "host": "test.mosquitto.org", + "port": 8886, + "ws_port": 8081, + "device_id": "proto-001", + "token": "not-a-real-token", +} + +REPO = os.path.dirname(os.path.dirname(PROTO)) +NODE = shutil.which("node") + + +def _programs(): + if not NODE: + return {} + out = subprocess.run([NODE, os.path.join(PROTO, "tools", "studio_python.js")], + cwd=REPO, capture_output=True, timeout=120) + if out.returncode: + raise RuntimeError(out.stderr.decode("utf-8", "replace")) + return json.loads(out.stdout.decode("utf-8")) + + +PROGRAMS = _programs() +RUNNABLE = sorted(k for k, v in PROGRAMS.items() if not v["gaps"] and not k.startswith("extra-")) +needs_node = pytest.mark.skipif(not NODE, reason="node is not installed") + +ERROR_LINE = re.compile(r"\b\w+(Error|Exception)\b") + + +@needs_node +def test_every_template_is_valid_python(): + assert len(PROGRAMS) > 50 + for tid, p in PROGRAMS.items(): + compile(p["code"], tid, "exec") + + +@needs_node +def test_most_templates_need_nothing_missing(): + assert len(RUNNABLE) > len(PROGRAMS) / 2 + + +@needs_node +@pytest.mark.parametrize("tid", RUNNABLE) +def test_template_runs_on_the_board(make_board, tid): + code = PROGRAMS[tid]["code"] + cloud = "from tinkerbit import cloud" in code + b, h = make_board(firmware="stage_b" if cloud else "stage_a") + h.read_until(">>> ") + h.enter_raw() + if cloud: + files = {"/boot.py": read("boot.py"), "/config.json": json.dumps(CLOUD_CONFIG)} + else: + files = library_files(with_main=False) + files["/main.py"] = code + h.install_files(files) + b.time_scale = 0.02 + h.soft_reset_run_main() + time.sleep(0.5) + # Triggered: buttons pressed, active-high sensors on, analog sensors high. + for jack in ("D13", "A1", "A2", "A3", "A4"): + b.inputs[gpio(jack)] = 0 if "btn" in PROGRAMS[tid]["code"] else 1 + b.analog[gpio(jack)] = 3500 + time.sleep(0.5) + for jack in ("D13", "A1", "A2", "A3", "A4"): + b.inputs[gpio(jack)] = 1 - b.inputs[gpio(jack)] + b.analog[gpio(jack)] = 300 + time.sleep(0.5) + h.write(b"\x03") + out = h.read_until(">>> ", timeout=5).decode("utf-8", "replace") + assert "TinkerBit Beginner ready" in out + errors = [l for l in out.splitlines() if ERROR_LINE.search(l)] + assert not errors, out[-1500:] + assert "KeyboardInterrupt" in out + if cloud: + assert 'Cloud: joining WiFi "test-ssid"' in out + assert "not-a-real-password" not in out and "not-a-real-token" not in out + # The loop ran: something printed after the program's own setup lines. + loop_lines = [l for l in out.splitlines() if l and "ready" not in l and "Traceback" not in l] + assert len(loop_lines) > 3, out[-800:] + + +@needs_node +def test_hc05_project_talks_at_9600_and_safe_mode_gets_the_board_back(make_board): + p = PROGRAMS["extra-hc05-echo"] + assert not p["gaps"] + b, h = make_board() + h.read_until(">>> ") + h.enter_raw() + files = library_files(with_main=False) + files["/main.py"] = p["code"] + h.install_files(files) + b.time_scale = 0.05 + h.soft_reset_run_main() + # Everything the program prints comes after the switch to 9600, the monitor's rate. + b.set_host_baud(9600) + out = h.read_until("HC-05: no data\r\n", timeout=5).decode("utf-8", "replace") + assert "TinkerBit Beginner ready" in out and "HC-05 ready on UART at 9600 baud" in out + h.write(b"hello\n") + out = h.read_until("got it\r\n", timeout=5).decode("utf-8", "replace") + assert "HC-05 RX=hello" in out + assert b.pins[gpio("D13")]["value"] == 1 + # Ctrl-C is data for the HC-05 now; Upload gets the board back with a reset plus safe mode. + h.write(b"\x03") + time.sleep(0.3) + b.set_host_baud(115200) + assert h.recover() + h.read_until(">>> ") + assert b.uart_baud == 115200 diff --git a/prototypes/micropython/tools/studio_python.js b/prototypes/micropython/tools/studio_python.js new file mode 100644 index 00000000000..cbab402a900 --- /dev/null +++ b/prototypes/micropython/tools/studio_python.js @@ -0,0 +1,58 @@ +/* eslint-disable no-console */ +// Prints the MicroPython that Beginner Studio writes for every built-in template, plus +// "extra-" projects for parts no template uses yet, as JSON: +// {"