initial commit

This commit is contained in:
Senad Uka
2017-11-19 15:16:07 +01:00
commit 0960216d5c
779 changed files with 266148 additions and 0 deletions

113
node_modules/es6-promise/CHANGELOG.md generated vendored Normal file
View File

@@ -0,0 +1,113 @@
# Master
# 4.0.5
* fix require('es6-promise/auto') for Node < 4
# 4.0.4
* fix asap when using https://github.com/Kinvey/titanium-sdk
# 4.0.3
* fix Readme links
# 4.0.2
* fix require('es6-promise/auto');
# 4.0.0
* no longer polyfill automatically, if needed one can still invoke
`require('es6-promise/auto')` directly.
# 3.3.1
* fix links in readme
# 3.3.0
* support polyfil on WebMAF (playstation env)
* fix tampering related bug global `constructor` was referenced by mistake.
* provide TS Typings
* increase compatibliity with sinon.useFakeTimers();
* update build tools (use rollup)
* directly export promise;
# 3.2.2
* IE8: use isArray
* update build dependencies
# 3.2.1
* fix race tampering issue
* use eslint
* fix Promise.all tampering
* remove unused code
* fix issues with NWJS/electron
# 3.2.0
* improve tamper resistence of Promise.all Promise.race and
Promise.prototype.then (note, this isn't complete, but addresses an exception
when used \w core-js, follow up work will address entirely)
* remove spec incompatible then chaining fast-path
* add eslint
* update build deps
# 3.1.2
* fix node detection issues with NWJS/electron
# 3.1.0
* improve performance of Promise.all when it encounters a non-promise input object input
* then/resolve tamper protection
* reduce AST size of promise constructor, to facilitate more inlining
* Update README.md with details about PhantomJS requirement for running tests
* Mangle and compress the minified version
# 3.0.1
* no longer include dist/test in npm releases
# 3.0.0
* use nextTick() instead of setImmediate() to schedule microtasks with node 0.10. Later versions of
nodes are not affected as they were already using nextTick(). Note that using nextTick() might
trigger a depreciation warning on 0.10 as described at https://github.com/cujojs/when/issues/410.
The reason why nextTick() is preferred is that is setImmediate() would schedule a macrotask
instead of a microtask and might result in a different scheduling.
If needed you can revert to the former behavior as follow:
var Promise = require('es6-promise').Promise;
Promise._setScheduler(setImmediate);
# 2.3.0
* #121: Ability to override the internal asap implementation
* #120: Use an ascii character for an apostrophe, for source maps
# 2.2.0
* #116: Expose asap() and a way to override the scheduling mechanism on Promise
* Lock to v0.2.3 of ember-cli
# 2.1.1
* Fix #100 via #105: tell browserify to ignore vertx require
* Fix #101 via #102: "follow thenable state, not own state"
# 2.1.0
* #59: Automatic polyfill. No need to invoke `ES6Promise.polyfill()` anymore.
* ... (see the commit log)
# 2.0.0
* re-sync with RSVP. Many large performance improvements and bugfixes.
# 1.0.0
* first subset of RSVP

19
node_modules/es6-promise/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,19 @@
Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors
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.

82
node_modules/es6-promise/README.md generated vendored Normal file
View File

@@ -0,0 +1,82 @@
# ES6-Promise (subset of [rsvp.js](https://github.com/tildeio/rsvp.js)) [![Build Status](https://travis-ci.org/stefanpenner/es6-promise.svg?branch=master)](https://travis-ci.org/stefanpenner/es6-promise)
This is a polyfill of the [ES6 Promise](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-promise-constructor). The implementation is a subset of [rsvp.js](https://github.com/tildeio/rsvp.js) extracted by @jakearchibald, if you're wanting extra features and more debugging options, check out the [full library](https://github.com/tildeio/rsvp.js).
For API details and how to use promises, see the <a href="http://www.html5rocks.com/en/tutorials/es6/promises/">JavaScript Promises HTML5Rocks article</a>.
## Downloads
* [es6-promise 27.86 KB (7.33 KB gzipped)](https://raw.githubusercontent.com/stefanpenner/es6-promise/master/dist/es6-promise.js)
* [es6-promise-auto 27.78 KB (7.3 KB gzipped)](https://raw.githubusercontent.com/stefanpenner/es6-promise/master/dist/es6-promise.auto.js) - Automatically provides/replaces `Promise` if missing or broken.
* [es6-promise-min 6.17 KB (2.4 KB gzipped)](https://raw.githubusercontent.com/stefanpenner/es6-promise/master/dist/es6-promise.min.js)
* [es6-promise-auto-min 6.19 KB (2.4 KB gzipped)](https://raw.githubusercontent.com/stefanpenner/es6-promise/master/dist/es6-promise.auto.min.js) - Minified version of `es6-promise-auto` above.
## Node.js
To install:
```sh
npm install es6-promise
```
To use:
```js
var Promise = require('es6-promise').Promise;
```
## Bower
To install:
```sh
bower install es6-promise --save
```
## Usage in IE<9
`catch` is a reserved word in IE<9, meaning `promise.catch(func)` throws a syntax error. To work around this, you can use a string to access the property as shown in the following example.
However, please remember that such technique is already provided by most common minifiers, making the resulting code safe for old browsers and production:
```js
promise['catch'](function(err) {
// ...
});
```
Or use `.then` instead:
```js
promise.then(undefined, function(err) {
// ...
});
```
## Auto-polyfill
To polyfill the global environment (either in Node or in the browser via CommonJS) use the following code snippet:
```js
require('es6-promise').polyfill();
```
Alternatively
```js
require('es6-promise/auto');
```
Notice that we don't assign the result of `polyfill()` to any variable. The `polyfill()` method will patch the global environment (in this case to the `Promise` name) when called.
## Building & Testing
You will need to have PhantomJS installed globally in order to run the tests.
`npm install -g phantomjs`
* `npm run build` to build
* `npm test` to run tests
* `npm start` to run a build watcher, and webserver to test
* `npm run test:server` for a testem test runner and watching builder

4
node_modules/es6-promise/auto.js generated vendored Normal file
View File

@@ -0,0 +1,4 @@
// This file can be required in Browserify and Node.js for automatic polyfill
// To use it: require('es6-promise/auto');
'use strict';
module.exports = require('./').polyfill();

1159
node_modules/es6-promise/dist/es6-promise.auto.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

1
node_modules/es6-promise/dist/es6-promise.auto.map generated vendored Normal file

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

1157
node_modules/es6-promise/dist/es6-promise.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

1
node_modules/es6-promise/dist/es6-promise.map generated vendored Normal file

File diff suppressed because one or more lines are too long

1
node_modules/es6-promise/dist/es6-promise.min.js generated vendored Normal file

File diff suppressed because one or more lines are too long

1
node_modules/es6-promise/dist/es6-promise.min.map generated vendored Normal file

File diff suppressed because one or more lines are too long

74
node_modules/es6-promise/es6-promise.d.ts generated vendored Normal file
View File

@@ -0,0 +1,74 @@
export interface Thenable <R> {
then <U> (onFulfilled?: (value: R) => U | Thenable<U>, onRejected?: (error: any) => U | Thenable<U>): Thenable<U>;
then <U> (onFulfilled?: (value: R) => U | Thenable<U>, onRejected?: (error: any) => void): Thenable<U>;
}
export class Promise <R> implements Thenable <R> {
/**
* If you call resolve in the body of the callback passed to the constructor,
* your promise is fulfilled with result object passed to resolve.
* If you call reject your promise is rejected with the object passed to resolve.
* For consistency and debugging (eg stack traces), obj should be an instanceof Error.
* Any errors thrown in the constructor callback will be implicitly passed to reject().
*/
constructor (callback: (resolve : (value?: R | Thenable<R>) => void, reject: (error?: any) => void) => void);
/**
* onFulfilled is called when/if "promise" resolves. onRejected is called when/if "promise" rejects.
* Both are optional, if either/both are omitted the next onFulfilled/onRejected in the chain is called.
* Both callbacks have a single parameter , the fulfillment value or rejection reason.
* "then" returns a new promise equivalent to the value you return from onFulfilled/onRejected after being passed through Promise.resolve.
* If an error is thrown in the callback, the returned promise rejects with that error.
*
* @param onFulfilled called when/if "promise" resolves
* @param onRejected called when/if "promise" rejects
*/
then <U> (onFulfilled?: (value: R) => U | Thenable<U>, onRejected?: (error: any) => U | Thenable<U>): Promise<U>;
then <U> (onFulfilled?: (value: R) => U | Thenable<U>, onRejected?: (error: any) => void): Promise<U>;
/**
* Sugar for promise.then(undefined, onRejected)
*
* @param onRejected called when/if "promise" rejects
*/
catch <U> (onRejected?: (error: any) => U | Thenable<U>): Promise<U>;
/**
* Make a new promise from the thenable.
* A thenable is promise-like in as far as it has a "then" method.
*/
static resolve (): Promise<void>;
static resolve <R> (value: R | Thenable<R>): Promise<R>;
/**
* Make a promise that rejects to obj. For consistency and debugging (eg stack traces), obj should be an instanceof Error
*/
static reject <R> (error: any): Promise<R>;
/**
* Make a promise that fulfills when every item in the array fulfills, and rejects if (and when) any item rejects.
* the array passed to all can be a mixture of promise-like objects and other objects.
* The fulfillment value is an array (in order) of fulfillment values. The rejection value is the first rejection value.
*/
static all<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(values: [T1 | Thenable<T1>, T2 | Thenable<T2>, T3 | Thenable<T3>, T4 | Thenable <T4>, T5 | Thenable<T5>, T6 | Thenable<T6>, T7 | Thenable<T7>, T8 | Thenable<T8>, T9 | Thenable<T9>, T10 | Thenable<T10>]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>;
static all<T1, T2, T3, T4, T5, T6, T7, T8, T9>(values: [T1 | Thenable<T1>, T2 | Thenable<T2>, T3 | Thenable<T3>, T4 | Thenable <T4>, T5 | Thenable<T5>, T6 | Thenable<T6>, T7 | Thenable<T7>, T8 | Thenable<T8>, T9 | Thenable<T9>]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>;
static all<T1, T2, T3, T4, T5, T6, T7, T8>(values: [T1 | Thenable<T1>, T2 | Thenable<T2>, T3 | Thenable<T3>, T4 | Thenable <T4>, T5 | Thenable<T5>, T6 | Thenable<T6>, T7 | Thenable<T7>, T8 | Thenable<T8>]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8]>;
static all<T1, T2, T3, T4, T5, T6, T7>(values: [T1 | Thenable<T1>, T2 | Thenable<T2>, T3 | Thenable<T3>, T4 | Thenable <T4>, T5 | Thenable<T5>, T6 | Thenable<T6>, T7 | Thenable<T7>]): Promise<[T1, T2, T3, T4, T5, T6, T7]>;
static all<T1, T2, T3, T4, T5, T6>(values: [T1 | Thenable<T1>, T2 | Thenable<T2>, T3 | Thenable<T3>, T4 | Thenable <T4>, T5 | Thenable<T5>, T6 | Thenable<T6>]): Promise<[T1, T2, T3, T4, T5, T6]>;
static all<T1, T2, T3, T4, T5>(values: [T1 | Thenable<T1>, T2 | Thenable<T2>, T3 | Thenable<T3>, T4 | Thenable <T4>, T5 | Thenable<T5>]): Promise<[T1, T2, T3, T4, T5]>;
static all<T1, T2, T3, T4>(values: [T1 | Thenable<T1>, T2 | Thenable<T2>, T3 | Thenable<T3>, T4 | Thenable <T4>]): Promise<[T1, T2, T3, T4]>;
static all<T1, T2, T3>(values: [T1 | Thenable<T1>, T2 | Thenable<T2>, T3 | Thenable<T3>]): Promise<[T1, T2, T3]>;
static all<T1, T2>(values: [T1 | Thenable<T1>, T2 | Thenable<T2>]): Promise<[T1, T2]>;
static all<T1>(values: [T1 | Thenable<T1>]): Promise<[T1]>;
static all<TAll>(values: Array<TAll | Thenable<TAll>>): Promise<TAll[]>;
/**
* Make a Promise that fulfills when any item fulfills, and rejects if any item rejects.
*/
static race <R> (promises: (R | Thenable<R>)[]): Promise<R>;
}
/**
* The polyfill method will patch the global environment (in this case to the Promise name) when called.
*/
export function polyfill (): void;

7
node_modules/es6-promise/lib/es6-promise.js generated vendored Normal file
View File

@@ -0,0 +1,7 @@
import Promise from './es6-promise/promise';
import polyfill from './es6-promise/polyfill';
// Strange compat..
Promise.polyfill = polyfill;
Promise.Promise = Promise;
export default Promise;

270
node_modules/es6-promise/lib/es6-promise/-internal.js generated vendored Normal file
View File

@@ -0,0 +1,270 @@
import {
objectOrFunction,
isFunction
} from './utils';
import {
asap
} from './asap';
import originalThen from './then';
import originalResolve from './promise/resolve';
export const PROMISE_ID = Math.random().toString(36).substring(16);
function noop() {}
const PENDING = void 0;
const FULFILLED = 1;
const REJECTED = 2;
const GET_THEN_ERROR = new ErrorObject();
function selfFulfillment() {
return new TypeError("You cannot resolve a promise with itself");
}
function cannotReturnOwn() {
return new TypeError('A promises callback cannot return that same promise.');
}
function getThen(promise) {
try {
return promise.then;
} catch(error) {
GET_THEN_ERROR.error = error;
return GET_THEN_ERROR;
}
}
function tryThen(then, value, fulfillmentHandler, rejectionHandler) {
try {
then.call(value, fulfillmentHandler, rejectionHandler);
} catch(e) {
return e;
}
}
function handleForeignThenable(promise, thenable, then) {
asap(promise => {
var sealed = false;
var error = tryThen(then, thenable, value => {
if (sealed) { return; }
sealed = true;
if (thenable !== value) {
resolve(promise, value);
} else {
fulfill(promise, value);
}
}, reason => {
if (sealed) { return; }
sealed = true;
reject(promise, reason);
}, 'Settle: ' + (promise._label || ' unknown promise'));
if (!sealed && error) {
sealed = true;
reject(promise, error);
}
}, promise);
}
function handleOwnThenable(promise, thenable) {
if (thenable._state === FULFILLED) {
fulfill(promise, thenable._result);
} else if (thenable._state === REJECTED) {
reject(promise, thenable._result);
} else {
subscribe(thenable, undefined, value => resolve(promise, value),
reason => reject(promise, reason))
}
}
function handleMaybeThenable(promise, maybeThenable, then) {
if (maybeThenable.constructor === promise.constructor &&
then === originalThen &&
maybeThenable.constructor.resolve === originalResolve) {
handleOwnThenable(promise, maybeThenable);
} else {
if (then === GET_THEN_ERROR) {
reject(promise, GET_THEN_ERROR.error);
} else if (then === undefined) {
fulfill(promise, maybeThenable);
} else if (isFunction(then)) {
handleForeignThenable(promise, maybeThenable, then);
} else {
fulfill(promise, maybeThenable);
}
}
}
function resolve(promise, value) {
if (promise === value) {
reject(promise, selfFulfillment());
} else if (objectOrFunction(value)) {
handleMaybeThenable(promise, value, getThen(value));
} else {
fulfill(promise, value);
}
}
function publishRejection(promise) {
if (promise._onerror) {
promise._onerror(promise._result);
}
publish(promise);
}
function fulfill(promise, value) {
if (promise._state !== PENDING) { return; }
promise._result = value;
promise._state = FULFILLED;
if (promise._subscribers.length !== 0) {
asap(publish, promise);
}
}
function reject(promise, reason) {
if (promise._state !== PENDING) { return; }
promise._state = REJECTED;
promise._result = reason;
asap(publishRejection, promise);
}
function subscribe(parent, child, onFulfillment, onRejection) {
let { _subscribers } = parent;
let { length } = _subscribers;
parent._onerror = null;
_subscribers[length] = child;
_subscribers[length + FULFILLED] = onFulfillment;
_subscribers[length + REJECTED] = onRejection;
if (length === 0 && parent._state) {
asap(publish, parent);
}
}
function publish(promise) {
let subscribers = promise._subscribers;
let settled = promise._state;
if (subscribers.length === 0) { return; }
let child, callback, detail = promise._result;
for (let i = 0; i < subscribers.length; i += 3) {
child = subscribers[i];
callback = subscribers[i + settled];
if (child) {
invokeCallback(settled, child, callback, detail);
} else {
callback(detail);
}
}
promise._subscribers.length = 0;
}
function ErrorObject() {
this.error = null;
}
const TRY_CATCH_ERROR = new ErrorObject();
function tryCatch(callback, detail) {
try {
return callback(detail);
} catch(e) {
TRY_CATCH_ERROR.error = e;
return TRY_CATCH_ERROR;
}
}
function invokeCallback(settled, promise, callback, detail) {
let hasCallback = isFunction(callback),
value, error, succeeded, failed;
if (hasCallback) {
value = tryCatch(callback, detail);
if (value === TRY_CATCH_ERROR) {
failed = true;
error = value.error;
value = null;
} else {
succeeded = true;
}
if (promise === value) {
reject(promise, cannotReturnOwn());
return;
}
} else {
value = detail;
succeeded = true;
}
if (promise._state !== PENDING) {
// noop
} else if (hasCallback && succeeded) {
resolve(promise, value);
} else if (failed) {
reject(promise, error);
} else if (settled === FULFILLED) {
fulfill(promise, value);
} else if (settled === REJECTED) {
reject(promise, value);
}
}
function initializePromise(promise, resolver) {
try {
resolver(function resolvePromise(value){
resolve(promise, value);
}, function rejectPromise(reason) {
reject(promise, reason);
});
} catch(e) {
reject(promise, e);
}
}
let id = 0;
function nextId() {
return id++;
}
function makePromise(promise) {
promise[PROMISE_ID] = id++;
promise._state = undefined;
promise._result = undefined;
promise._subscribers = [];
}
export {
nextId,
makePromise,
getThen,
noop,
resolve,
reject,
fulfill,
subscribe,
publish,
publishRejection,
initializePromise,
invokeCallback,
FULFILLED,
REJECTED,
PENDING,
handleMaybeThenable
};

120
node_modules/es6-promise/lib/es6-promise/asap.js generated vendored Normal file
View File

@@ -0,0 +1,120 @@
let len = 0;
let vertxNext;
let customSchedulerFn;
export var asap = function asap(callback, arg) {
queue[len] = callback;
queue[len + 1] = arg;
len += 2;
if (len === 2) {
// If len is 2, that means that we need to schedule an async flush.
// If additional callbacks are queued before the queue is flushed, they
// will be processed by this flush that we are scheduling.
if (customSchedulerFn) {
customSchedulerFn(flush);
} else {
scheduleFlush();
}
}
}
export function setScheduler(scheduleFn) {
customSchedulerFn = scheduleFn;
}
export function setAsap(asapFn) {
asap = asapFn;
}
const browserWindow = (typeof window !== 'undefined') ? window : undefined;
const browserGlobal = browserWindow || {};
const BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
const isNode = typeof self === 'undefined' && typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';
// test for web worker but not in IE10
const isWorker = typeof Uint8ClampedArray !== 'undefined' &&
typeof importScripts !== 'undefined' &&
typeof MessageChannel !== 'undefined';
// node
function useNextTick() {
// node version 0.10.x displays a deprecation warning when nextTick is used recursively
// see https://github.com/cujojs/when/issues/410 for details
return () => process.nextTick(flush);
}
// vertx
function useVertxTimer() {
if (typeof vertxNext !== 'undefined') {
return function() {
vertxNext(flush);
};
}
return useSetTimeout();
}
function useMutationObserver() {
let iterations = 0;
const observer = new BrowserMutationObserver(flush);
const node = document.createTextNode('');
observer.observe(node, { characterData: true });
return () => {
node.data = (iterations = ++iterations % 2);
};
}
// web worker
function useMessageChannel() {
const channel = new MessageChannel();
channel.port1.onmessage = flush;
return () => channel.port2.postMessage(0);
}
function useSetTimeout() {
// Store setTimeout reference so es6-promise will be unaffected by
// other code modifying setTimeout (like sinon.useFakeTimers())
const globalSetTimeout = setTimeout;
return () => globalSetTimeout(flush, 1);
}
const queue = new Array(1000);
function flush() {
for (let i = 0; i < len; i+=2) {
let callback = queue[i];
let arg = queue[i+1];
callback(arg);
queue[i] = undefined;
queue[i+1] = undefined;
}
len = 0;
}
function attemptVertx() {
try {
const r = require;
const vertx = r('vertx');
vertxNext = vertx.runOnLoop || vertx.runOnContext;
return useVertxTimer();
} catch(e) {
return useSetTimeout();
}
}
let scheduleFlush;
// Decide what async method to use to triggering processing of queued callbacks:
if (isNode) {
scheduleFlush = useNextTick();
} else if (BrowserMutationObserver) {
scheduleFlush = useMutationObserver();
} else if (isWorker) {
scheduleFlush = useMessageChannel();
} else if (browserWindow === undefined && typeof require === 'function') {
scheduleFlush = attemptVertx();
} else {
scheduleFlush = useSetTimeout();
}

114
node_modules/es6-promise/lib/es6-promise/enumerator.js generated vendored Normal file
View File

@@ -0,0 +1,114 @@
import {
isArray,
isMaybeThenable
} from './utils';
import {
noop,
reject,
fulfill,
subscribe,
FULFILLED,
REJECTED,
PENDING,
getThen,
handleMaybeThenable
} from './-internal';
import then from './then';
import Promise from './promise';
import originalResolve from './promise/resolve';
import originalThen from './then';
import { makePromise, PROMISE_ID } from './-internal';
export default Enumerator;
function Enumerator(Constructor, input) {
this._instanceConstructor = Constructor;
this.promise = new Constructor(noop);
if (!this.promise[PROMISE_ID]) {
makePromise(this.promise);
}
if (isArray(input)) {
this._input = input;
this.length = input.length;
this._remaining = input.length;
this._result = new Array(this.length);
if (this.length === 0) {
fulfill(this.promise, this._result);
} else {
this.length = this.length || 0;
this._enumerate();
if (this._remaining === 0) {
fulfill(this.promise, this._result);
}
}
} else {
reject(this.promise, validationError());
}
}
function validationError() {
return new Error('Array Methods must be provided an Array');
};
Enumerator.prototype._enumerate = function() {
let { length, _input } = this;
for (let i = 0; this._state === PENDING && i < length; i++) {
this._eachEntry(_input[i], i);
}
};
Enumerator.prototype._eachEntry = function(entry, i) {
let c = this._instanceConstructor;
let { resolve } = c;
if (resolve === originalResolve) {
let then = getThen(entry);
if (then === originalThen &&
entry._state !== PENDING) {
this._settledAt(entry._state, i, entry._result);
} else if (typeof then !== 'function') {
this._remaining--;
this._result[i] = entry;
} else if (c === Promise) {
let promise = new c(noop);
handleMaybeThenable(promise, entry, then);
this._willSettleAt(promise, i);
} else {
this._willSettleAt(new c(resolve => resolve(entry)), i);
}
} else {
this._willSettleAt(resolve(entry), i);
}
};
Enumerator.prototype._settledAt = function(state, i, value) {
let { promise } = this;
if (promise._state === PENDING) {
this._remaining--;
if (state === REJECTED) {
reject(promise, value);
} else {
this._result[i] = value;
}
}
if (this._remaining === 0) {
fulfill(promise, this._result);
}
};
Enumerator.prototype._willSettleAt = function(promise, i) {
let enumerator = this;
subscribe(promise, undefined, value => enumerator._settledAt(FULFILLED, i, value),
reason => enumerator._settledAt(REJECTED, i, reason));
};

35
node_modules/es6-promise/lib/es6-promise/polyfill.js generated vendored Normal file
View File

@@ -0,0 +1,35 @@
/*global self*/
import Promise from './promise';
export default function polyfill() {
let local;
if (typeof global !== 'undefined') {
local = global;
} else if (typeof self !== 'undefined') {
local = self;
} else {
try {
local = Function('return this')();
} catch (e) {
throw new Error('polyfill failed because global object is unavailable in this environment');
}
}
let P = local.Promise;
if (P) {
var promiseToString = null;
try {
promiseToString = Object.prototype.toString.call(P.resolve());
} catch(e) {
// silently ignored
}
if (promiseToString === '[object Promise]' && !P.cast){
return;
}
}
local.Promise = Promise;
}

383
node_modules/es6-promise/lib/es6-promise/promise.js generated vendored Normal file
View File

@@ -0,0 +1,383 @@
import {
isFunction
} from './utils';
import {
noop,
nextId,
PROMISE_ID,
initializePromise
} from './-internal';
import {
asap,
setAsap,
setScheduler
} from './asap';
import all from './promise/all';
import race from './promise/race';
import Resolve from './promise/resolve';
import Reject from './promise/reject';
import then from './then';
function needsResolver() {
throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
}
function needsNew() {
throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
}
/**
Promise objects represent the eventual result of an asynchronous operation. The
primary way of interacting with a promise is through its `then` method, which
registers callbacks to receive either a promise's eventual value or the reason
why the promise cannot be fulfilled.
Terminology
-----------
- `promise` is an object or function with a `then` method whose behavior conforms to this specification.
- `thenable` is an object or function that defines a `then` method.
- `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
- `exception` is a value that is thrown using the throw statement.
- `reason` is a value that indicates why a promise was rejected.
- `settled` the final resting state of a promise, fulfilled or rejected.
A promise can be in one of three states: pending, fulfilled, or rejected.
Promises that are fulfilled have a fulfillment value and are in the fulfilled
state. Promises that are rejected have a rejection reason and are in the
rejected state. A fulfillment value is never a thenable.
Promises can also be said to *resolve* a value. If this value is also a
promise, then the original promise's settled state will match the value's
settled state. So a promise that *resolves* a promise that rejects will
itself reject, and a promise that *resolves* a promise that fulfills will
itself fulfill.
Basic Usage:
------------
```js
let promise = new Promise(function(resolve, reject) {
// on success
resolve(value);
// on failure
reject(reason);
});
promise.then(function(value) {
// on fulfillment
}, function(reason) {
// on rejection
});
```
Advanced Usage:
---------------
Promises shine when abstracting away asynchronous interactions such as
`XMLHttpRequest`s.
```js
function getJSON(url) {
return new Promise(function(resolve, reject){
let xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onreadystatechange = handler;
xhr.responseType = 'json';
xhr.setRequestHeader('Accept', 'application/json');
xhr.send();
function handler() {
if (this.readyState === this.DONE) {
if (this.status === 200) {
resolve(this.response);
} else {
reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
}
}
};
});
}
getJSON('/posts.json').then(function(json) {
// on fulfillment
}, function(reason) {
// on rejection
});
```
Unlike callbacks, promises are great composable primitives.
```js
Promise.all([
getJSON('/posts'),
getJSON('/comments')
]).then(function(values){
values[0] // => postsJSON
values[1] // => commentsJSON
return values;
});
```
@class Promise
@param {function} resolver
Useful for tooling.
@constructor
*/
export default function Promise(resolver) {
this[PROMISE_ID] = nextId();
this._result = this._state = undefined;
this._subscribers = [];
if (noop !== resolver) {
typeof resolver !== 'function' && needsResolver();
this instanceof Promise ? initializePromise(this, resolver) : needsNew();
}
}
Promise.all = all;
Promise.race = race;
Promise.resolve = Resolve;
Promise.reject = Reject;
Promise._setScheduler = setScheduler;
Promise._setAsap = setAsap;
Promise._asap = asap;
Promise.prototype = {
constructor: Promise,
/**
The primary way of interacting with a promise is through its `then` method,
which registers callbacks to receive either a promise's eventual value or the
reason why the promise cannot be fulfilled.
```js
findUser().then(function(user){
// user is available
}, function(reason){
// user is unavailable, and you are given the reason why
});
```
Chaining
--------
The return value of `then` is itself a promise. This second, 'downstream'
promise is resolved with the return value of the first promise's fulfillment
or rejection handler, or rejected if the handler throws an exception.
```js
findUser().then(function (user) {
return user.name;
}, function (reason) {
return 'default name';
}).then(function (userName) {
// If `findUser` fulfilled, `userName` will be the user's name, otherwise it
// will be `'default name'`
});
findUser().then(function (user) {
throw new Error('Found user, but still unhappy');
}, function (reason) {
throw new Error('`findUser` rejected and we're unhappy');
}).then(function (value) {
// never reached
}, function (reason) {
// if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
// If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
});
```
If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
```js
findUser().then(function (user) {
throw new PedagogicalException('Upstream error');
}).then(function (value) {
// never reached
}).then(function (value) {
// never reached
}, function (reason) {
// The `PedgagocialException` is propagated all the way down to here
});
```
Assimilation
------------
Sometimes the value you want to propagate to a downstream promise can only be
retrieved asynchronously. This can be achieved by returning a promise in the
fulfillment or rejection handler. The downstream promise will then be pending
until the returned promise is settled. This is called *assimilation*.
```js
findUser().then(function (user) {
return findCommentsByAuthor(user);
}).then(function (comments) {
// The user's comments are now available
});
```
If the assimliated promise rejects, then the downstream promise will also reject.
```js
findUser().then(function (user) {
return findCommentsByAuthor(user);
}).then(function (comments) {
// If `findCommentsByAuthor` fulfills, we'll have the value here
}, function (reason) {
// If `findCommentsByAuthor` rejects, we'll have the reason here
});
```
Simple Example
--------------
Synchronous Example
```javascript
let result;
try {
result = findResult();
// success
} catch(reason) {
// failure
}
```
Errback Example
```js
findResult(function(result, err){
if (err) {
// failure
} else {
// success
}
});
```
Promise Example;
```javascript
findResult().then(function(result){
// success
}, function(reason){
// failure
});
```
Advanced Example
--------------
Synchronous Example
```javascript
let author, books;
try {
author = findAuthor();
books = findBooksByAuthor(author);
// success
} catch(reason) {
// failure
}
```
Errback Example
```js
function foundBooks(books) {
}
function failure(reason) {
}
findAuthor(function(author, err){
if (err) {
failure(err);
// failure
} else {
try {
findBoooksByAuthor(author, function(books, err) {
if (err) {
failure(err);
} else {
try {
foundBooks(books);
} catch(reason) {
failure(reason);
}
}
});
} catch(error) {
failure(err);
}
// success
}
});
```
Promise Example;
```javascript
findAuthor().
then(findBooksByAuthor).
then(function(books){
// found books
}).catch(function(reason){
// something went wrong
});
```
@method then
@param {Function} onFulfilled
@param {Function} onRejected
Useful for tooling.
@return {Promise}
*/
then: then,
/**
`catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
as the catch block of a try/catch statement.
```js
function findAuthor(){
throw new Error('couldn't find that author');
}
// synchronous
try {
findAuthor();
} catch(reason) {
// something went wrong
}
// async with promises
findAuthor().catch(function(reason){
// something went wrong
});
```
@method catch
@param {Function} onRejection
Useful for tooling.
@return {Promise}
*/
catch(onRejection) {
return this.then(null, onRejection);
}
};

View File

@@ -0,0 +1,52 @@
import Enumerator from '../enumerator';
/**
`Promise.all` accepts an array of promises, and returns a new promise which
is fulfilled with an array of fulfillment values for the passed promises, or
rejected with the reason of the first passed promise to be rejected. It casts all
elements of the passed iterable to promises as it runs this algorithm.
Example:
```javascript
let promise1 = resolve(1);
let promise2 = resolve(2);
let promise3 = resolve(3);
let promises = [ promise1, promise2, promise3 ];
Promise.all(promises).then(function(array){
// The array here would be [ 1, 2, 3 ];
});
```
If any of the `promises` given to `all` are rejected, the first promise
that is rejected will be given as an argument to the returned promises's
rejection handler. For example:
Example:
```javascript
let promise1 = resolve(1);
let promise2 = reject(new Error("2"));
let promise3 = reject(new Error("3"));
let promises = [ promise1, promise2, promise3 ];
Promise.all(promises).then(function(array){
// Code here never runs because there are rejected promises!
}, function(error) {
// error.message === "2"
});
```
@method all
@static
@param {Array} entries array of promises
@param {String} label optional string for labeling the promise.
Useful for tooling.
@return {Promise} promise that is fulfilled when all `promises` have been
fulfilled, or rejected if any of them become rejected.
@static
*/
export default function all(entries) {
return new Enumerator(this, entries).promise;
}

View File

@@ -0,0 +1,84 @@
import {
isArray
} from "../utils";
/**
`Promise.race` returns a new promise which is settled in the same way as the
first passed promise to settle.
Example:
```javascript
let promise1 = new Promise(function(resolve, reject){
setTimeout(function(){
resolve('promise 1');
}, 200);
});
let promise2 = new Promise(function(resolve, reject){
setTimeout(function(){
resolve('promise 2');
}, 100);
});
Promise.race([promise1, promise2]).then(function(result){
// result === 'promise 2' because it was resolved before promise1
// was resolved.
});
```
`Promise.race` is deterministic in that only the state of the first
settled promise matters. For example, even if other promises given to the
`promises` array argument are resolved, but the first settled promise has
become rejected before the other promises became fulfilled, the returned
promise will become rejected:
```javascript
let promise1 = new Promise(function(resolve, reject){
setTimeout(function(){
resolve('promise 1');
}, 200);
});
let promise2 = new Promise(function(resolve, reject){
setTimeout(function(){
reject(new Error('promise 2'));
}, 100);
});
Promise.race([promise1, promise2]).then(function(result){
// Code here never runs
}, function(reason){
// reason.message === 'promise 2' because promise 2 became rejected before
// promise 1 became fulfilled
});
```
An example real-world use case is implementing timeouts:
```javascript
Promise.race([ajax('foo.json'), timeout(5000)])
```
@method race
@static
@param {Array} promises array of promises to observe
Useful for tooling.
@return {Promise} a promise which settles in the same way as the first passed
promise to settle.
*/
export default function race(entries) {
/*jshint validthis:true */
let Constructor = this;
if (!isArray(entries)) {
return new Constructor((_, reject) => reject(new TypeError('You must pass an array to race.')));
} else {
return new Constructor((resolve, reject) => {
let length = entries.length;
for (let i = 0; i < length; i++) {
Constructor.resolve(entries[i]).then(resolve, reject);
}
});
}
}

View File

@@ -0,0 +1,46 @@
import {
noop,
reject as _reject
} from '../-internal';
/**
`Promise.reject` returns a promise rejected with the passed `reason`.
It is shorthand for the following:
```javascript
let promise = new Promise(function(resolve, reject){
reject(new Error('WHOOPS'));
});
promise.then(function(value){
// Code here doesn't run because the promise is rejected!
}, function(reason){
// reason.message === 'WHOOPS'
});
```
Instead of writing the above, your code now simply becomes the following:
```javascript
let promise = Promise.reject(new Error('WHOOPS'));
promise.then(function(value){
// Code here doesn't run because the promise is rejected!
}, function(reason){
// reason.message === 'WHOOPS'
});
```
@method reject
@static
@param {Any} reason value that the returned promise will be rejected with.
Useful for tooling.
@return {Promise} a promise rejected with the given `reason`.
*/
export default function reject(reason) {
/*jshint validthis:true */
let Constructor = this;
let promise = new Constructor(noop);
_reject(promise, reason);
return promise;
}

View File

@@ -0,0 +1,48 @@
import {
noop,
resolve as _resolve
} from '../-internal';
/**
`Promise.resolve` returns a promise that will become resolved with the
passed `value`. It is shorthand for the following:
```javascript
let promise = new Promise(function(resolve, reject){
resolve(1);
});
promise.then(function(value){
// value === 1
});
```
Instead of writing the above, your code now simply becomes the following:
```javascript
let promise = Promise.resolve(1);
promise.then(function(value){
// value === 1
});
```
@method resolve
@static
@param {Any} value value that the returned promise will be resolved with
Useful for tooling.
@return {Promise} a promise that will become fulfilled with the given
`value`
*/
export default function resolve(object) {
/*jshint validthis:true */
let Constructor = this;
if (object && typeof object === 'object' && object.constructor === Constructor) {
return object;
}
let promise = new Constructor(noop);
_resolve(promise, object);
return promise;
}

32
node_modules/es6-promise/lib/es6-promise/then.js generated vendored Normal file
View File

@@ -0,0 +1,32 @@
import {
invokeCallback,
subscribe,
FULFILLED,
REJECTED,
noop,
makePromise,
PROMISE_ID
} from './-internal';
import { asap } from './asap';
export default function then(onFulfillment, onRejection) {
const parent = this;
const child = new this.constructor(noop);
if (child[PROMISE_ID] === undefined) {
makePromise(child);
}
const { _state } = parent;
if (_state) {
const callback = arguments[_state - 1];
asap(() => invokeCallback(_state, child, callback, parent._result));
} else {
subscribe(parent, child, onFulfillment, onRejection);
}
return child;
}

20
node_modules/es6-promise/lib/es6-promise/utils.js generated vendored Normal file
View File

@@ -0,0 +1,20 @@
export function objectOrFunction(x) {
return typeof x === 'function' || (typeof x === 'object' && x !== null);
}
export function isFunction(x) {
return typeof x === 'function';
}
export function isMaybeThenable(x) {
return typeof x === 'object' && x !== null;
}
let _isArray;
if (!Array.isArray) {
_isArray = x => Object.prototype.toString.call(x) === '[object Array]';
} else {
_isArray = Array.isArray;
}
export const isArray = _isArray;

134
node_modules/es6-promise/package.json generated vendored Normal file
View File

@@ -0,0 +1,134 @@
{
"_args": [
[
{
"raw": "es6-promise@latest",
"scope": null,
"escapedName": "es6-promise",
"name": "es6-promise",
"rawSpec": "latest",
"spec": "latest",
"type": "tag"
},
"/Users/smus/Projects/webvr-boilerplate"
]
],
"_from": "es6-promise@latest",
"_id": "es6-promise@4.0.5",
"_inCache": true,
"_installable": true,
"_location": "/es6-promise",
"_nodeVersion": "6.6.0",
"_npmOperationalInternal": {
"host": "packages-12-west.internal.npmjs.com",
"tmp": "tmp/es6-promise-4.0.5.tgz_1475539568489_0.15082282247021794"
},
"_npmUser": {
"name": "stefanpenner",
"email": "stefan.penner@gmail.com"
},
"_npmVersion": "3.10.8",
"_phantomChildren": {},
"_requested": {
"raw": "es6-promise@latest",
"scope": null,
"escapedName": "es6-promise",
"name": "es6-promise",
"rawSpec": "latest",
"spec": "latest",
"type": "tag"
},
"_requiredBy": [
"/"
],
"_resolved": "https://registry.npmjs.org/es6-promise/-/es6-promise-4.0.5.tgz",
"_shasum": "7882f30adde5b240ccfa7f7d78c548330951ae42",
"_shrinkwrap": null,
"_spec": "es6-promise@latest",
"_where": "/Users/smus/Projects/webvr-boilerplate",
"author": {
"name": "Yehuda Katz, Tom Dale, Stefan Penner and contributors",
"url": "Conversion to ES6 API by Jake Archibald"
},
"browser": {
"vertx": false
},
"bugs": {
"url": "https://github.com/stefanpenner/es6-promise/issues"
},
"dependencies": {},
"description": "A lightweight library that provides tools for organizing asynchronous code",
"devDependencies": {
"broccoli-babel-transpiler": "^5.6.1",
"broccoli-concat": "^3.0.2",
"broccoli-merge-trees": "^1.1.1",
"broccoli-rollup": "^1.0.2",
"broccoli-stew": "^1.2.0",
"broccoli-uglify-js": "^0.2.0",
"broccoli-watchify": "v1.0.0",
"ember-cli": "^2.7.0",
"ember-cli-dependency-checker": "^1.3.0",
"ember-publisher": "0.0.7",
"git-repo-version": "0.4.0",
"json3": "^3.3.2",
"mocha": "^3.1.0",
"promises-aplus-tests-phantom": "^2.1.0-revise",
"release-it": "0.0.10"
},
"directories": {
"lib": "lib"
},
"dist": {
"shasum": "7882f30adde5b240ccfa7f7d78c548330951ae42",
"tarball": "https://registry.npmjs.org/es6-promise/-/es6-promise-4.0.5.tgz"
},
"files": [
"dist",
"lib",
"es6-promise.d.ts",
"auto.js",
"!dist/test"
],
"gitHead": "6da7ebc01723ec2fd7744c5c08fa9f338992b2e1",
"homepage": "https://github.com/stefanpenner/es6-promise#readme",
"keywords": [
"promises",
"futures"
],
"license": "MIT",
"main": "dist/es6-promise.js",
"maintainers": [
{
"name": "jaffathecake",
"email": "jaffathecake@gmail.com"
},
{
"name": "stefanpenner",
"email": "stefan.penner@gmail.com"
}
],
"name": "es6-promise",
"namespace": "es6-promise",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git://github.com/stefanpenner/es6-promise.git"
},
"scripts": {
"build": "ember build --environment production",
"build:production": "ember build --env production",
"dry-run-release": "ember build --environment production && release-it --dry-run --non-interactive",
"lint": "jshint lib",
"prepublish": "ember build --environment production",
"start": "ember s",
"test": "ember test",
"test:node": "ember build && mocha ./dist/test/browserify",
"test:server": "ember test --server"
},
"spm": {
"main": "dist/es6-promise.js"
},
"typings": "es6-promise.d.ts",
"version": "4.0.5"
}

21
node_modules/eventemitter3/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2014 Arnout Kazemier
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.

106
node_modules/eventemitter3/README.md generated vendored Normal file
View File

@@ -0,0 +1,106 @@
# EventEmitter3
[![Version npm](https://img.shields.io/npm/v/eventemitter3.svg?style=flat-square)](https://www.npmjs.com/package/eventemitter3)[![Build Status](https://img.shields.io/travis/primus/eventemitter3/master.svg?style=flat-square)](https://travis-ci.org/primus/eventemitter3)[![Dependencies](https://img.shields.io/david/primus/eventemitter3.svg?style=flat-square)](https://david-dm.org/primus/eventemitter3)[![Coverage Status](https://img.shields.io/coveralls/primus/eventemitter3/master.svg?style=flat-square)](https://coveralls.io/r/primus/eventemitter3?branch=master)[![IRC channel](https://img.shields.io/badge/IRC-irc.freenode.net%23primus-00a8ff.svg?style=flat-square)](https://webchat.freenode.net/?channels=primus)
[![Sauce Test Status](https://saucelabs.com/browser-matrix/eventemitter3.svg)](https://saucelabs.com/u/eventemitter3)
EventEmitter3 is a high performance EventEmitter. It has been micro-optimized
for various of code paths making this, one of, if not the fastest EventEmitter
available for Node.js and browsers. The module is API compatible with the
EventEmitter that ships by default with Node.js but there are some slight
differences:
- Domain support has been removed.
- We do not `throw` an error when you emit an `error` event and nobody is
listening.
- The `newListener` event is removed as the use-cases for this functionality are
really just edge cases.
- No `setMaxListeners` and its pointless memory leak warnings. If you want to
add `end` listeners you should be able to do that without modules complaining.
- No `listenerCount` method. Use `EE.listeners(event).length` instead.
- Support for custom context for events so there is no need to use `fn.bind`.
- The `listeners` method can do existence checking instead of returning only
arrays.
- The `removeListener` method removes all matching listeners, not only the
first.
It's a drop in replacement for existing EventEmitters, but just faster. Free
performance, who wouldn't want that? The EventEmitter is written in EcmaScript 3
so it will work in the oldest browsers and node versions that you need to
support.
## Installation
```bash
$ npm install --save eventemitter3 # npm
$ component install primus/eventemitter3 # Component
$ bower install eventemitter3 # Bower
```
## Usage
After installation the only thing you need to do is require the module:
```js
var EventEmitter = require('eventemitter3');
```
And you're ready to create your own EventEmitter instances. For the API
documentation, please follow the official Node.js documentation:
http://nodejs.org/api/events.html
### Contextual emits
We've upgraded the API of the `EventEmitter.on`, `EventEmitter.once` and
`EventEmitter.removeListener` to accept an extra argument which is the `context`
or `this` value that should be set for the emitted events. This means you no
longer have the overhead of an event that required `fn.bind` in order to get a
custom `this` value.
```js
var EE = new EventEmitter()
, context = { foo: 'bar' };
function emitted() {
console.log(this === context); // true
}
EE.once('event-name', emitted, context);
EE.on('another-event', emitted, context);
EE.removeListener('another-event', emitted, context);
```
### Existence
To check if there is already a listener for a given event you can supply the
`listeners` method with an extra boolean argument. This will transform the
output from an array, to a boolean value which indicates if there are listeners
in place for the given event:
```js
var EE = new EventEmitter();
EE.once('event-name', function () {});
EE.on('another-event', function () {});
EE.listeners('event-name', true); // returns true
EE.listeners('unknown-name', true); // returns false
```
### Tests and benchmarks
This module is well tested. You can run:
- `npm test` to run the tests under Node.js.
- `npm run coverage` to get the code coverage.
- `npm run test-browser` to run the tests in real browsers via Sauce Labs.
We also have a set of benchmarks to compare EventEmitter3 with some available
alternatives. To run the benchmarks run `npm run benchmark`.
Tests and benchmarks are not included in the npm package. If you want to play
with them you have to clone the GitHub repository.
## License
[MIT](LICENSE)

50
node_modules/eventemitter3/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,50 @@
export as namespace EventEmitter;
type ListenerFn = (...args: Array<any>) => void;
/**
* Minimal `EventEmitter` interface that is molded against the Node.js
* `EventEmitter` interface.
*/
export class EventEmitter {
static prefixed: string | boolean;
/**
* Return an array listing the events for which the emitter has registered
* listeners.
*/
eventNames(): Array<string | symbol>;
/**
* Return the listeners registered for a given event.
*/
listeners(event: string | symbol, exists: boolean): Array<ListenerFn> | boolean;
listeners(event: string | symbol): Array<ListenerFn>;
/**
* Calls each of the listeners registered for a given event.
*/
emit(event: string | symbol, ...args: Array<any>): boolean;
/**
* Add a listener for a given event.
*/
on(event: string | symbol, fn: ListenerFn, context?: any): this;
addListener(event: string | symbol, fn: ListenerFn, context?: any): this;
/**
* Add a one-time listener for a given event.
*/
once(event: string | symbol, fn: ListenerFn, context?: any): this;
/**
* Remove the listeners of a given event.
*/
removeListener(event: string | symbol, fn?: ListenerFn, context?: any, once?: boolean): this;
off(event: string | symbol, fn?: ListenerFn, context?: any, once?: boolean): this;
/**
* Remove all listeners, or those of the specified event.
*/
removeAllListeners(event?: string | symbol): this;
}

311
node_modules/eventemitter3/index.js generated vendored Normal file
View File

@@ -0,0 +1,311 @@
'use strict';
var has = Object.prototype.hasOwnProperty
, prefix = '~';
/**
* Constructor to create a storage for our `EE` objects.
* An `Events` instance is a plain object whose properties are event names.
*
* @constructor
* @api private
*/
function Events() {}
//
// We try to not inherit from `Object.prototype`. In some engines creating an
// instance in this way is faster than calling `Object.create(null)` directly.
// If `Object.create(null)` is not supported we prefix the event names with a
// character to make sure that the built-in object properties are not
// overridden or used as an attack vector.
//
if (Object.create) {
Events.prototype = Object.create(null);
//
// This hack is needed because the `__proto__` property is still inherited in
// some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.
//
if (!new Events().__proto__) prefix = false;
}
/**
* Representation of a single event listener.
*
* @param {Function} fn The listener function.
* @param {Mixed} context The context to invoke the listener with.
* @param {Boolean} [once=false] Specify if the listener is a one-time listener.
* @constructor
* @api private
*/
function EE(fn, context, once) {
this.fn = fn;
this.context = context;
this.once = once || false;
}
/**
* Minimal `EventEmitter` interface that is molded against the Node.js
* `EventEmitter` interface.
*
* @constructor
* @api public
*/
function EventEmitter() {
this._events = new Events();
this._eventsCount = 0;
}
/**
* Return an array listing the events for which the emitter has registered
* listeners.
*
* @returns {Array}
* @api public
*/
EventEmitter.prototype.eventNames = function eventNames() {
var names = []
, events
, name;
if (this._eventsCount === 0) return names;
for (name in (events = this._events)) {
if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);
}
if (Object.getOwnPropertySymbols) {
return names.concat(Object.getOwnPropertySymbols(events));
}
return names;
};
/**
* Return the listeners registered for a given event.
*
* @param {String|Symbol} event The event name.
* @param {Boolean} exists Only check if there are listeners.
* @returns {Array|Boolean}
* @api public
*/
EventEmitter.prototype.listeners = function listeners(event, exists) {
var evt = prefix ? prefix + event : event
, available = this._events[evt];
if (exists) return !!available;
if (!available) return [];
if (available.fn) return [available.fn];
for (var i = 0, l = available.length, ee = new Array(l); i < l; i++) {
ee[i] = available[i].fn;
}
return ee;
};
/**
* Calls each of the listeners registered for a given event.
*
* @param {String|Symbol} event The event name.
* @returns {Boolean} `true` if the event had listeners, else `false`.
* @api public
*/
EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
var evt = prefix ? prefix + event : event;
if (!this._events[evt]) return false;
var listeners = this._events[evt]
, len = arguments.length
, args
, i;
if (listeners.fn) {
if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);
switch (len) {
case 1: return listeners.fn.call(listeners.context), true;
case 2: return listeners.fn.call(listeners.context, a1), true;
case 3: return listeners.fn.call(listeners.context, a1, a2), true;
case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;
case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
}
for (i = 1, args = new Array(len -1); i < len; i++) {
args[i - 1] = arguments[i];
}
listeners.fn.apply(listeners.context, args);
} else {
var length = listeners.length
, j;
for (i = 0; i < length; i++) {
if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);
switch (len) {
case 1: listeners[i].fn.call(listeners[i].context); break;
case 2: listeners[i].fn.call(listeners[i].context, a1); break;
case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;
case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;
default:
if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {
args[j - 1] = arguments[j];
}
listeners[i].fn.apply(listeners[i].context, args);
}
}
}
return true;
};
/**
* Add a listener for a given event.
*
* @param {String|Symbol} event The event name.
* @param {Function} fn The listener function.
* @param {Mixed} [context=this] The context to invoke the listener with.
* @returns {EventEmitter} `this`.
* @api public
*/
EventEmitter.prototype.on = function on(event, fn, context) {
var listener = new EE(fn, context || this)
, evt = prefix ? prefix + event : event;
if (!this._events[evt]) this._events[evt] = listener, this._eventsCount++;
else if (!this._events[evt].fn) this._events[evt].push(listener);
else this._events[evt] = [this._events[evt], listener];
return this;
};
/**
* Add a one-time listener for a given event.
*
* @param {String|Symbol} event The event name.
* @param {Function} fn The listener function.
* @param {Mixed} [context=this] The context to invoke the listener with.
* @returns {EventEmitter} `this`.
* @api public
*/
EventEmitter.prototype.once = function once(event, fn, context) {
var listener = new EE(fn, context || this, true)
, evt = prefix ? prefix + event : event;
if (!this._events[evt]) this._events[evt] = listener, this._eventsCount++;
else if (!this._events[evt].fn) this._events[evt].push(listener);
else this._events[evt] = [this._events[evt], listener];
return this;
};
/**
* Remove the listeners of a given event.
*
* @param {String|Symbol} event The event name.
* @param {Function} fn Only remove the listeners that match this function.
* @param {Mixed} context Only remove the listeners that have this context.
* @param {Boolean} once Only remove one-time listeners.
* @returns {EventEmitter} `this`.
* @api public
*/
EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
var evt = prefix ? prefix + event : event;
if (!this._events[evt]) return this;
if (!fn) {
if (--this._eventsCount === 0) this._events = new Events();
else delete this._events[evt];
return this;
}
var listeners = this._events[evt];
if (listeners.fn) {
if (
listeners.fn === fn
&& (!once || listeners.once)
&& (!context || listeners.context === context)
) {
if (--this._eventsCount === 0) this._events = new Events();
else delete this._events[evt];
}
} else {
for (var i = 0, events = [], length = listeners.length; i < length; i++) {
if (
listeners[i].fn !== fn
|| (once && !listeners[i].once)
|| (context && listeners[i].context !== context)
) {
events.push(listeners[i]);
}
}
//
// Reset the array, or remove it completely if we have no more listeners.
//
if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;
else if (--this._eventsCount === 0) this._events = new Events();
else delete this._events[evt];
}
return this;
};
/**
* Remove all listeners, or those of the specified event.
*
* @param {String|Symbol} [event] The event name.
* @returns {EventEmitter} `this`.
* @api public
*/
EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
var evt;
if (event) {
evt = prefix ? prefix + event : event;
if (this._events[evt]) {
if (--this._eventsCount === 0) this._events = new Events();
else delete this._events[evt];
}
} else {
this._events = new Events();
this._eventsCount = 0;
}
return this;
};
//
// Alias methods names because people roll like that.
//
EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
EventEmitter.prototype.addListener = EventEmitter.prototype.on;
//
// This function doesn't apply anymore.
//
EventEmitter.prototype.setMaxListeners = function setMaxListeners() {
return this;
};
//
// Expose the prefix.
//
EventEmitter.prefixed = prefix;
//
// Allow `EventEmitter` to be imported as module namespace.
//
EventEmitter.EventEmitter = EventEmitter;
//
// Expose the module.
//
if ('undefined' !== typeof module) {
module.exports = EventEmitter;
}

123
node_modules/eventemitter3/package.json generated vendored Normal file
View File

@@ -0,0 +1,123 @@
{
"_args": [
[
{
"raw": "eventemitter3@^2.0.2",
"scope": null,
"escapedName": "eventemitter3",
"name": "eventemitter3",
"rawSpec": "^2.0.2",
"spec": ">=2.0.2 <3.0.0",
"type": "range"
},
"/Users/smus/Projects/webvr-boilerplate/node_modules/webvr-polyfill"
]
],
"_from": "eventemitter3@>=2.0.2 <3.0.0",
"_id": "eventemitter3@2.0.2",
"_inCache": true,
"_installable": true,
"_location": "/eventemitter3",
"_nodeVersion": "6.7.0",
"_npmOperationalInternal": {
"host": "packages-16-east.internal.npmjs.com",
"tmp": "tmp/eventemitter3-2.0.2.tgz_1475216591620_0.3523867195472121"
},
"_npmUser": {
"name": "lpinca",
"email": "luigipinca@gmail.com"
},
"_npmVersion": "3.10.7",
"_phantomChildren": {},
"_requested": {
"raw": "eventemitter3@^2.0.2",
"scope": null,
"escapedName": "eventemitter3",
"name": "eventemitter3",
"rawSpec": "^2.0.2",
"spec": ">=2.0.2 <3.0.0",
"type": "range"
},
"_requiredBy": [
"/webvr-polyfill",
"/webvr-ui"
],
"_resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-2.0.2.tgz",
"_shasum": "20ce4891909ce9f35b088c94fab40e2c96f473ac",
"_shrinkwrap": null,
"_spec": "eventemitter3@^2.0.2",
"_where": "/Users/smus/Projects/webvr-boilerplate/node_modules/webvr-polyfill",
"author": {
"name": "Arnout Kazemier"
},
"bugs": {
"url": "https://github.com/primus/eventemitter3/issues"
},
"dependencies": {},
"description": "EventEmitter3 focuses on performance while maintaining a Node.js AND browser compatible interface.",
"devDependencies": {
"assume": "1.4.x",
"istanbul": "0.4.x",
"mocha": "3.1.x",
"pre-commit": "1.1.x",
"zuul": "3.11.x"
},
"directories": {},
"dist": {
"shasum": "20ce4891909ce9f35b088c94fab40e2c96f473ac",
"tarball": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-2.0.2.tgz"
},
"gitHead": "a9eedef2a58deae7006028662a83d88579486886",
"homepage": "https://github.com/primus/eventemitter3#readme",
"keywords": [
"EventEmitter",
"EventEmitter2",
"EventEmitter3",
"Events",
"addEventListener",
"addListener",
"emit",
"emits",
"emitter",
"event",
"once",
"pub/sub",
"publish",
"reactor",
"subscribe"
],
"license": "MIT",
"main": "index.js",
"maintainers": [
{
"name": "v1",
"email": "npm@3rd-Eden.com"
},
{
"name": "3rdeden",
"email": "npm@3rd-Eden.com"
},
{
"name": "lpinca",
"email": "luigipinca@gmail.com"
}
],
"name": "eventemitter3",
"optionalDependencies": {},
"pre-commit": "sync, test",
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git://github.com/primus/eventemitter3.git"
},
"scripts": {
"benchmark": "find benchmarks/run -name '*.js' -exec benchmarks/start.sh {} \\;",
"coverage": "istanbul cover _mocha -- test.js",
"sync": "node versions.js",
"test": "mocha test.js",
"test-browser": "zuul -- test.js",
"test-node": "istanbul cover _mocha --report lcovonly -- test.js"
},
"typings": "index.d.ts",
"version": "2.0.2"
}

90
node_modules/object-assign/index.js generated vendored Normal file
View File

@@ -0,0 +1,90 @@
/*
object-assign
(c) Sindre Sorhus
@license MIT
*/
'use strict';
/* eslint-disable no-unused-vars */
var getOwnPropertySymbols = Object.getOwnPropertySymbols;
var hasOwnProperty = Object.prototype.hasOwnProperty;
var propIsEnumerable = Object.prototype.propertyIsEnumerable;
function toObject(val) {
if (val === null || val === undefined) {
throw new TypeError('Object.assign cannot be called with null or undefined');
}
return Object(val);
}
function shouldUseNative() {
try {
if (!Object.assign) {
return false;
}
// Detect buggy property enumeration order in older V8 versions.
// https://bugs.chromium.org/p/v8/issues/detail?id=4118
var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
test1[5] = 'de';
if (Object.getOwnPropertyNames(test1)[0] === '5') {
return false;
}
// https://bugs.chromium.org/p/v8/issues/detail?id=3056
var test2 = {};
for (var i = 0; i < 10; i++) {
test2['_' + String.fromCharCode(i)] = i;
}
var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
return test2[n];
});
if (order2.join('') !== '0123456789') {
return false;
}
// https://bugs.chromium.org/p/v8/issues/detail?id=3056
var test3 = {};
'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
test3[letter] = letter;
});
if (Object.keys(Object.assign({}, test3)).join('') !==
'abcdefghijklmnopqrst') {
return false;
}
return true;
} catch (err) {
// We don't expect any of the above to throw, but better to be safe.
return false;
}
}
module.exports = shouldUseNative() ? Object.assign : function (target, source) {
var from;
var to = toObject(target);
var symbols;
for (var s = 1; s < arguments.length; s++) {
from = Object(arguments[s]);
for (var key in from) {
if (hasOwnProperty.call(from, key)) {
to[key] = from[key];
}
}
if (getOwnPropertySymbols) {
symbols = getOwnPropertySymbols(from);
for (var i = 0; i < symbols.length; i++) {
if (propIsEnumerable.call(from, symbols[i])) {
to[symbols[i]] = from[symbols[i]];
}
}
}
}
return to;
};

21
node_modules/object-assign/license generated vendored Normal file
View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
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.

119
node_modules/object-assign/package.json generated vendored Normal file
View File

@@ -0,0 +1,119 @@
{
"_args": [
[
{
"raw": "object-assign@^4.0.1",
"scope": null,
"escapedName": "object-assign",
"name": "object-assign",
"rawSpec": "^4.0.1",
"spec": ">=4.0.1 <5.0.0",
"type": "range"
},
"/Users/smus/Projects/webvr-boilerplate/node_modules/webvr-polyfill"
]
],
"_from": "object-assign@>=4.0.1 <5.0.0",
"_id": "object-assign@4.1.1",
"_inCache": true,
"_installable": true,
"_location": "/object-assign",
"_nodeVersion": "4.6.2",
"_npmOperationalInternal": {
"host": "packages-12-west.internal.npmjs.com",
"tmp": "tmp/object-assign-4.1.1.tgz_1484580915042_0.07107710791751742"
},
"_npmUser": {
"name": "sindresorhus",
"email": "sindresorhus@gmail.com"
},
"_npmVersion": "2.15.11",
"_phantomChildren": {},
"_requested": {
"raw": "object-assign@^4.0.1",
"scope": null,
"escapedName": "object-assign",
"name": "object-assign",
"rawSpec": "^4.0.1",
"spec": ">=4.0.1 <5.0.0",
"type": "range"
},
"_requiredBy": [
"/webvr-polyfill"
],
"_resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
"_shasum": "2109adc7965887cfc05cbbd442cac8bfbb360863",
"_shrinkwrap": null,
"_spec": "object-assign@^4.0.1",
"_where": "/Users/smus/Projects/webvr-boilerplate/node_modules/webvr-polyfill",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"bugs": {
"url": "https://github.com/sindresorhus/object-assign/issues"
},
"dependencies": {},
"description": "ES2015 `Object.assign()` ponyfill",
"devDependencies": {
"ava": "^0.16.0",
"lodash": "^4.16.4",
"matcha": "^0.7.0",
"xo": "^0.16.0"
},
"directories": {},
"dist": {
"shasum": "2109adc7965887cfc05cbbd442cac8bfbb360863",
"tarball": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz"
},
"engines": {
"node": ">=0.10.0"
},
"files": [
"index.js"
],
"gitHead": "a89774b252c91612203876984bbd6addbe3b5a0e",
"homepage": "https://github.com/sindresorhus/object-assign#readme",
"keywords": [
"object",
"assign",
"extend",
"properties",
"es2015",
"ecmascript",
"harmony",
"ponyfill",
"prollyfill",
"polyfill",
"shim",
"browser"
],
"license": "MIT",
"maintainers": [
{
"name": "gaearon",
"email": "dan.abramov@gmail.com"
},
{
"name": "sindresorhus",
"email": "sindresorhus@gmail.com"
},
{
"name": "spicyj",
"email": "ben@benalpert.com"
}
],
"name": "object-assign",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git+https://github.com/sindresorhus/object-assign.git"
},
"scripts": {
"bench": "matcha bench.js",
"test": "xo && ava"
},
"version": "4.1.1"
}

61
node_modules/object-assign/readme.md generated vendored Normal file
View File

@@ -0,0 +1,61 @@
# object-assign [![Build Status](https://travis-ci.org/sindresorhus/object-assign.svg?branch=master)](https://travis-ci.org/sindresorhus/object-assign)
> ES2015 [`Object.assign()`](http://www.2ality.com/2014/01/object-assign.html) [ponyfill](https://ponyfill.com)
## Use the built-in
Node.js 4 and up, as well as every evergreen browser (Chrome, Edge, Firefox, Opera, Safari),
support `Object.assign()` :tada:. If you target only those environments, then by all
means, use `Object.assign()` instead of this package.
## Install
```
$ npm install --save object-assign
```
## Usage
```js
const objectAssign = require('object-assign');
objectAssign({foo: 0}, {bar: 1});
//=> {foo: 0, bar: 1}
// multiple sources
objectAssign({foo: 0}, {bar: 1}, {baz: 2});
//=> {foo: 0, bar: 1, baz: 2}
// overwrites equal keys
objectAssign({foo: 0}, {foo: 1}, {foo: 2});
//=> {foo: 2}
// ignores null and undefined sources
objectAssign({foo: 0}, null, {bar: 1}, undefined);
//=> {foo: 0, bar: 1}
```
## API
### objectAssign(target, [source, ...])
Assigns enumerable own properties of `source` objects to the `target` object and returns the `target` object. Additional `source` objects will overwrite previous ones.
## Resources
- [ES2015 spec - Object.assign](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.assign)
## Related
- [deep-assign](https://github.com/sindresorhus/deep-assign) - Recursive `Object.assign()`
## License
MIT © [Sindre Sorhus](https://sindresorhus.com)

145
node_modules/screenfull/dist/screenfull.js generated vendored Normal file
View File

@@ -0,0 +1,145 @@
/*!
* screenfull
* v3.0.0 - 2015-11-24
* (c) Sindre Sorhus; MIT License
*/
(function () {
'use strict';
var isCommonjs = typeof module !== 'undefined' && module.exports;
var keyboardAllowed = typeof Element !== 'undefined' && 'ALLOW_KEYBOARD_INPUT' in Element;
var fn = (function () {
var val;
var valLength;
var fnMap = [
[
'requestFullscreen',
'exitFullscreen',
'fullscreenElement',
'fullscreenEnabled',
'fullscreenchange',
'fullscreenerror'
],
// new WebKit
[
'webkitRequestFullscreen',
'webkitExitFullscreen',
'webkitFullscreenElement',
'webkitFullscreenEnabled',
'webkitfullscreenchange',
'webkitfullscreenerror'
],
// old WebKit (Safari 5.1)
[
'webkitRequestFullScreen',
'webkitCancelFullScreen',
'webkitCurrentFullScreenElement',
'webkitCancelFullScreen',
'webkitfullscreenchange',
'webkitfullscreenerror'
],
[
'mozRequestFullScreen',
'mozCancelFullScreen',
'mozFullScreenElement',
'mozFullScreenEnabled',
'mozfullscreenchange',
'mozfullscreenerror'
],
[
'msRequestFullscreen',
'msExitFullscreen',
'msFullscreenElement',
'msFullscreenEnabled',
'MSFullscreenChange',
'MSFullscreenError'
]
];
var i = 0;
var l = fnMap.length;
var ret = {};
for (; i < l; i++) {
val = fnMap[i];
if (val && val[1] in document) {
for (i = 0, valLength = val.length; i < valLength; i++) {
ret[fnMap[0][i]] = val[i];
}
return ret;
}
}
return false;
})();
var screenfull = {
request: function (elem) {
var request = fn.requestFullscreen;
elem = elem || document.documentElement;
// Work around Safari 5.1 bug: reports support for
// keyboard in fullscreen even though it doesn't.
// Browser sniffing, since the alternative with
// setTimeout is even worse.
if (/5\.1[\.\d]* Safari/.test(navigator.userAgent)) {
elem[request]();
} else {
elem[request](keyboardAllowed && Element.ALLOW_KEYBOARD_INPUT);
}
},
exit: function () {
document[fn.exitFullscreen]();
},
toggle: function (elem) {
if (this.isFullscreen) {
this.exit();
} else {
this.request(elem);
}
},
raw: fn
};
if (!fn) {
if (isCommonjs) {
module.exports = false;
} else {
window.screenfull = false;
}
return;
}
Object.defineProperties(screenfull, {
isFullscreen: {
get: function () {
return Boolean(document[fn.fullscreenElement]);
}
},
element: {
enumerable: true,
get: function () {
return document[fn.fullscreenElement];
}
},
enabled: {
enumerable: true,
get: function () {
// Coerce to boolean in case of old WebKit
return Boolean(document[fn.fullscreenEnabled]);
}
}
});
if (isCommonjs) {
module.exports = screenfull;
} else {
window.screenfull = screenfull;
}
})();

21
node_modules/screenfull/license generated vendored Normal file
View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
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.

108
node_modules/screenfull/package.json generated vendored Normal file
View File

@@ -0,0 +1,108 @@
{
"_args": [
[
{
"raw": "screenfull@^3.0.2",
"scope": null,
"escapedName": "screenfull",
"name": "screenfull",
"rawSpec": "^3.0.2",
"spec": ">=3.0.2 <4.0.0",
"type": "range"
},
"/Users/smus/Projects/webvr-boilerplate/node_modules/webvr-ui"
]
],
"_from": "screenfull@>=3.0.2 <4.0.0",
"_id": "screenfull@3.0.2",
"_inCache": true,
"_installable": true,
"_location": "/screenfull",
"_nodeVersion": "4.4.5",
"_npmOperationalInternal": {
"host": "packages-12-west.internal.npmjs.com",
"tmp": "tmp/screenfull-3.0.2.tgz_1471045464332_0.06257056491449475"
},
"_npmUser": {
"name": "sindresorhus",
"email": "sindresorhus@gmail.com"
},
"_npmVersion": "2.15.5",
"_phantomChildren": {},
"_requested": {
"raw": "screenfull@^3.0.2",
"scope": null,
"escapedName": "screenfull",
"name": "screenfull",
"rawSpec": "^3.0.2",
"spec": ">=3.0.2 <4.0.0",
"type": "range"
},
"_requiredBy": [
"/webvr-ui"
],
"_resolved": "https://registry.npmjs.org/screenfull/-/screenfull-3.0.2.tgz",
"_shasum": "9fbcce07bad4c680a8f90f2bfc9c41788af55d0c",
"_shrinkwrap": null,
"_spec": "screenfull@^3.0.2",
"_where": "/Users/smus/Projects/webvr-boilerplate/node_modules/webvr-ui",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"bugs": {
"url": "https://github.com/sindresorhus/screenfull.js/issues"
},
"dependencies": {},
"description": "Simple wrapper for cross-browser usage of the JavaScript Fullscreen API, which lets you bring the page or any element into fullscreen.",
"devDependencies": {
"grunt": "^1.0.1",
"grunt-contrib-concat": "^1.0.0",
"grunt-contrib-uglify": "^2.0.0",
"load-grunt-tasks": "^3.3.0",
"xo": "*"
},
"directories": {},
"dist": {
"shasum": "9fbcce07bad4c680a8f90f2bfc9c41788af55d0c",
"tarball": "https://registry.npmjs.org/screenfull/-/screenfull-3.0.2.tgz"
},
"engines": {
"node": ">=0.10.0"
},
"files": [
"dist/screenfull.js"
],
"gitHead": "dcdfb8c24688e041ba861529711089cf0e542169",
"homepage": "https://github.com/sindresorhus/screenfull.js#readme",
"keywords": [
"browser",
"fullscreen"
],
"license": "MIT",
"main": "dist/screenfull.js",
"maintainers": [
{
"name": "sindresorhus",
"email": "sindresorhus@gmail.com"
}
],
"name": "screenfull",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git+https://github.com/sindresorhus/screenfull.js.git"
},
"scripts": {
"test": "xo"
},
"version": "3.0.2",
"xo": {
"envs": [
"node",
"browser"
]
}
}

244
node_modules/screenfull/readme.md generated vendored Normal file
View File

@@ -0,0 +1,244 @@
# screenfull.js
> Simple wrapper for cross-browser usage of the JavaScript [Fullscreen API](https://developer.mozilla.org/en/DOM/Using_full-screen_mode), which lets you bring the page or any element into fullscreen. Smoothens out the browser implementation differences, so you don't have to.
---
<p align="center"><b>🔥 Want to strengthen your core JavaScript skills and master ES6?</b><br>I would personally recommend this awesome <a href="https://ES6.io/friend/AWESOME">ES6 course</a> by Wes Bos.</p>
---
### [Demo](https://sindresorhus.com/screenfull.js)
### [Check out my other projects](https://github.com/sindresorhus?tab=repositories)
## Install
Only 0.7 kB gzipped.
Download the [production version][min] or the [development version][max].
[min]: https://github.com/sindresorhus/screenfull.js/raw/gh-pages/dist/screenfull.min.js
[max]: https://github.com/sindresorhus/screenfull.js/raw/gh-pages/dist/screenfull.js
```
$ npm install --save screenfull
```
Also available on [cdnjs](https://cdnjs.com/libraries/screenfull.js).
## Why?
### Screenfull
```js
if (screenfull.enabled) {
screenfull.request();
}
```
### Vanilla JavaScript
```js
document.fullscreenEnabled = document.fullscreenEnabled || document.mozFullScreenEnabled || document.documentElement.webkitRequestFullScreen;
function requestFullscreen(element) {
if (element.requestFullscreen) {
element.requestFullscreen();
} else if (element.mozRequestFullScreen) {
element.mozRequestFullScreen();
} else if (element.webkitRequestFullScreen) {
element.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
}
}
if (document.fullscreenEnabled) {
requestFullscreen(document.documentElement);
}
// Actually it's more if you want it to work in Safari, but let's not go there...
```
## Support
[Supported browsers](http://caniuse.com/fullscreen)
Safari doesn't support use of the keyboard in fullscreen.
## Documentation
### Examples
#### Fullscreen the page
```js
document.getElementById('button').addEventListener('click', () => {
if (screenfull.enabled) {
screenfull.request();
} else {
// Ignore or do something else
}
});
```
#### Fullscreen an element
```js
const elem = document.getElementById('target');
document.getElementById('button').addEventListener('click', () => {
if (screenfull.enabled) {
screenfull.request(elem);
}
});
```
#### Fullscreen an element with jQuery
```js
const target = $('#target')[0]; // Get DOM element from jQuery collection
$('#button').on('click', () => {
if (screenfull.enabled) {
screenfull.request(target);
}
});
```
#### Toggle fullscreen on a image with jQuery
```js
$('img').on('click', event => {
if (screenfull.enabled) {
screenfull.toggle(event.target);
}
});
```
#### Detect fullscreen change
```js
if (screenfull.enabled) {
document.addEventListener(screenfull.raw.fullscreenchange, () => {
console.log('Am I fullscreen? ' + (screenfull.isFullscreen ? 'Yes' : 'No'));
});
}
```
#### Detect fullscreen error
```js
if (screenfull.enabled) {
document.addEventListener(screenfull.raw.fullscreenerror, event => {
console.error('Failed to enable fullscreen', event);
});
}
```
See the [demo](https://sindresorhus.com/screenfull.js) for more examples, and view the source.
#### Fullscreen an element with Angular.js
You can use the [Angular.js binding](https://github.com/hrajchert/angular-screenfull) to do something like:
```html
<div ngsf-fullscreen>
<p>This is a fullscreen element</p>
<button ngsf-toggle-fullscreen>Toggle fullscreen</button>
</div>
```
### Methods
#### .request()
Make an element fullscreen.
Accepts a DOM element. Default is `<html>`. If called with another element than the currently active, it will switch to that if it's a decendant.
If your page is inside an `<iframe>` you will need to add a `allowfullscreen` attribute (+ `webkitallowfullscreen` and `mozallowfullscreen`).
Keep in mind that the browser will only enter fullscreen when initiated by user events like click, touch, key.
#### .exit()
Brings you out of fullscreen.
#### .toggle()
Requests fullscreen if not active, otherwise exits.
### Properties
#### .isFullscreen
Returns a boolean whether fullscreen is active.
#### .element
Returns the element currently in fullscreen, otherwise `null`.
#### .enabled
Returns a boolean whether you are allowed to enter fullscreen. If your page is inside an `<iframe>` you will need to add a `allowfullscreen` attribute (+ `webkitallowfullscreen` and `mozallowfullscreen`).
#### .raw
Exposes the raw properties (prefixed if needed) used internally: `requestFullscreen`, `exitFullscreen`, `fullscreenElement`, `fullscreenEnabled`, `fullscreenchange`, `fullscreenerror`
```js
$(document).on(screenfull.raw.fullscreenchange, () => {
console.log('Fullscreen change');
});
```
## FAQ
### How can I navigate to a new page when fullscreen?
That's not supported by browsers for security reasons. There is, however, a dirty workaround. Create a seamless iframe that fills the screen and navigate to the page in that instead.
```js
$('#new-page-btn').click(() => {
const iframe = document.createElement('iframe')
iframe.setAttribute('id', 'external-iframe');
iframe.setAttribute('src', 'http://new-page-website.com');
iframe.setAttribute('frameborder', 'no');
iframe.style.position = 'absolute';
iframe.style.top = '0';
iframe.style.right = '0';
iframe.style.bottom = '0';
iframe.style.left = '0';
iframe.style.width = '100%';
iframe.style.height = '100%';
$(document.body).prepend(iframe);
document.body.style.overflow = 'hidden';
});
```
## Resources
- [Using the Fullscreen API in web browsers](http://hacks.mozilla.org/2012/01/using-the-fullscreen-api-in-web-browsers/)
- [MDN - Fullscreen API](https://developer.mozilla.org/en/DOM/Using_full-screen_mode)
- [W3C Fullscreen spec](http://dvcs.w3.org/hg/fullscreen/raw-file/tip/Overview.html)
- [Building an amazing fullscreen mobile experience](http://www.html5rocks.com/en/mobile/fullscreen/)
## License
MIT © [Sindre Sorhus](https://sindresorhus.com)

1
node_modules/test.html generated vendored Normal file
View File

@@ -0,0 +1 @@
testing

21
node_modules/three/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,21 @@
The MIT License
Copyright © 2010-2017 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.

84
node_modules/three/README.md generated vendored Normal file
View File

@@ -0,0 +1,84 @@
three.js
========
[![Latest NPM release][npm-badge]][npm-badge-url]
[![License][license-badge]][license-badge-url]
[![Dependencies][dependencies-badge]][dependencies-badge-url]
[![Dev Dependencies][devDependencies-badge]][devDependencies-badge-url]
#### JavaScript 3D library ####
The aim of the project is to create an easy to use, lightweight, 3D library. The library provides &lt;canvas&gt;, &lt;svg&gt;, CSS3D and WebGL renderers.
[Examples](http://threejs.org/examples/) &mdash;
[Documentation](http://threejs.org/docs/) &mdash;
[Wiki](https://github.com/mrdoob/three.js/wiki) &mdash;
[Migrating](https://github.com/mrdoob/three.js/wiki/Migration-Guide) &mdash;
[Help](http://stackoverflow.com/questions/tagged/three.js)
### Usage ###
Download the [minified library](http://threejs.org/build/three.min.js) and include it in your html.
Alternatively see [how to build the library yourself](https://github.com/mrdoob/three.js/wiki/Build-instructions).
```html
<script src="js/three.min.js"></script>
```
This code creates a scene, a camera, and a geometric cube, and it adds the cube to the scene. It then creates a `WebGL` renderer for the scene and camera, and it adds that viewport to the document.body element. Finally it animates the cube within the scene for the camera.
```javascript
var scene, camera, renderer;
var geometry, material, mesh;
init();
animate();
function init() {
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 10000 );
camera.position.z = 1000;
geometry = new THREE.BoxGeometry( 200, 200, 200 );
material = new THREE.MeshBasicMaterial( { color: 0xff0000, wireframe: true } );
mesh = new THREE.Mesh( geometry, material );
scene.add( mesh );
renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
}
function animate() {
requestAnimationFrame( animate );
mesh.rotation.x += 0.01;
mesh.rotation.y += 0.02;
renderer.render( scene, camera );
}
```
If everything went well you should see [this](http://jsfiddle.net/hfj7gm6t/).
### Change log ###
[releases](https://github.com/mrdoob/three.js/releases)
[npm-badge]: https://img.shields.io/npm/v/three.svg
[npm-badge-url]: https://www.npmjs.com/package/three
[license-badge]: https://img.shields.io/npm/l/three.svg
[license-badge-url]: ./LICENSE
[dependencies-badge]: https://img.shields.io/david/mrdoob/three.js.svg
[dependencies-badge-url]: https://david-dm.org/mrdoob/three.js
[devDependencies-badge]: https://img.shields.io/david/dev/mrdoob/three.js.svg
[devDependencies-badge-url]: https://david-dm.org/mrdoob/three.js#info=devDependencies

43300
node_modules/three/build/three.js generated vendored Normal file

File diff suppressed because one or more lines are too long

859
node_modules/three/build/three.min.js generated vendored Normal file

File diff suppressed because one or more lines are too long

42915
node_modules/three/build/three.module.js generated vendored Normal file

File diff suppressed because one or more lines are too long

13
node_modules/three/examples/fonts/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,13 @@
Copyright <20> 2004 by MAGENTA Ltd. All Rights Reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy of the fonts accompanying this license ("Fonts") and associated documentation files (the "Font Software"), to reproduce and distribute the Font Software, including without limitation the rights to use, copy, merge, publish, distribute, and/or sell copies of the Font Software, and to permit persons to whom the Font Software is furnished to do so, subject to the following conditions:
The above copyright and this permission notice shall be included in all copies of one or more of the Font Software typefaces.
The Font Software may be modified, altered, or added to, and in particular the designs of glyphs or characters in the Fonts may be modified and additional glyphs or characters may be added to the Fonts, only if the fonts are renamed to names not containing the word "MgOpen", or if the modifications are accepted for inclusion in the Font Software itself by the each appointed Administrator.
This License becomes null and void to the extent applicable to Fonts or Font Software that has been modified and is distributed under the "MgOpen" name.
The Font Software may be sold as part of a larger software package but no copy of one or more of the Font Software typefaces may be sold by itself.
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL MAGENTA OR PERSONS OR BODIES IN CHARGE OF ADMINISTRATION AND MAINTENANCE OF THE FONT SOFTWARE BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE.

2
node_modules/three/examples/fonts/README generated vendored Normal file
View File

@@ -0,0 +1,2 @@
Use Facetype.js to generate typeface.json fonts.
http://gero3.github.io/facetype.js/

190
node_modules/three/examples/fonts/droid/NOTICE generated vendored Normal file
View File

@@ -0,0 +1,190 @@
Copyright (c) 2005-2008, The Android Open Source Project
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS

18
node_modules/three/examples/fonts/droid/README.txt generated vendored Normal file
View File

@@ -0,0 +1,18 @@
Copyright (C) 2008 The Android Open Source Project
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
##########
This directory contains the fonts for the platform. They are licensed
under the Apache 2 license.

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

BIN
node_modules/three/examples/fonts/ttf/kenpixel.ttf generated vendored Normal file

Binary file not shown.

115
node_modules/three/examples/js/AnimationClipCreator.js generated vendored Normal file
View File

@@ -0,0 +1,115 @@
/**
*
* Creator of typical test AnimationClips / KeyframeTracks
*
* @author Ben Houston / http://clara.io/
* @author David Sarno / http://lighthaus.us/
*/
THREE.AnimationClipCreator = function() {
};
THREE.AnimationClipCreator.CreateRotationAnimation = function( period, axis ) {
var times = [ 0, period ], values = [ 0, 360 ];
axis = axis || 'x';
var trackName = '.rotation[' + axis + ']';
var track = new THREE.NumberKeyframeTrack( trackName, times, values );
return new THREE.AnimationClip( null, period, [ track ] );
};
THREE.AnimationClipCreator.CreateScaleAxisAnimation = function( period, axis ) {
var times = [ 0, period ], values = [ 0, 1 ];
axis = axis || 'x';
var trackName = '.scale[' + axis + ']';
var track = new THREE.NumberKeyframeTrack( trackName, times, values );
return new THREE.AnimationClip( null, period, [ track ] );
};
THREE.AnimationClipCreator.CreateShakeAnimation = function( duration, shakeScale ) {
var times = [], values = [], tmp = new THREE.Vector3();
for( var i = 0; i < duration * 10; i ++ ) {
times.push( i / 10 );
tmp.set( Math.random() * 2.0 - 1.0, Math.random() * 2.0 - 1.0, Math.random() * 2.0 - 1.0 ).
multiply( shakeScale ).
toArray( values, values.length );
}
var trackName = '.position';
var track = new THREE.VectorKeyframeTrack( trackName, times, values );
return new THREE.AnimationClip( null, duration, [ track ] );
};
THREE.AnimationClipCreator.CreatePulsationAnimation = function( duration, pulseScale ) {
var times = [], values = [], tmp = new THREE.Vector3();
for( var i = 0; i < duration * 10; i ++ ) {
times.push( i / 10 );
var scaleFactor = Math.random() * pulseScale;
tmp.set( scaleFactor, scaleFactor, scaleFactor ).
toArray( values, values.length );
}
var trackName = '.scale';
var track = new THREE.VectorKeyframeTrack( trackName, keys );
return new THREE.AnimationClip( null, duration, [ track ] );
};
THREE.AnimationClipCreator.CreateVisibilityAnimation = function( duration ) {
var times = [ 0, duration / 2, duration ], values = [ true, false, true ];
var trackName = '.visible';
var track = new THREE.BooleanKeyframeTrack( trackName, times, values );
return new THREE.AnimationClip( null, duration, [ track ] );
};
THREE.AnimationClipCreator.CreateMaterialColorAnimation = function( duration, colors, loop ) {
var times = [], values = [],
timeStep = duration / colors.length;
for( var i = 0; i <= colors.length; i ++ ) {
timees.push( i * timeStep );
values.push( colors[ i % colors.length ] );
}
var trackName = '.material[0].color';
var track = new THREE.ColorKeyframeTrack( trackName, times, values );
return new THREE.AnimationClip( null, duration, [ track ] );
};

182
node_modules/three/examples/js/BlendCharacter.js generated vendored Normal file
View File

@@ -0,0 +1,182 @@
/**
* @author Michael Guerrero / http://realitymeltdown.com
*/
THREE.BlendCharacter = function () {
this.weightSchedule = [];
this.warpSchedule = [];
this.load = function ( url, onLoad ) {
var scope = this;
var loader = new THREE.ObjectLoader();
loader.load( url, function( loadedObject ) {
// The exporter does not currently allow exporting a skinned mesh by itself
// so we must fish it out of the hierarchy it is embedded in (scene)
loadedObject.traverse( function( object ) {
if ( object instanceof THREE.SkinnedMesh ) {
scope.skinnedMesh = object;
}
} );
THREE.SkinnedMesh.call( scope, scope.skinnedMesh.geometry, scope.skinnedMesh.material );
// If we didn't successfully find the mesh, bail out
if ( scope.skinnedMesh == undefined ) {
console.log( 'unable to find skinned mesh in ' + url );
return;
}
scope.material.skinning = true;
scope.mixer = new THREE.AnimationMixer( scope );
// Create the animations
for ( var i = 0; i < scope.geometry.animations.length; ++ i ) {
scope.mixer.clipAction( scope.geometry.animations[ i ] );
}
// Loading is complete, fire the callback
if ( onLoad !== undefined ) onLoad();
} );
};
this.loadJSON = function ( url, onLoad ) {
var scope = this;
var loader = new THREE.JSONLoader();
loader.load( url, function( geometry, materials ) {
var originalMaterial = materials[ 0 ];
originalMaterial.skinning = true;
THREE.SkinnedMesh.call( scope, geometry, originalMaterial );
var mixer = new THREE.AnimationMixer( scope );
scope.mixer = mixer;
// Create the animations
for ( var i = 0; i < geometry.animations.length; ++ i ) {
mixer.clipAction( geometry.animations[ i ] );
}
// Loading is complete, fire the callback
if ( onLoad !== undefined ) onLoad();
} );
};
this.update = function( dt ) {
this.mixer.update( dt );
};
this.play = function( animName, weight ) {
//console.log("play('%s', %f)", animName, weight);
return this.mixer.clipAction( animName ).
setEffectiveWeight( weight ).play();
};
this.crossfade = function( fromAnimName, toAnimName, duration ) {
this.mixer.stopAllAction();
var fromAction = this.play( fromAnimName, 1 );
var toAction = this.play( toAnimName, 1 );
fromAction.crossFadeTo( toAction, duration, false );
};
this.warp = function( fromAnimName, toAnimName, duration ) {
this.mixer.stopAllAction();
var fromAction = this.play( fromAnimName, 1 );
var toAction = this.play( toAnimName, 1 );
fromAction.crossFadeTo( toAction, duration, true );
};
this.applyWeight = function( animName, weight ) {
this.mixer.clipAction( animName ).setEffectiveWeight( weight );
};
this.getWeight = function( animName ) {
return this.mixer.clipAction( animName ).getEffectiveWeight();
};
this.pauseAll = function() {
this.mixer.timeScale = 0;
};
this.unPauseAll = function() {
this.mixer.timeScale = 1;
};
this.stopAll = function() {
this.mixer.stopAllAction();
};
this.showModel = function( boolean ) {
this.visible = boolean;
};
};
THREE.BlendCharacter.prototype = Object.create( THREE.SkinnedMesh.prototype );
THREE.BlendCharacter.prototype.constructor = THREE.BlendCharacter;
THREE.BlendCharacter.prototype.getForward = function() {
var forward = new THREE.Vector3();
return function() {
// pull the character's forward basis vector out of the matrix
forward.set(
- this.matrix.elements[ 8 ],
- this.matrix.elements[ 9 ],
- this.matrix.elements[ 10 ]
);
return forward;
}
};

207
node_modules/three/examples/js/BlendCharacterGui.js generated vendored Normal file
View File

@@ -0,0 +1,207 @@
/**
* @author Michael Guerrero / http://realitymeltdown.com
*/
function BlendCharacterGui( blendMesh ) {
var controls = {
gui: null,
"Show Model": true,
"Show Skeleton": false,
"Time Scale": 1.0,
"Step Size": 0.016,
"Crossfade Time": 3.5,
"idle": 0.33,
"walk": 0.33,
"run": 0.33
};
var blendMesh = blendMesh;
this.showModel = function() {
return controls[ 'Show Model' ];
};
this.showSkeleton = function() {
return controls[ 'Show Skeleton' ];
};
this.getTimeScale = function() {
return controls[ 'Time Scale' ];
};
this.update = function( time ) {
controls[ 'idle' ] = blendMesh.getWeight( 'idle' );
controls[ 'walk' ] = blendMesh.getWeight( 'walk' );
controls[ 'run' ] = blendMesh.getWeight( 'run' );
};
var init = function() {
controls.gui = new dat.GUI();
var settings = controls.gui.addFolder( 'Settings' );
var playback = controls.gui.addFolder( 'Playback' );
var blending = controls.gui.addFolder( 'Blend Tuning' );
settings.add( controls, "Show Model" ).onChange( controls.showModelChanged );
settings.add( controls, "Show Skeleton" ).onChange( controls.showSkeletonChanged );
settings.add( controls, "Time Scale", 0, 1, 0.01 );
settings.add( controls, "Step Size", 0.01, 0.1, 0.01 );
settings.add( controls, "Crossfade Time", 0.1, 6.0, 0.05 );
// These controls execute functions
playback.add( controls, "start" );
playback.add( controls, "pause" );
playback.add( controls, "step" );
playback.add( controls, "idle to walk" );
playback.add( controls, "walk to run" );
playback.add( controls, "warp walk to run" );
blending.add( controls, "idle", 0, 1, 0.01 ).listen().onChange( controls.weight );
blending.add( controls, "walk", 0, 1, 0.01 ).listen().onChange( controls.weight );
blending.add( controls, "run", 0, 1, 0.01 ).listen().onChange( controls.weight );
settings.open();
playback.open();
blending.open();
};
var getAnimationData = function() {
return {
detail: {
anims: [ "idle", "walk", "run" ],
weights: [ controls[ 'idle' ],
controls[ 'walk' ],
controls[ 'run' ] ]
}
};
};
controls.start = function() {
var startEvent = new CustomEvent( 'start-animation', getAnimationData() );
window.dispatchEvent( startEvent );
};
controls.stop = function() {
var stopEvent = new CustomEvent( 'stop-animation' );
window.dispatchEvent( stopEvent );
};
controls.pause = function() {
var pauseEvent = new CustomEvent( 'pause-animation' );
window.dispatchEvent( pauseEvent );
};
controls.step = function() {
var stepData = { detail: { stepSize: controls[ 'Step Size' ] } };
window.dispatchEvent( new CustomEvent( 'step-animation', stepData ) );
};
controls.weight = function() {
// renormalize
var sum = controls[ 'idle' ] + controls[ 'walk' ] + controls[ 'run' ];
controls[ 'idle' ] /= sum;
controls[ 'walk' ] /= sum;
controls[ 'run' ] /= sum;
var weightEvent = new CustomEvent( 'weight-animation', getAnimationData() );
window.dispatchEvent( weightEvent );
};
controls.crossfade = function( from, to ) {
var fadeData = getAnimationData();
fadeData.detail.from = from;
fadeData.detail.to = to;
fadeData.detail.time = controls[ "Crossfade Time" ];
window.dispatchEvent( new CustomEvent( 'crossfade', fadeData ) );
};
controls.warp = function( from, to ) {
var warpData = getAnimationData();
warpData.detail.from = 'walk';
warpData.detail.to = 'run';
warpData.detail.time = controls[ "Crossfade Time" ];
window.dispatchEvent( new CustomEvent( 'warp', warpData ) );
};
controls[ 'idle to walk' ] = function() {
controls.crossfade( 'idle', 'walk' );
};
controls[ 'walk to run' ] = function() {
controls.crossfade( 'walk', 'run' );
};
controls[ 'warp walk to run' ] = function() {
controls.warp( 'walk', 'run' );
};
controls.showSkeletonChanged = function() {
var data = {
detail: {
shouldShow: controls[ 'Show Skeleton' ]
}
};
window.dispatchEvent( new CustomEvent( 'toggle-show-skeleton', data ) );
};
controls.showModelChanged = function() {
var data = {
detail: {
shouldShow: controls[ 'Show Model' ]
}
};
window.dispatchEvent( new CustomEvent( 'toggle-show-model', data ) );
};
init.call( this );
}

187
node_modules/three/examples/js/BufferGeometryUtils.js generated vendored Normal file
View File

@@ -0,0 +1,187 @@
/**
* @author mrdoob / http://mrdoob.com/
*/
THREE.BufferGeometryUtils = {
computeTangents: function ( geometry ) {
var index = geometry.index;
var attributes = geometry.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 ) {
console.warn( 'THREE.BufferGeometry: Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()' );
return;
}
var indices = index.array;
var positions = attributes.position.array;
var normals = attributes.normal.array;
var uvs = attributes.uv.array;
var nVertices = positions.length / 3;
if ( attributes.tangent === undefined ) {
geometry.addAttribute( 'tangent', new THREE.BufferAttribute( new Float32Array( 4 * nVertices ), 4 ) );
}
var tangents = attributes.tangent.array;
var tan1 = [], tan2 = [];
for ( var k = 0; k < nVertices; k ++ ) {
tan1[ k ] = new THREE.Vector3();
tan2[ k ] = new THREE.Vector3();
}
var vA = new THREE.Vector3(),
vB = new THREE.Vector3(),
vC = new THREE.Vector3(),
uvA = new THREE.Vector2(),
uvB = new THREE.Vector2(),
uvC = new THREE.Vector2(),
sdir = new THREE.Vector3(),
tdir = new THREE.Vector3();
function handleTriangle( a, b, c ) {
vA.fromArray( positions, a * 3 );
vB.fromArray( positions, b * 3 );
vC.fromArray( positions, c * 3 );
uvA.fromArray( uvs, a * 2 );
uvB.fromArray( uvs, b * 2 );
uvC.fromArray( uvs, c * 2 );
var x1 = vB.x - vA.x;
var x2 = vC.x - vA.x;
var y1 = vB.y - vA.y;
var y2 = vC.y - vA.y;
var z1 = vB.z - vA.z;
var z2 = vC.z - vA.z;
var s1 = uvB.x - uvA.x;
var s2 = uvC.x - uvA.x;
var t1 = uvB.y - uvA.y;
var t2 = uvC.y - uvA.y;
var r = 1.0 / ( s1 * t2 - s2 * t1 );
sdir.set(
( t2 * x1 - t1 * x2 ) * r,
( t2 * y1 - t1 * y2 ) * r,
( t2 * z1 - t1 * z2 ) * r
);
tdir.set(
( s1 * x2 - s2 * x1 ) * r,
( s1 * y2 - s2 * y1 ) * r,
( s1 * z2 - s2 * z1 ) * 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 );
}
var groups = geometry.groups;
if ( groups.length === 0 ) {
groups = [ {
start: 0,
count: indices.length
} ];
}
for ( var j = 0, jl = groups.length; j < jl; ++ j ) {
var group = groups[ j ];
var start = group.start;
var count = group.count;
for ( var i = start, il = start + count; i < il; i += 3 ) {
handleTriangle(
indices[ i + 0 ],
indices[ i + 1 ],
indices[ i + 2 ]
);
}
}
var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3();
var n = new THREE.Vector3(), n2 = new THREE.Vector3();
var w, t, test;
function handleVertex( v ) {
n.fromArray( normals, v * 3 );
n2.copy( n );
t = tan1[ v ];
// Gram-Schmidt orthogonalize
tmp.copy( t );
tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
// Calculate handedness
tmp2.crossVectors( n2, t );
test = tmp2.dot( tan2[ v ] );
w = ( test < 0.0 ) ? - 1.0 : 1.0;
tangents[ v * 4 ] = tmp.x;
tangents[ v * 4 + 1 ] = tmp.y;
tangents[ v * 4 + 2 ] = tmp.z;
tangents[ v * 4 + 3 ] = w;
}
for ( var j = 0, jl = groups.length; j < jl; ++ j ) {
var group = groups[ j ];
var start = group.start;
var count = group.count;
for ( var i = start, il = start + count; i < il; i += 3 ) {
handleVertex( indices[ i + 0 ] );
handleVertex( indices[ i + 1 ] );
handleVertex( indices[ i + 2 ] );
}
}
}
};

407
node_modules/three/examples/js/Car.js generated vendored Normal file
View File

@@ -0,0 +1,407 @@
/**
* @author alteredq / http://alteredqualia.com/
*/
THREE.Car = function () {
var scope = this;
// car geometry manual parameters
this.modelScale = 1;
this.backWheelOffset = 2;
this.autoWheelGeometry = true;
// car geometry parameters automatically set from wheel mesh
// - assumes wheel mesh is front left wheel in proper global
// position with respect to body mesh
// - other wheels are mirrored against car root
// - if necessary back wheels can be offset manually
this.wheelOffset = new THREE.Vector3();
this.wheelDiameter = 1;
// car "feel" parameters
this.MAX_SPEED = 2200;
this.MAX_REVERSE_SPEED = - 1500;
this.MAX_WHEEL_ROTATION = 0.6;
this.FRONT_ACCELERATION = 1250;
this.BACK_ACCELERATION = 1500;
this.WHEEL_ANGULAR_ACCELERATION = 1.5;
this.FRONT_DECCELERATION = 750;
this.WHEEL_ANGULAR_DECCELERATION = 1.0;
this.STEERING_RADIUS_RATIO = 0.0023;
this.MAX_TILT_SIDES = 0.05;
this.MAX_TILT_FRONTBACK = 0.015;
// internal control variables
this.speed = 0;
this.acceleration = 0;
this.wheelOrientation = 0;
this.carOrientation = 0;
// car rigging
this.root = new THREE.Object3D();
this.frontLeftWheelRoot = new THREE.Object3D();
this.frontRightWheelRoot = new THREE.Object3D();
this.bodyMesh = null;
this.frontLeftWheelMesh = null;
this.frontRightWheelMesh = null;
this.backLeftWheelMesh = null;
this.backRightWheelMesh = null;
this.bodyGeometry = null;
this.wheelGeometry = null;
this.bodyMaterials = null;
this.wheelMaterials = null;
// internal helper variables
this.loaded = false;
this.meshes = [];
// API
this.enableShadows = function ( enable ) {
for ( var i = 0; i < this.meshes.length; i ++ ) {
this.meshes[ i ].castShadow = enable;
this.meshes[ i ].receiveShadow = enable;
}
};
this.setVisible = function ( enable ) {
for ( var i = 0; i < this.meshes.length; i ++ ) {
this.meshes[ i ].visible = enable;
this.meshes[ i ].visible = enable;
}
};
this.loadPartsJSON = function ( bodyURL, wheelURL ) {
var loader = new THREE.JSONLoader();
loader.load( bodyURL, function( geometry, materials ) {
createBody( geometry, materials )
} );
loader.load( wheelURL, function( geometry, materials ) {
createWheels( geometry, materials )
} );
};
this.loadPartsBinary = function ( bodyURL, wheelURL ) {
var loader = new THREE.BinaryLoader();
loader.load( bodyURL, function( geometry, materials ) {
createBody( geometry, materials )
} );
loader.load( wheelURL, function( geometry, materials ) {
createWheels( geometry, materials )
} );
};
this.updateCarModel = function ( delta, controls ) {
// speed and wheels based on controls
if ( controls.moveForward ) {
this.speed = THREE.Math.clamp( this.speed + delta * this.FRONT_ACCELERATION, this.MAX_REVERSE_SPEED, this.MAX_SPEED );
this.acceleration = THREE.Math.clamp( this.acceleration + delta, - 1, 1 );
}
if ( controls.moveBackward ) {
this.speed = THREE.Math.clamp( this.speed - delta * this.BACK_ACCELERATION, this.MAX_REVERSE_SPEED, this.MAX_SPEED );
this.acceleration = THREE.Math.clamp( this.acceleration - delta, - 1, 1 );
}
if ( controls.moveLeft ) {
this.wheelOrientation = THREE.Math.clamp( this.wheelOrientation + delta * this.WHEEL_ANGULAR_ACCELERATION, - this.MAX_WHEEL_ROTATION, this.MAX_WHEEL_ROTATION );
}
if ( controls.moveRight ) {
this.wheelOrientation = THREE.Math.clamp( this.wheelOrientation - delta * this.WHEEL_ANGULAR_ACCELERATION, - this.MAX_WHEEL_ROTATION, this.MAX_WHEEL_ROTATION );
}
// speed decay
if ( ! ( controls.moveForward || controls.moveBackward ) ) {
if ( this.speed > 0 ) {
var k = exponentialEaseOut( this.speed / this.MAX_SPEED );
this.speed = THREE.Math.clamp( this.speed - k * delta * this.FRONT_DECCELERATION, 0, this.MAX_SPEED );
this.acceleration = THREE.Math.clamp( this.acceleration - k * delta, 0, 1 );
} else {
var k = exponentialEaseOut( this.speed / this.MAX_REVERSE_SPEED );
this.speed = THREE.Math.clamp( this.speed + k * delta * this.BACK_ACCELERATION, this.MAX_REVERSE_SPEED, 0 );
this.acceleration = THREE.Math.clamp( this.acceleration + k * delta, - 1, 0 );
}
}
// steering decay
if ( ! ( controls.moveLeft || controls.moveRight ) ) {
if ( this.wheelOrientation > 0 ) {
this.wheelOrientation = THREE.Math.clamp( this.wheelOrientation - delta * this.WHEEL_ANGULAR_DECCELERATION, 0, this.MAX_WHEEL_ROTATION );
} else {
this.wheelOrientation = THREE.Math.clamp( this.wheelOrientation + delta * this.WHEEL_ANGULAR_DECCELERATION, - this.MAX_WHEEL_ROTATION, 0 );
}
}
// car update
var forwardDelta = this.speed * delta;
this.carOrientation += ( forwardDelta * this.STEERING_RADIUS_RATIO ) * this.wheelOrientation;
// displacement
this.root.position.x += Math.sin( this.carOrientation ) * forwardDelta;
this.root.position.z += Math.cos( this.carOrientation ) * forwardDelta;
// steering
this.root.rotation.y = this.carOrientation;
// tilt
if ( this.loaded ) {
this.bodyMesh.rotation.z = this.MAX_TILT_SIDES * this.wheelOrientation * ( this.speed / this.MAX_SPEED );
this.bodyMesh.rotation.x = - this.MAX_TILT_FRONTBACK * this.acceleration;
}
// wheels rolling
var angularSpeedRatio = 1 / ( this.modelScale * ( this.wheelDiameter / 2 ) );
var wheelDelta = forwardDelta * angularSpeedRatio;
if ( this.loaded ) {
this.frontLeftWheelMesh.rotation.x += wheelDelta;
this.frontRightWheelMesh.rotation.x += wheelDelta;
this.backLeftWheelMesh.rotation.x += wheelDelta;
this.backRightWheelMesh.rotation.x += wheelDelta;
}
// front wheels steering
this.frontLeftWheelRoot.rotation.y = this.wheelOrientation;
this.frontRightWheelRoot.rotation.y = this.wheelOrientation;
};
// internal helper methods
function createBody ( geometry, materials ) {
scope.bodyGeometry = geometry;
scope.bodyMaterials = materials;
createCar();
}
function createWheels ( geometry, materials ) {
scope.wheelGeometry = geometry;
scope.wheelMaterials = materials;
createCar();
}
function createCar () {
if ( scope.bodyGeometry && scope.wheelGeometry ) {
// compute wheel geometry parameters
if ( scope.autoWheelGeometry ) {
scope.wheelGeometry.computeBoundingBox();
var bb = scope.wheelGeometry.boundingBox;
scope.wheelOffset.addVectors( bb.min, bb.max );
scope.wheelOffset.multiplyScalar( 0.5 );
scope.wheelDiameter = bb.max.y - bb.min.y;
scope.wheelGeometry.center();
}
// rig the car
var s = scope.modelScale,
delta = new THREE.Vector3();
var bodyFaceMaterial = new THREE.MultiMaterial( scope.bodyMaterials );
var wheelFaceMaterial = new THREE.MultiMaterial( scope.wheelMaterials );
// body
scope.bodyMesh = new THREE.Mesh( scope.bodyGeometry, bodyFaceMaterial );
scope.bodyMesh.scale.set( s, s, s );
scope.root.add( scope.bodyMesh );
// front left wheel
delta.multiplyVectors( scope.wheelOffset, new THREE.Vector3( s, s, s ) );
scope.frontLeftWheelRoot.position.add( delta );
scope.frontLeftWheelMesh = new THREE.Mesh( scope.wheelGeometry, wheelFaceMaterial );
scope.frontLeftWheelMesh.scale.set( s, s, s );
scope.frontLeftWheelRoot.add( scope.frontLeftWheelMesh );
scope.root.add( scope.frontLeftWheelRoot );
// front right wheel
delta.multiplyVectors( scope.wheelOffset, new THREE.Vector3( - s, s, s ) );
scope.frontRightWheelRoot.position.add( delta );
scope.frontRightWheelMesh = new THREE.Mesh( scope.wheelGeometry, wheelFaceMaterial );
scope.frontRightWheelMesh.scale.set( s, s, s );
scope.frontRightWheelMesh.rotation.z = Math.PI;
scope.frontRightWheelRoot.add( scope.frontRightWheelMesh );
scope.root.add( scope.frontRightWheelRoot );
// back left wheel
delta.multiplyVectors( scope.wheelOffset, new THREE.Vector3( s, s, - s ) );
delta.z -= scope.backWheelOffset;
scope.backLeftWheelMesh = new THREE.Mesh( scope.wheelGeometry, wheelFaceMaterial );
scope.backLeftWheelMesh.position.add( delta );
scope.backLeftWheelMesh.scale.set( s, s, s );
scope.root.add( scope.backLeftWheelMesh );
// back right wheel
delta.multiplyVectors( scope.wheelOffset, new THREE.Vector3( - s, s, - s ) );
delta.z -= scope.backWheelOffset;
scope.backRightWheelMesh = new THREE.Mesh( scope.wheelGeometry, wheelFaceMaterial );
scope.backRightWheelMesh.position.add( delta );
scope.backRightWheelMesh.scale.set( s, s, s );
scope.backRightWheelMesh.rotation.z = Math.PI;
scope.root.add( scope.backRightWheelMesh );
// cache meshes
scope.meshes = [ scope.bodyMesh, scope.frontLeftWheelMesh, scope.frontRightWheelMesh, scope.backLeftWheelMesh, scope.backRightWheelMesh ];
// callback
scope.loaded = true;
if ( scope.callback ) {
scope.callback( scope );
}
}
}
function quadraticEaseOut( k ) {
return - k * ( k - 2 );
}
function cubicEaseOut( k ) {
return -- k * k * k + 1;
}
function circularEaseOut( k ) {
return Math.sqrt( 1 - -- k * k );
}
function sinusoidalEaseOut( k ) {
return Math.sin( k * Math.PI / 2 );
}
function exponentialEaseOut( k ) {
return k === 1 ? 1 : - Math.pow( 2, - 10 * k ) + 1;
}
};

330
node_modules/three/examples/js/Cloth.js generated vendored Normal file
View File

@@ -0,0 +1,330 @@
/*
* Cloth Simulation using a relaxed constraints solver
*/
// Suggested Readings
// Advanced Character Physics by Thomas Jakobsen Character
// http://freespace.virgin.net/hugo.elias/models/m_cloth.htm
// http://en.wikipedia.org/wiki/Cloth_modeling
// http://cg.alexandra.dk/tag/spring-mass-system/
// Real-time Cloth Animation http://www.darwin3d.com/gamedev/articles/col0599.pdf
var DAMPING = 0.03;
var DRAG = 1 - DAMPING;
var MASS = 0.1;
var restDistance = 25;
var xSegs = 10;
var ySegs = 10;
var clothFunction = plane( restDistance * xSegs, restDistance * ySegs );
var cloth = new Cloth( xSegs, ySegs );
var GRAVITY = 981 * 1.4;
var gravity = new THREE.Vector3( 0, - GRAVITY, 0 ).multiplyScalar( MASS );
var TIMESTEP = 18 / 1000;
var TIMESTEP_SQ = TIMESTEP * TIMESTEP;
var pins = [];
var wind = true;
var windStrength = 2;
var windForce = new THREE.Vector3( 0, 0, 0 );
var ballPosition = new THREE.Vector3( 0, - 45, 0 );
var ballSize = 60; //40
var tmpForce = new THREE.Vector3();
var lastTime;
function plane( width, height ) {
return function( u, v ) {
var x = ( u - 0.5 ) * width;
var y = ( v + 0.5 ) * height;
var z = 0;
return new THREE.Vector3( x, y, z );
};
}
function Particle( x, y, z, mass ) {
this.position = clothFunction( x, y ); // position
this.previous = clothFunction( x, y ); // previous
this.original = clothFunction( x, y );
this.a = new THREE.Vector3( 0, 0, 0 ); // acceleration
this.mass = mass;
this.invMass = 1 / mass;
this.tmp = new THREE.Vector3();
this.tmp2 = new THREE.Vector3();
}
// Force -> Acceleration
Particle.prototype.addForce = function( force ) {
this.a.add(
this.tmp2.copy( force ).multiplyScalar( this.invMass )
);
};
// Performs Verlet integration
Particle.prototype.integrate = function( timesq ) {
var newPos = this.tmp.subVectors( this.position, this.previous );
newPos.multiplyScalar( DRAG ).add( this.position );
newPos.add( this.a.multiplyScalar( timesq ) );
this.tmp = this.previous;
this.previous = this.position;
this.position = newPos;
this.a.set( 0, 0, 0 );
};
var diff = new THREE.Vector3();
function satisifyConstraints( p1, p2, distance ) {
diff.subVectors( p2.position, p1.position );
var currentDist = diff.length();
if ( currentDist === 0 ) return; // prevents division by 0
var correction = diff.multiplyScalar( 1 - distance / currentDist );
var correctionHalf = correction.multiplyScalar( 0.5 );
p1.position.add( correctionHalf );
p2.position.sub( correctionHalf );
}
function Cloth( w, h ) {
w = w || 10;
h = h || 10;
this.w = w;
this.h = h;
var particles = [];
var constraints = [];
var u, v;
// Create particles
for ( v = 0; v <= h; v ++ ) {
for ( u = 0; u <= w; u ++ ) {
particles.push(
new Particle( u / w, v / h, 0, MASS )
);
}
}
// Structural
for ( v = 0; v < h; v ++ ) {
for ( u = 0; u < w; u ++ ) {
constraints.push( [
particles[ index( u, v ) ],
particles[ index( u, v + 1 ) ],
restDistance
] );
constraints.push( [
particles[ index( u, v ) ],
particles[ index( u + 1, v ) ],
restDistance
] );
}
}
for ( u = w, v = 0; v < h; v ++ ) {
constraints.push( [
particles[ index( u, v ) ],
particles[ index( u, v + 1 ) ],
restDistance
] );
}
for ( v = h, u = 0; u < w; u ++ ) {
constraints.push( [
particles[ index( u, v ) ],
particles[ index( u + 1, v ) ],
restDistance
] );
}
// While many systems use shear and bend springs,
// the relaxed constraints model seems to be just fine
// using structural springs.
// Shear
// var diagonalDist = Math.sqrt(restDistance * restDistance * 2);
// for (v=0;v<h;v++) {
// for (u=0;u<w;u++) {
// constraints.push([
// particles[index(u, v)],
// particles[index(u+1, v+1)],
// diagonalDist
// ]);
// constraints.push([
// particles[index(u+1, v)],
// particles[index(u, v+1)],
// diagonalDist
// ]);
// }
// }
this.particles = particles;
this.constraints = constraints;
function index( u, v ) {
return u + v * ( w + 1 );
}
this.index = index;
}
function simulate( time ) {
if ( ! lastTime ) {
lastTime = time;
return;
}
var i, il, particles, particle, pt, constraints, constraint;
// Aerodynamics forces
if ( wind ) {
var face, faces = clothGeometry.faces, normal;
particles = cloth.particles;
for ( i = 0, il = faces.length; i < il; i ++ ) {
face = faces[ i ];
normal = face.normal;
tmpForce.copy( normal ).normalize().multiplyScalar( normal.dot( windForce ) );
particles[ face.a ].addForce( tmpForce );
particles[ face.b ].addForce( tmpForce );
particles[ face.c ].addForce( tmpForce );
}
}
for ( particles = cloth.particles, i = 0, il = particles.length; i < il; i ++ ) {
particle = particles[ i ];
particle.addForce( gravity );
particle.integrate( TIMESTEP_SQ );
}
// Start Constraints
constraints = cloth.constraints;
il = constraints.length;
for ( i = 0; i < il; i ++ ) {
constraint = constraints[ i ];
satisifyConstraints( constraint[ 0 ], constraint[ 1 ], constraint[ 2 ] );
}
// Ball Constraints
ballPosition.z = - Math.sin( Date.now() / 600 ) * 90 ; //+ 40;
ballPosition.x = Math.cos( Date.now() / 400 ) * 70;
if ( sphere.visible ) {
for ( particles = cloth.particles, i = 0, il = particles.length; i < il; i ++ ) {
particle = particles[ i ];
pos = particle.position;
diff.subVectors( pos, ballPosition );
if ( diff.length() < ballSize ) {
// collided
diff.normalize().multiplyScalar( ballSize );
pos.copy( ballPosition ).add( diff );
}
}
}
// Floor Constraints
for ( particles = cloth.particles, i = 0, il = particles.length; i < il; i ++ ) {
particle = particles[ i ];
pos = particle.position;
if ( pos.y < - 250 ) {
pos.y = - 250;
}
}
// Pin Constraints
for ( i = 0, il = pins.length; i < il; i ++ ) {
var xy = pins[ i ];
var p = particles[ xy ];
p.position.copy( p.original );
p.previous.copy( p.original );
}
}

489
node_modules/three/examples/js/ConvexObjectBreaker.js generated vendored Normal file
View File

@@ -0,0 +1,489 @@
/**
* @author yomboprime https://github.com/yomboprime
*
* @fileoverview This class can be used to subdivide a convex Geometry object into pieces.
*
* Usage:
*
* Use the function prepareBreakableObject to prepare a Mesh object to be broken.
*
* Then, call the various functions to subdivide the object (subdivideByImpact, cutByPlane)
*
* Sub-objects that are product of subdivision don't need prepareBreakableObject to be called on them.
*
* Requisites for the object:
*
* - Mesh object must have a Geometry (not BufferGeometry) and a Material
*
* - The Geometry must be convex (this is not tested in the library). You can create convex
* Geometries with THREE.ConvexGeometry. The BoxGeometry, SphereGeometry and other convex primitives
* can also be used.
*
* Note: This lib adds member variables to object's userData member and to its vertices.
* (see prepareBreakableObject function)
* Use with caution and read the code when using with other libs.
*
* @param {double} minSizeForBreak Min size a debris can have to break.
* @param {double} smallDelta Max distance to consider that a point belongs to a plane.
*
*/
THREE.ConvexObjectBreaker = function( minSizeForBreak, smallDelta ) {
this.minSizeForBreak = minSizeForBreak || 1.4;
this.smallDelta = smallDelta || 0.0001;
this.tempLine1 = new THREE.Line3();
this.tempPlane1 = new THREE.Plane();
this.tempPlane2 = new THREE.Plane();
this.tempCM1 = new THREE.Vector3();
this.tempCM2 = new THREE.Vector3();
this.tempVector3 = new THREE.Vector3();
this.tempVector3_2 = new THREE.Vector3();
this.tempVector3_3 = new THREE.Vector3();
this.tempResultObjects = { object1: null, object2: null };
this.segments = [];
var n = 30 * 30;
for ( var i = 0; i < n; i++ ) {
this.segments[ i ] = false;
}
};
THREE.ConvexObjectBreaker.prototype = {
constructor: THREE.ConvexObjectBreaker,
prepareBreakableObject: function( object, mass, velocity, angularVelocity, breakable ) {
// object is a THREE.Object3d (normally a Mesh), must have a Geometry, and it must be convex.
// Its material property is propagated to its children (sub-pieces)
// mass must be > 0
// Create vertices mark
var vertices = object.geometry.vertices;
for ( var i = 0, il = vertices.length; i < il; i++ ) {
vertices[ i ].mark = 0;
}
var userData = object.userData;
userData.mass = mass;
userData.velocity = velocity.clone();
userData.angularVelocity = angularVelocity.clone();
userData.breakable = breakable;
},
/*
* @param {int} maxRadialIterations Iterations for radial cuts.
* @param {int} maxRandomIterations Max random iterations for not-radial cuts
* @param {double} minSizeForRadialSubdivision Min size a debris can have to break in radial subdivision.
*
* Returns the array of pieces
*/
subdivideByImpact: function( object, pointOfImpact, normal, maxRadialIterations, maxRandomIterations, minSizeForRadialSubdivision ) {
var debris = [];
var tempPlane1 = this.tempPlane1;
var tempPlane2 = this.tempPlane2;
this.tempVector3.addVectors( pointOfImpact, normal );
tempPlane1.setFromCoplanarPoints( pointOfImpact, object.position, this.tempVector3 );
var maxTotalIterations = maxRandomIterations + maxRadialIterations;
var scope = this;
function subdivideRadial( subObject, startAngle, endAngle, numIterations ) {
if ( Math.random() < numIterations * 0.05 || numIterations > maxTotalIterations ) {
debris.push( subObject );
return;
}
var angle = Math.PI;
if ( numIterations === 0 ) {
tempPlane2.normal.copy( tempPlane1.normal );
tempPlane2.constant = tempPlane1.constant;
}
else {
if ( numIterations <= maxRadialIterations ) {
angle = ( endAngle - startAngle ) * ( 0.2 + 0.6 * Math.random() ) + startAngle;
// Rotate tempPlane2 at impact point around normal axis and the angle
scope.tempVector3_2.copy( object.position ).sub( pointOfImpact ).applyAxisAngle( normal, angle ).add( pointOfImpact );
tempPlane2.setFromCoplanarPoints( pointOfImpact, scope.tempVector3, scope.tempVector3_2 );
}
else {
angle = ( ( 0.5 * ( numIterations & 1 ) ) + 0.2 * ( 2 - Math.random() ) ) * Math.PI;
// Rotate tempPlane2 at object position around normal axis and the angle
scope.tempVector3_2.copy( pointOfImpact ).sub( subObject.position ).applyAxisAngle( normal, angle ).add( subObject.position );
scope.tempVector3_3.copy( normal ).add( subObject.position );
tempPlane2.setFromCoplanarPoints( subObject.position, scope.tempVector3_3, scope.tempVector3_2 );
}
}
// Perform the cut
scope.cutByPlane( subObject, tempPlane2, scope.tempResultObjects );
var obj1 = scope.tempResultObjects.object1;
var obj2 = scope.tempResultObjects.object2;
if ( obj1 ) {
subdivideRadial( obj1, startAngle, angle, numIterations + 1 );
}
if ( obj2 ) {
subdivideRadial( obj2, angle, endAngle, numIterations + 1 );
}
}
subdivideRadial( object, 0, 2 * Math.PI, 0 );
return debris;
},
cutByPlane: function( object, plane, output ) {
// Returns breakable objects in output.object1 and output.object2 members, the resulting 2 pieces of the cut.
// object2 can be null if the plane doesn't cut the object.
// object1 can be null only in case of internal error
// Returned value is number of pieces, 0 for error.
var geometry = object.geometry;
var points = geometry.vertices;
var faces = geometry.faces;
var numPoints = points.length;
var points1 = [];
var points2 = [];
var delta = this.smallDelta;
// Reset vertices mark
for ( var i = 0; i < numPoints; i++ ) {
points[ i ].mark = 0;
}
// Reset segments mark
var numPointPairs = numPoints * numPoints;
for ( var i = 0; i < numPointPairs; i++ ) {
this.segments[ i ] = false;
}
// Iterate through the faces to mark edges shared by coplanar faces
for ( var i = 0, il = faces.length - 1; i < il; i++ ) {
var face1 = faces[ i ];
for ( var j = i + 1, jl = faces.length; j < jl; j++ ) {
var face2 = faces[ j ];
var coplanar = 1 - face1.normal.dot( face2.normal ) < delta;
if ( coplanar ) {
var a1 = face1.a;
var b1 = face1.b;
var c1 = face1.c;
var a2 = face2.a;
var b2 = face2.b;
var c2 = face2.c;
if ( a1 === a2 || a1 === b2 || a1 === c2 ) {
if ( b1 === a2 || b1 === b2 || b1 === c2 ) {
this.segments[ a1 * numPoints + b1 ] = true;
this.segments[ b1 * numPoints + a1 ] = true;
}
else {
this.segments[ c1 * numPoints + a1 ] = true;
this.segments[ a1 * numPoints + c1 ] = true;
}
}
else if ( b1 === a2 || b1 === b2 || b1 === c2 ) {
this.segments[ c1 * numPoints + b1 ] = true;
this.segments[ b1 * numPoints + c1 ] = true;
}
}
}
}
// Transform the plane to object local space
var localPlane = this.tempPlane1;
object.updateMatrix();
THREE.ConvexObjectBreaker.transformPlaneToLocalSpace( plane, object.matrix, localPlane );
// Iterate through the faces adding points to both pieces
for ( var i = 0, il = faces.length; i < il; i ++ ) {
var face = faces[ i ];
for ( var segment = 0; segment < 3; segment++ ) {
var i0 = segment === 0 ? face.a : ( segment === 1 ? face.b : face.c );
var i1 = segment === 0 ? face.b : ( segment === 1 ? face.c : face.a );
var segmentState = this.segments[ i0 * numPoints + i1 ];
if ( segmentState ) {
// The segment already has been processed in another face
continue;
}
// Mark segment as processed (also inverted segment)
this.segments[ i0 * numPoints + i1 ] = true;
this.segments[ i1 * numPoints + i0 ] = true;
var p0 = points[ i0 ];
var p1 = points[ i1 ];
if ( p0.mark === 0 ) {
var d = localPlane.distanceToPoint( p0 );
// mark: 1 for negative side, 2 for positive side, 3 for coplanar point
if ( d > delta ) {
p0.mark = 2;
points2.push( p0 );
}
else if ( d < - delta ) {
p0.mark = 1;
points1.push( p0 );
}
else {
p0.mark = 3;
points1.push( p0 );
var p0_2 = p0.clone();
p0_2.mark = 3;
points2.push( p0_2 );
}
}
if ( p1.mark === 0 ) {
var d = localPlane.distanceToPoint( p1 );
// mark: 1 for negative side, 2 for positive side, 3 for coplanar point
if ( d > delta ) {
p1.mark = 2;
points2.push( p1 );
}
else if ( d < - delta ) {
p1.mark = 1;
points1.push( p1 );
}
else {
p1.mark = 3;
points1.push( p1 );
var p1_2 = p1.clone();
p1_2.mark = 3;
points2.push( p1_2 );
}
}
var mark0 = p0.mark;
var mark1 = p1.mark;
if ( ( mark0 === 1 && mark1 === 2 ) || ( mark0 === 2 && mark1 === 1 ) ) {
// Intersection of segment with the plane
this.tempLine1.start.copy( p0 );
this.tempLine1.end.copy( p1 );
var intersection = localPlane.intersectLine( this.tempLine1 );
if ( intersection === undefined ) {
// Shouldn't happen
console.error( "Internal error: segment does not intersect plane." );
output.segmentedObject1 = null;
output.segmentedObject2 = null;
return 0;
}
intersection.mark = 1;
points1.push( intersection );
var intersection_2 = intersection.clone();
intersection_2.mark = 2;
points2.push( intersection_2 );
}
}
}
// Calculate debris mass (very fast and imprecise):
var newMass = object.userData.mass * 0.5;
// Calculate debris Center of Mass (again fast and imprecise)
this.tempCM1.set( 0, 0, 0 );
var radius1 = 0;
var numPoints1 = points1.length;
if ( numPoints1 > 0 ) {
for ( var i = 0; i < numPoints1; i++ ) {
this.tempCM1.add( points1[ i ] );
}
this.tempCM1.divideScalar( numPoints1 );
for ( var i = 0; i < numPoints1; i++ ) {
var p = points1[ i ];
p.sub( this.tempCM1 );
radius1 = Math.max( radius1, p.x, p.y, p.z );
}
this.tempCM1.add( object.position );
}
this.tempCM2.set( 0, 0, 0 );
var radius2 = 0;
var numPoints2 = points2.length;
if ( numPoints2 > 0 ) {
for ( var i = 0; i < numPoints2; i++ ) {
this.tempCM2.add( points2[ i ] );
}
this.tempCM2.divideScalar( numPoints2 );
for ( var i = 0; i < numPoints2; i++ ) {
var p = points2[ i ];
p.sub( this.tempCM2 );
radius2 = Math.max( radius2, p.x, p.y, p.z );
}
this.tempCM2.add( object.position );
}
var object1 = null;
var object2 = null;
var numObjects = 0;
if ( numPoints1 > 4 ) {
object1 = new THREE.Mesh( new THREE.ConvexGeometry( points1 ), object.material );
object1.position.copy( this.tempCM1 );
object1.quaternion.copy( object.quaternion );
this.prepareBreakableObject( object1, newMass, object.userData.velocity, object.userData.angularVelocity, 2 * radius1 > this.minSizeForBreak );
numObjects++;
}
if ( numPoints2 > 4 ) {
object2 = new THREE.Mesh( new THREE.ConvexGeometry( points2 ), object.material );
object2.position.copy( this.tempCM2 );
object2.quaternion.copy( object.quaternion );
this.prepareBreakableObject( object2, newMass, object.userData.velocity, object.userData.angularVelocity, 2 * radius2 > this.minSizeForBreak );
numObjects++;
}
output.object1 = object1;
output.object2 = object2;
return numObjects;
}
};
THREE.ConvexObjectBreaker.transformFreeVector = function( v, m ) {
// input:
// vector interpreted as a free vector
// THREE.Matrix4 orthogonal matrix (matrix without scale)
var x = v.x, y = v.y, z = v.z;
var e = m.elements;
v.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
v.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
v.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
return v;
};
THREE.ConvexObjectBreaker.transformFreeVectorInverse = function( v, m ) {
// input:
// vector interpreted as a free vector
// THREE.Matrix4 orthogonal matrix (matrix without scale)
var x = v.x, y = v.y, z = v.z;
var e = m.elements;
v.x = e[ 0 ] * x + e[ 1 ] * y + e[ 2 ] * z;
v.y = e[ 4 ] * x + e[ 5 ] * y + e[ 6 ] * z;
v.z = e[ 8 ] * x + e[ 9 ] * y + e[ 10 ] * z;
return v;
};
THREE.ConvexObjectBreaker.transformTiedVectorInverse = function( v, m ) {
// input:
// vector interpreted as a tied (ordinary) vector
// THREE.Matrix4 orthogonal matrix (matrix without scale)
var x = v.x, y = v.y, z = v.z;
var e = m.elements;
v.x = e[ 0 ] * x + e[ 1 ] * y + e[ 2 ] * z - e[ 12 ];
v.y = e[ 4 ] * x + e[ 5 ] * y + e[ 6 ] * z - e[ 13 ];
v.z = e[ 8 ] * x + e[ 9 ] * y + e[ 10 ] * z - e[ 14 ];
return v;
};
THREE.ConvexObjectBreaker.transformPlaneToLocalSpace = function() {
var v1 = new THREE.Vector3();
var m1 = new THREE.Matrix3();
return function transformPlaneToLocalSpace( plane, m, resultPlane ) {
resultPlane.normal.copy( plane.normal );
resultPlane.constant = plane.constant;
var referencePoint = THREE.ConvexObjectBreaker.transformTiedVectorInverse( plane.coplanarPoint( v1 ), m );
THREE.ConvexObjectBreaker.transformFreeVectorInverse( resultPlane.normal, m );
// recalculate constant (like in setFromNormalAndCoplanarPoint)
resultPlane.constant = - referencePoint.dot( resultPlane.normal );
};
}();

363
node_modules/three/examples/js/CurveExtras.js generated vendored Normal file
View File

@@ -0,0 +1,363 @@
/*
* A bunch of parametric curves
* @author zz85
*
* Formulas collected from various sources
* http://mathworld.wolfram.com/HeartCurve.html
* http://mathdl.maa.org/images/upload_library/23/stemkoski/knots/page6.html
* http://en.wikipedia.org/wiki/Viviani%27s_curve
* http://mathdl.maa.org/images/upload_library/23/stemkoski/knots/page4.html
* http://www.mi.sanu.ac.rs/vismath/taylorapril2011/Taylor.pdf
* http://prideout.net/blog/?p=44
*/
( function( Curves ) {
// GrannyKnot
function GrannyKnot() {}
GrannyKnot.prototype = Object.create( THREE.Curve.prototype );
GrannyKnot.prototype.constructor = GrannyKnot;
GrannyKnot.prototype.getPoint = function( t ) {
t = 2 * Math.PI * t;
var x = - 0.22 * Math.cos( t ) - 1.28 * Math.sin( t ) - 0.44 * Math.cos( 3 * t ) - 0.78 * Math.sin( 3 * t );
var y = - 0.1 * Math.cos( 2 * t ) - 0.27 * Math.sin( 2 * t ) + 0.38 * Math.cos( 4 * t ) + 0.46 * Math.sin( 4 * t );
var z = 0.7 * Math.cos( 3 * t ) - 0.4 * Math.sin( 3 * t );
return new THREE.Vector3( x, y, z ).multiplyScalar( 20 );
};
// HeartCurve
function HeartCurve( s ) {
this.scale = ( s === undefined ) ? 5 : s;
}
HeartCurve.prototype = Object.create( THREE.Curve.prototype );
HeartCurve.prototype.constructor = HeartCurve;
HeartCurve.prototype.getPoint = function( t ) {
t *= 2 * Math.PI;
var x = 16 * Math.pow( Math.sin( t ), 3 );
var y = 13 * Math.cos( t ) - 5 * Math.cos( 2 * t ) - 2 * Math.cos( 3 * t ) - Math.cos( 4 * t );
var z = 0;
return new THREE.Vector3( x, y, z ).multiplyScalar( this.scale );
};
// Viviani's Curve
function VivianiCurve( radius ) {
this.radius = radius;
}
VivianiCurve.prototype = Object.create( THREE.Curve.prototype );
VivianiCurve.prototype.constructor = VivianiCurve;
VivianiCurve.prototype.getPoint = function( t ) {
t = t * 4 * Math.PI; // normalized to 0..1
var a = this.radius / 2;
var x = a * ( 1 + Math.cos( t ) );
var y = a * Math.sin( t );
var z = 2 * a * Math.sin( t / 2 );
return new THREE.Vector3( x, y, z );
};
// KnotCurve
function KnotCurve() {}
KnotCurve.prototype = Object.create( THREE.Curve.prototype );
KnotCurve.prototype.constructor = KnotCurve;
KnotCurve.prototype.getPoint = function( t ) {
t *= 2 * Math.PI;
var R = 10;
var s = 50;
var x = s * Math.sin( t );
var y = Math.cos( t ) * ( R + s * Math.cos( t ) );
var z = Math.sin( t ) * ( R + s * Math.cos( t ) );
return new THREE.Vector3( x, y, z );
};
// HelixCurve
function HelixCurve() {}
HelixCurve.prototype = Object.create( THREE.Curve.prototype );
HelixCurve.prototype.constructor = HelixCurve;
HelixCurve.prototype.getPoint = function( t ) {
var a = 30; // radius
var b = 150; // height
var t2 = 2 * Math.PI * t * b / 30;
var x = Math.cos( t2 ) * a;
var y = Math.sin( t2 ) * a;
var z = b * t;
return new THREE.Vector3( x, y, z );
};
// TrefoilKnot
function TrefoilKnot( s ) {
this.scale = ( s === undefined ) ? 10 : s;
}
TrefoilKnot.prototype = Object.create( THREE.Curve.prototype );
TrefoilKnot.prototype.constructor = TrefoilKnot;
TrefoilKnot.prototype.getPoint = function( t ) {
t *= Math.PI * 2;
var x = ( 2 + Math.cos( 3 * t ) ) * Math.cos( 2 * t );
var y = ( 2 + Math.cos( 3 * t ) ) * Math.sin( 2 * t );
var z = Math.sin( 3 * t );
return new THREE.Vector3( x, y, z ).multiplyScalar( this.scale );
};
// TorusKnot
function TorusKnot( s ) {
this.scale = ( s === undefined ) ? 10 : s;
}
TorusKnot.prototype = Object.create( THREE.Curve.prototype );
TorusKnot.prototype.constructor = TorusKnot;
TorusKnot.prototype.getPoint = function( t ) {
var p = 3;
var q = 4;
t *= Math.PI * 2;
var x = ( 2 + Math.cos( q * t ) ) * Math.cos( p * t );
var y = ( 2 + Math.cos( q * t ) ) * Math.sin( p * t );
var z = Math.sin( q * t );
return new THREE.Vector3( x, y, z ).multiplyScalar( this.scale );
};
// CinquefoilKnot
function CinquefoilKnot( s ) {
this.scale = ( s === undefined ) ? 10 : s;
}
CinquefoilKnot.prototype = Object.create( THREE.Curve.prototype );
CinquefoilKnot.prototype.constructor = CinquefoilKnot;
CinquefoilKnot.prototype.getPoint = function( t ) {
var p = 2;
var q = 5;
t *= Math.PI * 2;
var x = ( 2 + Math.cos( q * t ) ) * Math.cos( p * t );
var y = ( 2 + Math.cos( q * t ) ) * Math.sin( p * t );
var z = Math.sin( q * t );
return new THREE.Vector3( x, y, z ).multiplyScalar( this.scale );
};
// TrefoilPolynomialKnot
function TrefoilPolynomialKnot( s ) {
this.scale = ( s === undefined ) ? 10 : s;
}
TrefoilPolynomialKnot.prototype = Object.create( THREE.Curve.prototype );
TrefoilPolynomialKnot.prototype.constructor = TrefoilPolynomialKnot;
TrefoilPolynomialKnot.prototype.getPoint = function( t ) {
t = t * 4 - 2;
var x = Math.pow( t, 3 ) - 3 * t;
var y = Math.pow( t, 4 ) - 4 * t * t;
var z = 1 / 5 * Math.pow( t, 5 ) - 2 * t;
return new THREE.Vector3( x, y, z ).multiplyScalar( this.scale );
};
var scaleTo = function( x, y, t ) {
var r = y - x;
return t * r + x;
};
// FigureEightPolynomialKnot
function FigureEightPolynomialKnot( s ) {
this.scale = ( s === undefined ) ? 1 : s;
}
FigureEightPolynomialKnot.prototype = Object.create( THREE.Curve.prototype );
FigureEightPolynomialKnot.prototype.constructor = FigureEightPolynomialKnot;
FigureEightPolynomialKnot.prototype.getPoint = function( t ) {
t = scaleTo( - 4, 4, t );
var x = 2 / 5 * t * ( t * t - 7 ) * ( t * t - 10 );
var y = Math.pow( t, 4 ) - 13 * t * t;
var z = 1 / 10 * t * ( t * t - 4 ) * ( t * t - 9 ) * ( t * t - 12 );
return new THREE.Vector3( x, y, z ).multiplyScalar( this.scale );
};
// DecoratedTorusKnot4a
function DecoratedTorusKnot4a( s ) {
this.scale = ( s === undefined ) ? 40 : s;
}
DecoratedTorusKnot4a.prototype = Object.create( THREE.Curve.prototype );
DecoratedTorusKnot4a.prototype.constructor = DecoratedTorusKnot4a;
DecoratedTorusKnot4a.prototype.getPoint = function( t ) {
t *= Math.PI * 2;
var x = Math.cos( 2 * t ) * ( 1 + 0.6 * ( Math.cos( 5 * t ) + 0.75 * Math.cos( 10 * t ) ) );
var y = Math.sin( 2 * t ) * ( 1 + 0.6 * ( Math.cos( 5 * t ) + 0.75 * Math.cos( 10 * t ) ) );
var z = 0.35 * Math.sin( 5 * t );
return new THREE.Vector3( x, y, z ).multiplyScalar( this.scale );
};
// DecoratedTorusKnot4b
function DecoratedTorusKnot4b( s ) {
this.scale = ( s === undefined ) ? 40 : s;
}
DecoratedTorusKnot4b.prototype = Object.create( THREE.Curve.prototype );
DecoratedTorusKnot4b.prototype.constructor = DecoratedTorusKnot4b;
DecoratedTorusKnot4b.prototype.getPoint = function( t ) {
var fi = t * Math.PI * 2;
var x = Math.cos( 2 * fi ) * ( 1 + 0.45 * Math.cos( 3 * fi ) + 0.4 * Math.cos( 9 * fi ) );
var y = Math.sin( 2 * fi ) * ( 1 + 0.45 * Math.cos( 3 * fi ) + 0.4 * Math.cos( 9 * fi ) );
var z = 0.2 * Math.sin( 9 * fi );
return new THREE.Vector3( x, y, z ).multiplyScalar( this.scale );
};
// DecoratedTorusKnot5a
function DecoratedTorusKnot5a( s ) {
this.scale = ( s === undefined ) ? 40 : s;
}
DecoratedTorusKnot5a.prototype = Object.create( THREE.Curve.prototype );
DecoratedTorusKnot5a.prototype.constructor = DecoratedTorusKnot5a;
DecoratedTorusKnot5a.prototype.getPoint = function( t ) {
var fi = t * Math.PI * 2;
var x = Math.cos( 3 * fi ) * ( 1 + 0.3 * Math.cos( 5 * fi ) + 0.5 * Math.cos( 10 * fi ) );
var y = Math.sin( 3 * fi ) * ( 1 + 0.3 * Math.cos( 5 * fi ) + 0.5 * Math.cos( 10 * fi ) );
var z = 0.2 * Math.sin( 20 * fi );
return new THREE.Vector3( x, y, z ).multiplyScalar( this.scale );
};
// DecoratedTorusKnot5c
function DecoratedTorusKnot5c( s ) {
this.scale = ( s === undefined ) ? 40 : s;
}
DecoratedTorusKnot5c.prototype = Object.create( THREE.Curve.prototype );
DecoratedTorusKnot5c.prototype.constructor = DecoratedTorusKnot5c;
DecoratedTorusKnot5c.prototype.getPoint = function( t ) {
var fi = t * Math.PI * 2;
var x = Math.cos( 4 * fi ) * ( 1 + 0.5 * ( Math.cos( 5 * fi ) + 0.4 * Math.cos( 20 * fi ) ) );
var y = Math.sin( 4 * fi ) * ( 1 + 0.5 * ( Math.cos( 5 * fi ) + 0.4 * Math.cos( 20 * fi ) ) );
var z = 0.35 * Math.sin( 15 * fi );
return new THREE.Vector3( x, y, z ).multiplyScalar( this.scale );
};
// export
Curves.GrannyKnot = GrannyKnot;
Curves.HeartCurve = HeartCurve;
Curves.VivianiCurve = VivianiCurve;
Curves.KnotCurve = KnotCurve;
Curves.HelixCurve = HelixCurve;
Curves.TrefoilKnot = TrefoilKnot;
Curves.TorusKnot = TorusKnot;
Curves.CinquefoilKnot = CinquefoilKnot;
Curves.TrefoilPolynomialKnot = TrefoilPolynomialKnot;
Curves.FigureEightPolynomialKnot = FigureEightPolynomialKnot;
Curves.DecoratedTorusKnot4a = DecoratedTorusKnot4a;
Curves.DecoratedTorusKnot4b = DecoratedTorusKnot4b;
Curves.DecoratedTorusKnot5a = DecoratedTorusKnot5a;
Curves.DecoratedTorusKnot5c = DecoratedTorusKnot5c;
} ) ( THREE.Curves = THREE.Curves || {} );

78
node_modules/three/examples/js/Detector.js generated vendored Normal file
View File

@@ -0,0 +1,78 @@
/**
* @author alteredq / http://alteredqualia.com/
* @author mr.doob / http://mrdoob.com/
*/
var Detector = {
canvas: !! window.CanvasRenderingContext2D,
webgl: ( function () {
try {
var canvas = document.createElement( 'canvas' ); return !! ( window.WebGLRenderingContext && ( canvas.getContext( 'webgl' ) || canvas.getContext( 'experimental-webgl' ) ) );
} catch ( e ) {
return false;
}
} )(),
workers: !! window.Worker,
fileapi: window.File && window.FileReader && window.FileList && window.Blob,
getWebGLErrorMessage: function () {
var element = document.createElement( 'div' );
element.id = 'webgl-error-message';
element.style.fontFamily = 'monospace';
element.style.fontSize = '13px';
element.style.fontWeight = 'normal';
element.style.textAlign = 'center';
element.style.background = '#fff';
element.style.color = '#000';
element.style.padding = '1.5em';
element.style.width = '400px';
element.style.margin = '5em auto 0';
if ( ! this.webgl ) {
element.innerHTML = window.WebGLRenderingContext ? [
'Your graphics card does not seem to support <a href="http://khronos.org/webgl/wiki/Getting_a_WebGL_Implementation" style="color:#000">WebGL</a>.<br />',
'Find out how to get it <a href="http://get.webgl.org/" style="color:#000">here</a>.'
].join( '\n' ) : [
'Your browser does not seem to support <a href="http://khronos.org/webgl/wiki/Getting_a_WebGL_Implementation" style="color:#000">WebGL</a>.<br/>',
'Find out how to get it <a href="http://get.webgl.org/" style="color:#000">here</a>.'
].join( '\n' );
}
return element;
},
addGetWebGLMessage: function ( parameters ) {
var parent, id, element;
parameters = parameters || {};
parent = parameters.parent !== undefined ? parameters.parent : document.body;
id = parameters.id !== undefined ? parameters.id : 'oldie';
element = Detector.getWebGLErrorMessage();
element.id = id;
parent.appendChild( element );
}
};
// browserify support
if ( typeof module === 'object' ) {
module.exports = Detector;
}

View File

@@ -0,0 +1,370 @@
/**
* @author yomboprime https://github.com/yomboprime
*
* GPUComputationRenderer, based on SimulationRenderer by zz85
*
* The GPUComputationRenderer uses the concept of variables. These variables are RGBA float textures that hold 4 floats
* for each compute element (texel)
*
* Each variable has a fragment shader that defines the computation made to obtain the variable in question.
* You can use as many variables you need, and make dependencies so you can use textures of other variables in the shader
* (the sampler uniforms are added automatically) Most of the variables will need themselves as dependency.
*
* The renderer has actually two render targets per variable, to make ping-pong. Textures from the current frame are used
* as inputs to render the textures of the next frame.
*
* The render targets of the variables can be used as input textures for your visualization shaders.
*
* Variable names should be valid identifiers and should not collide with THREE GLSL used identifiers.
* a common approach could be to use 'texture' prefixing the variable name; i.e texturePosition, textureVelocity...
*
* The size of the computation (sizeX * sizeY) is defined as 'resolution' automatically in the shader. For example:
* #DEFINE resolution vec2( 1024.0, 1024.0 )
*
* -------------
*
* Basic use:
*
* // Initialization...
*
* // Create computation renderer
* var gpuCompute = new GPUComputationRenderer( 1024, 1024, renderer );
*
* // Create initial state float textures
* var pos0 = gpuCompute.createTexture();
* var vel0 = gpuCompute.createTexture();
* // and fill in here the texture data...
*
* // Add texture variables
* var velVar = gpuCompute.addVariable( "textureVelocity", fragmentShaderVel, pos0 );
* var posVar = gpuCompute.addVariable( "texturePosition", fragmentShaderPos, vel0 );
*
* // Add variable dependencies
* gpuCompute.setVariableDependencies( velVar, [ velVar, posVar ] );
* gpuCompute.setVariableDependencies( posVar, [ velVar, posVar ] );
*
* // Add custom uniforms
* velVar.material.uniforms.time = { value: 0.0 };
*
* // Check for completeness
* var error = gpuCompute.init();
* if ( error !== null ) {
* console.error( error );
* }
*
*
* // In each frame...
*
* // Compute!
* gpuCompute.compute();
*
* // Update texture uniforms in your visualization materials with the gpu renderer output
* myMaterial.uniforms.myTexture.value = gpuCompute.getCurrentRenderTarget( posVar ).texture;
*
* // Do your rendering
* renderer.render( myScene, myCamera );
*
* -------------
*
* Also, you can use utility functions to create ShaderMaterial and perform computations (rendering between textures)
* Note that the shaders can have multiple input textures.
*
* var myFilter1 = gpuCompute.createShaderMaterial( myFilterFragmentShader1, { theTexture: { value: null } } );
* var myFilter2 = gpuCompute.createShaderMaterial( myFilterFragmentShader2, { theTexture: { value: null } } );
*
* var inputTexture = gpuCompute.createTexture();
*
* // Fill in here inputTexture...
*
* myFilter1.uniforms.theTexture.value = inputTexture;
*
* var myRenderTarget = gpuCompute.createRenderTarget();
* myFilter2.uniforms.theTexture.value = myRenderTarget.texture;
*
* var outputRenderTarget = gpuCompute.createRenderTarget();
*
* // Now use the output texture where you want:
* myMaterial.uniforms.map.value = outputRenderTarget.texture;
*
* // And compute each frame, before rendering to screen:
* gpuCompute.doRenderTarget( myFilter1, myRenderTarget );
* gpuCompute.doRenderTarget( myFilter2, outputRenderTarget );
*
*
*
* @param {int} sizeX Computation problem size is always 2d: sizeX * sizeY elements.
* @param {int} sizeY Computation problem size is always 2d: sizeX * sizeY elements.
* @param {WebGLRenderer} renderer The renderer
*/
function GPUComputationRenderer( sizeX, sizeY, renderer ) {
this.variables = [];
this.currentTextureIndex = 0;
var scene = new THREE.Scene();
var camera = new THREE.Camera();
camera.position.z = 1;
var passThruUniforms = {
texture: { value: null }
};
var passThruShader = createShaderMaterial( getPassThroughFragmentShader(), passThruUniforms );
var mesh = new THREE.Mesh( new THREE.PlaneBufferGeometry( 2, 2 ), passThruShader );
scene.add( mesh );
this.addVariable = function( variableName, computeFragmentShader, initialValueTexture ) {
var material = this.createShaderMaterial( computeFragmentShader );
var variable = {
name: variableName,
initialValueTexture: initialValueTexture,
material: material,
dependencies: null,
renderTargets: [],
wrapS: null,
wrapT: null,
minFilter: THREE.NearestFilter,
magFilter: THREE.NearestFilter
};
this.variables.push( variable );
return variable;
};
this.setVariableDependencies = function( variable, dependencies ) {
variable.dependencies = dependencies;
};
this.init = function() {
if ( ! renderer.extensions.get( "OES_texture_float" ) ) {
return "No OES_texture_float support for float textures.";
}
if ( renderer.capabilities.maxVertexTextures === 0 ) {
return "No support for vertex shader textures.";
}
for ( var i = 0; i < this.variables.length; i++ ) {
var variable = this.variables[ i ];
// Creates rendertargets and initialize them with input texture
variable.renderTargets[ 0 ] = this.createRenderTarget( sizeX, sizeY, variable.wrapS, variable.wrapT, variable.minFilter, variable.magFilter );
variable.renderTargets[ 1 ] = this.createRenderTarget( sizeX, sizeY, variable.wrapS, variable.wrapT, variable.minFilter, variable.magFilter );
this.renderTexture( variable.initialValueTexture, variable.renderTargets[ 0 ] );
this.renderTexture( variable.initialValueTexture, variable.renderTargets[ 1 ] );
// Adds dependencies uniforms to the ShaderMaterial
var material = variable.material;
var uniforms = material.uniforms;
if ( variable.dependencies !== null ) {
for ( var d = 0; d < variable.dependencies.length; d++ ) {
var depVar = variable.dependencies[ d ];
if ( depVar.name !== variable.name ) {
// Checks if variable exists
var found = false;
for ( var j = 0; j < this.variables.length; j++ ) {
if ( depVar.name === this.variables[ j ].name ) {
found = true;
break;
}
}
if ( ! found ) {
return "Variable dependency not found. Variable=" + variable.name + ", dependency=" + depVar.name;
}
}
uniforms[ depVar.name ] = { value: null };
material.fragmentShader = "\nuniform sampler2D " + depVar.name + ";\n" + material.fragmentShader;
}
}
}
this.currentTextureIndex = 0;
return null;
};
this.compute = function() {
var currentTextureIndex = this.currentTextureIndex;
var nextTextureIndex = this.currentTextureIndex === 0 ? 1 : 0;
for ( var i = 0, il = this.variables.length; i < il; i++ ) {
var variable = this.variables[ i ];
// Sets texture dependencies uniforms
if ( variable.dependencies !== null ) {
var uniforms = variable.material.uniforms;
for ( var d = 0, dl = variable.dependencies.length; d < dl; d++ ) {
var depVar = variable.dependencies[ d ];
uniforms[ depVar.name ].value = depVar.renderTargets[ currentTextureIndex ].texture;
}
}
// Performs the computation for this variable
this.doRenderTarget( variable.material, variable.renderTargets[ nextTextureIndex ] );
}
this.currentTextureIndex = nextTextureIndex;
};
this.getCurrentRenderTarget = function( variable ) {
return variable.renderTargets[ this.currentTextureIndex ];
};
this.getAlternateRenderTarget = function( variable ) {
return variable.renderTargets[ this.currentTextureIndex === 0 ? 1 : 0 ];
};
function addResolutionDefine( materialShader ) {
materialShader.defines.resolution = 'vec2( ' + sizeX.toFixed( 1 ) + ', ' + sizeY.toFixed( 1 ) + " )";
}
this.addResolutionDefine = addResolutionDefine;
// The following functions can be used to compute things manually
function createShaderMaterial( computeFragmentShader, uniforms ) {
uniforms = uniforms || {};
var material = new THREE.ShaderMaterial( {
uniforms: uniforms,
vertexShader: getPassThroughVertexShader(),
fragmentShader: computeFragmentShader
} );
addResolutionDefine( material );
return material;
}
this.createShaderMaterial = createShaderMaterial;
this.createRenderTarget = function( sizeXTexture, sizeYTexture, wrapS, wrapT, minFilter, magFilter ) {
sizeXTexture = sizeXTexture || sizeX;
sizeYTexture = sizeYTexture || sizeY;
wrapS = wrapS || THREE.ClampToEdgeWrapping;
wrapT = wrapT || THREE.ClampToEdgeWrapping;
minFilter = minFilter || THREE.NearestFilter;
magFilter = magFilter || THREE.NearestFilter;
var renderTarget = new THREE.WebGLRenderTarget( sizeXTexture, sizeYTexture, {
wrapS: wrapS,
wrapT: wrapT,
minFilter: minFilter,
magFilter: magFilter,
format: THREE.RGBAFormat,
type: ( /(iPad|iPhone|iPod)/g.test( navigator.userAgent ) ) ? THREE.HalfFloatType : THREE.FloatType,
stencilBuffer: false
} );
return renderTarget;
};
this.createTexture = function( sizeXTexture, sizeYTexture ) {
sizeXTexture = sizeXTexture || sizeX;
sizeYTexture = sizeYTexture || sizeY;
var a = new Float32Array( sizeXTexture * sizeYTexture * 4 );
var texture = new THREE.DataTexture( a, sizeX, sizeY, THREE.RGBAFormat, THREE.FloatType );
texture.needsUpdate = true;
return texture;
};
this.renderTexture = function( input, output ) {
// Takes a texture, and render out in rendertarget
// input = Texture
// output = RenderTarget
passThruUniforms.texture.value = input;
this.doRenderTarget( passThruShader, output);
passThruUniforms.texture.value = null;
};
this.doRenderTarget = function( material, output ) {
mesh.material = material;
renderer.render( scene, camera, output );
mesh.material = passThruShader;
};
// Shaders
function getPassThroughVertexShader() {
return "void main() {\n" +
"\n" +
" gl_Position = vec4( position, 1.0 );\n" +
"\n" +
"}\n";
}
function getPassThroughFragmentShader() {
return "uniform sampler2D texture;\n" +
"\n" +
"void main() {\n" +
"\n" +
" vec2 uv = gl_FragCoord.xy / resolution.xy;\n" +
"\n" +
" gl_FragColor = texture2D( texture, uv );\n" +
"\n" +
"}\n";
}
}

508
node_modules/three/examples/js/GPUParticleSystem.js generated vendored Normal file
View File

@@ -0,0 +1,508 @@
/*
* GPU Particle System
* @author flimshaw - Charlie Hoey - http://charliehoey.com
*
* A simple to use, general purpose GPU system. Particles are spawn-and-forget with
* several options available, and do not require monitoring or cleanup after spawning.
* Because the paths of all particles are completely deterministic once spawned, the scale
* and direction of time is also variable.
*
* Currently uses a static wrapping perlin noise texture for turbulence, and a small png texture for
* particles, but adding support for a particle texture atlas or changing to a different type of turbulence
* would be a fairly light day's work.
*
* Shader and javascript packing code derrived from several Stack Overflow examples.
*
*/
THREE.GPUParticleSystem = function(options) {
var self = this;
var options = options || {};
// parse options and use defaults
self.PARTICLE_COUNT = options.maxParticles || 1000000;
self.PARTICLE_CONTAINERS = options.containerCount || 1;
self.PARTICLE_NOISE_TEXTURE = options.particleNoiseTex || null;
self.PARTICLE_SPRITE_TEXTURE = options.particleSpriteTex || null;
self.PARTICLES_PER_CONTAINER = Math.ceil(self.PARTICLE_COUNT / self.PARTICLE_CONTAINERS);
self.PARTICLE_CURSOR = 0;
self.time = 0;
// Custom vertex and fragement shader
var GPUParticleShader = {
vertexShader: [
'precision highp float;',
'const vec4 bitSh = vec4(256. * 256. * 256., 256. * 256., 256., 1.);',
'const vec4 bitMsk = vec4(0.,vec3(1./256.0));',
'const vec4 bitShifts = vec4(1.) / bitSh;',
'#define FLOAT_MAX 1.70141184e38',
'#define FLOAT_MIN 1.17549435e-38',
'lowp vec4 encode_float(highp float v) {',
'highp float av = abs(v);',
'//Handle special cases',
'if(av < FLOAT_MIN) {',
'return vec4(0.0, 0.0, 0.0, 0.0);',
'} else if(v > FLOAT_MAX) {',
'return vec4(127.0, 128.0, 0.0, 0.0) / 255.0;',
'} else if(v < -FLOAT_MAX) {',
'return vec4(255.0, 128.0, 0.0, 0.0) / 255.0;',
'}',
'highp vec4 c = vec4(0,0,0,0);',
'//Compute exponent and mantissa',
'highp float e = floor(log2(av));',
'highp float m = av * pow(2.0, -e) - 1.0;',
//Unpack mantissa
'c[1] = floor(128.0 * m);',
'm -= c[1] / 128.0;',
'c[2] = floor(32768.0 * m);',
'm -= c[2] / 32768.0;',
'c[3] = floor(8388608.0 * m);',
'//Unpack exponent',
'highp float ebias = e + 127.0;',
'c[0] = floor(ebias / 2.0);',
'ebias -= c[0] * 2.0;',
'c[1] += floor(ebias) * 128.0;',
'//Unpack sign bit',
'c[0] += 128.0 * step(0.0, -v);',
'//Scale back to range',
'return c / 255.0;',
'}',
'vec4 pack(const in float depth)',
'{',
'const vec4 bit_shift = vec4(256.0*256.0*256.0, 256.0*256.0, 256.0, 1.0);',
'const vec4 bit_mask = vec4(0.0, 1.0/256.0, 1.0/256.0, 1.0/256.0);',
'vec4 res = mod(depth*bit_shift*vec4(255), vec4(256))/vec4(255);',
'res -= res.xxyz * bit_mask;',
'return res;',
'}',
'float unpack(const in vec4 rgba_depth)',
'{',
'const vec4 bit_shift = vec4(1.0/(256.0*256.0*256.0), 1.0/(256.0*256.0), 1.0/256.0, 1.0);',
'float depth = dot(rgba_depth, bit_shift);',
'return depth;',
'}',
'uniform float uTime;',
'uniform float uScale;',
'uniform sampler2D tNoise;',
'attribute vec4 particlePositionsStartTime;',
'attribute vec4 particleVelColSizeLife;',
'varying vec4 vColor;',
'varying float lifeLeft;',
'void main() {',
'// unpack things from our attributes',
'vColor = encode_float( particleVelColSizeLife.y );',
'// convert our velocity back into a value we can use',
'vec4 velTurb = encode_float( particleVelColSizeLife.x );',
'vec3 velocity = vec3( velTurb.xyz );',
'float turbulence = velTurb.w;',
'vec3 newPosition;',
'float timeElapsed = uTime - particlePositionsStartTime.a;',
'lifeLeft = 1. - (timeElapsed / particleVelColSizeLife.w);',
'gl_PointSize = ( uScale * particleVelColSizeLife.z ) * lifeLeft;',
'velocity.x = ( velocity.x - .5 ) * 3.;',
'velocity.y = ( velocity.y - .5 ) * 3.;',
'velocity.z = ( velocity.z - .5 ) * 3.;',
'newPosition = particlePositionsStartTime.xyz + ( velocity * 10. ) * ( uTime - particlePositionsStartTime.a );',
'vec3 noise = texture2D( tNoise, vec2( newPosition.x * .015 + (uTime * .05), newPosition.y * .02 + (uTime * .015) )).rgb;',
'vec3 noiseVel = ( noise.rgb - .5 ) * 30.;',
'newPosition = mix(newPosition, newPosition + vec3(noiseVel * ( turbulence * 5. ) ), (timeElapsed / particleVelColSizeLife.a) );',
'if( velocity.y > 0. && velocity.y < .05 ) {',
'lifeLeft = 0.;',
'}',
'if( velocity.x < -1.45 ) {',
'lifeLeft = 0.;',
'}',
'if( timeElapsed > 0. ) {',
'gl_Position = projectionMatrix * modelViewMatrix * vec4( newPosition, 1.0 );',
'} else {',
'gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );',
'lifeLeft = 0.;',
'gl_PointSize = 0.;',
'}',
'}'
].join("\n"),
fragmentShader: [
'float scaleLinear(float value, vec2 valueDomain) {',
'return (value - valueDomain.x) / (valueDomain.y - valueDomain.x);',
'}',
'float scaleLinear(float value, vec2 valueDomain, vec2 valueRange) {',
'return mix(valueRange.x, valueRange.y, scaleLinear(value, valueDomain));',
'}',
'varying vec4 vColor;',
'varying float lifeLeft;',
'uniform sampler2D tSprite;',
'void main() {',
'float alpha = 0.;',
'if( lifeLeft > .995 ) {',
'alpha = scaleLinear( lifeLeft, vec2(1., .995), vec2(0., 1.));//mix( 0., 1., ( lifeLeft - .95 ) * 100. ) * .75;',
'} else {',
'alpha = lifeLeft * .75;',
'}',
'vec4 tex = texture2D( tSprite, gl_PointCoord );',
'gl_FragColor = vec4( vColor.rgb * tex.a, alpha * tex.a );',
'}'
].join("\n")
};
// preload a million random numbers
self.rand = [];
for (var i = 1e5; i > 0; i--) {
self.rand.push(Math.random() - .5);
}
self.random = function() {
return ++i >= self.rand.length ? self.rand[i = 1] : self.rand[i];
};
var textureLoader = new THREE.TextureLoader();
self.particleNoiseTex = self.PARTICLE_NOISE_TEXTURE || textureLoader.load("textures/perlin-512.png");
self.particleNoiseTex.wrapS = self.particleNoiseTex.wrapT = THREE.RepeatWrapping;
self.particleSpriteTex = self.PARTICLE_SPRITE_TEXTURE || textureLoader.load("textures/particle2.png");
self.particleSpriteTex.wrapS = self.particleSpriteTex.wrapT = THREE.RepeatWrapping;
self.particleShaderMat = new THREE.ShaderMaterial({
transparent: true,
depthWrite: false,
uniforms: {
"uTime": {
value: 0.0
},
"uScale": {
value: 1.0
},
"tNoise": {
value: self.particleNoiseTex
},
"tSprite": {
value: self.particleSpriteTex
}
},
blending: THREE.AdditiveBlending,
vertexShader: GPUParticleShader.vertexShader,
fragmentShader: GPUParticleShader.fragmentShader
});
// define defaults for all values
self.particleShaderMat.defaultAttributeValues.particlePositionsStartTime = [0, 0, 0, 0];
self.particleShaderMat.defaultAttributeValues.particleVelColSizeLife = [0, 0, 0, 0];
self.particleContainers = [];
// extend Object3D
THREE.Object3D.apply(this, arguments);
this.init = function() {
for (var i = 0; i < self.PARTICLE_CONTAINERS; i++) {
var c = new THREE.GPUParticleContainer(self.PARTICLES_PER_CONTAINER, self);
self.particleContainers.push(c);
self.add(c);
}
};
this.spawnParticle = function(options) {
self.PARTICLE_CURSOR++;
if (self.PARTICLE_CURSOR >= self.PARTICLE_COUNT) {
self.PARTICLE_CURSOR = 1;
}
var currentContainer = self.particleContainers[Math.floor(self.PARTICLE_CURSOR / self.PARTICLES_PER_CONTAINER)];
currentContainer.spawnParticle(options);
};
this.update = function(time) {
for (var i = 0; i < self.PARTICLE_CONTAINERS; i++) {
self.particleContainers[i].update(time);
}
};
this.init();
};
THREE.GPUParticleSystem.prototype = Object.create(THREE.Object3D.prototype);
THREE.GPUParticleSystem.prototype.constructor = THREE.GPUParticleSystem;
// Subclass for particle containers, allows for very large arrays to be spread out
THREE.GPUParticleContainer = function(maxParticles, particleSystem) {
var self = this;
self.PARTICLE_COUNT = maxParticles || 100000;
self.PARTICLE_CURSOR = 0;
self.time = 0;
self.DPR = window.devicePixelRatio;
self.GPUParticleSystem = particleSystem;
var particlesPerArray = Math.floor(self.PARTICLE_COUNT / self.MAX_ATTRIBUTES);
// extend Object3D
THREE.Object3D.apply(this, arguments);
// construct a couple small arrays used for packing variables into floats etc
var UINT8_VIEW = new Uint8Array(4);
var FLOAT_VIEW = new Float32Array(UINT8_VIEW.buffer);
function decodeFloat(x, y, z, w) {
UINT8_VIEW[0] = Math.floor(w);
UINT8_VIEW[1] = Math.floor(z);
UINT8_VIEW[2] = Math.floor(y);
UINT8_VIEW[3] = Math.floor(x);
return FLOAT_VIEW[0]
}
function componentToHex(c) {
var hex = c.toString(16);
return hex.length == 1 ? "0" + hex : hex;
}
function rgbToHex(r, g, b) {
return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
}
function hexToRgb(hex) {
var r = hex >> 16;
var g = (hex & 0x00FF00) >> 8;
var b = hex & 0x0000FF;
if (r > 0) r--;
if (g > 0) g--;
if (b > 0) b--;
return [r, g, b];
}
self.particles = [];
self.deadParticles = [];
self.particlesAvailableSlot = [];
// create a container for particles
self.particleUpdate = false;
// Shader Based Particle System
self.particleShaderGeo = new THREE.BufferGeometry();
// new hyper compressed attributes
self.particleVertices = new Float32Array(self.PARTICLE_COUNT * 3); // position
self.particlePositionsStartTime = new Float32Array(self.PARTICLE_COUNT * 4); // position
self.particleVelColSizeLife = new Float32Array(self.PARTICLE_COUNT * 4);
for (var i = 0; i < self.PARTICLE_COUNT; i++) {
self.particlePositionsStartTime[i * 4 + 0] = 100; //x
self.particlePositionsStartTime[i * 4 + 1] = 0; //y
self.particlePositionsStartTime[i * 4 + 2] = 0.0; //z
self.particlePositionsStartTime[i * 4 + 3] = 0.0; //startTime
self.particleVertices[i * 3 + 0] = 0; //x
self.particleVertices[i * 3 + 1] = 0; //y
self.particleVertices[i * 3 + 2] = 0.0; //z
self.particleVelColSizeLife[i * 4 + 0] = decodeFloat(128, 128, 0, 0); //vel
self.particleVelColSizeLife[i * 4 + 1] = decodeFloat(0, 254, 0, 254); //color
self.particleVelColSizeLife[i * 4 + 2] = 1.0; //size
self.particleVelColSizeLife[i * 4 + 3] = 0.0; //lifespan
}
self.particleShaderGeo.addAttribute('position', new THREE.BufferAttribute(self.particleVertices, 3));
self.particleShaderGeo.addAttribute('particlePositionsStartTime', new THREE.BufferAttribute(self.particlePositionsStartTime, 4).setDynamic(true));
self.particleShaderGeo.addAttribute('particleVelColSizeLife', new THREE.BufferAttribute(self.particleVelColSizeLife, 4).setDynamic(true));
self.posStart = self.particleShaderGeo.getAttribute('particlePositionsStartTime');
self.velCol = self.particleShaderGeo.getAttribute('particleVelColSizeLife');
self.particleShaderMat = self.GPUParticleSystem.particleShaderMat;
this.init = function() {
self.particleSystem = new THREE.Points(self.particleShaderGeo, self.particleShaderMat);
self.particleSystem.frustumCulled = false;
this.add(self.particleSystem);
};
var options = {},
position = new THREE.Vector3(),
velocity = new THREE.Vector3(),
positionRandomness = 0.,
velocityRandomness = 0.,
color = 0xffffff,
colorRandomness = 0.,
turbulence = 0.,
lifetime = 0.,
size = 0.,
sizeRandomness = 0.,
smoothPosition = false,
i;
var maxVel = 2;
var maxSource = 250;
this.offset = 0;
this.count = 0;
this.spawnParticle = function(options) {
options = options || {};
// setup reasonable default values for all arguments
position = options.position !== undefined ? position.copy(options.position) : position.set(0., 0., 0.);
velocity = options.velocity !== undefined ? velocity.copy(options.velocity) : velocity.set(0., 0., 0.);
positionRandomness = options.positionRandomness !== undefined ? options.positionRandomness : 0.0;
velocityRandomness = options.velocityRandomness !== undefined ? options.velocityRandomness : 0.0;
color = options.color !== undefined ? options.color : 0xffffff;
colorRandomness = options.colorRandomness !== undefined ? options.colorRandomness : 1.0;
turbulence = options.turbulence !== undefined ? options.turbulence : 1.0;
lifetime = options.lifetime !== undefined ? options.lifetime : 5.0;
size = options.size !== undefined ? options.size : 10;
sizeRandomness = options.sizeRandomness !== undefined ? options.sizeRandomness : 0.0;
smoothPosition = options.smoothPosition !== undefined ? options.smoothPosition : false;
if (self.DPR !== undefined) size *= self.DPR;
i = self.PARTICLE_CURSOR;
self.posStart.array[i * 4 + 0] = position.x + ((particleSystem.random()) * positionRandomness); // - ( velocity.x * particleSystem.random() ); //x
self.posStart.array[i * 4 + 1] = position.y + ((particleSystem.random()) * positionRandomness); // - ( velocity.y * particleSystem.random() ); //y
self.posStart.array[i * 4 + 2] = position.z + ((particleSystem.random()) * positionRandomness); // - ( velocity.z * particleSystem.random() ); //z
self.posStart.array[i * 4 + 3] = self.time + (particleSystem.random() * 2e-2); //startTime
if (smoothPosition === true) {
self.posStart.array[i * 4 + 0] += -(velocity.x * particleSystem.random()); //x
self.posStart.array[i * 4 + 1] += -(velocity.y * particleSystem.random()); //y
self.posStart.array[i * 4 + 2] += -(velocity.z * particleSystem.random()); //z
}
var velX = velocity.x + (particleSystem.random()) * velocityRandomness;
var velY = velocity.y + (particleSystem.random()) * velocityRandomness;
var velZ = velocity.z + (particleSystem.random()) * velocityRandomness;
// convert turbulence rating to something we can pack into a vec4
var turbulence = Math.floor(turbulence * 254);
// clamp our value to between 0. and 1.
velX = Math.floor(maxSource * ((velX - -maxVel) / (maxVel - -maxVel)));
velY = Math.floor(maxSource * ((velY - -maxVel) / (maxVel - -maxVel)));
velZ = Math.floor(maxSource * ((velZ - -maxVel) / (maxVel - -maxVel)));
self.velCol.array[i * 4 + 0] = decodeFloat(velX, velY, velZ, turbulence); //vel
var rgb = hexToRgb(color);
for (var c = 0; c < rgb.length; c++) {
rgb[c] = Math.floor(rgb[c] + ((particleSystem.random()) * colorRandomness) * 254);
if (rgb[c] > 254) rgb[c] = 254;
if (rgb[c] < 0) rgb[c] = 0;
}
self.velCol.array[i * 4 + 1] = decodeFloat(rgb[0], rgb[1], rgb[2], 254); //color
self.velCol.array[i * 4 + 2] = size + (particleSystem.random()) * sizeRandomness; //size
self.velCol.array[i * 4 + 3] = lifetime; //lifespan
if (this.offset == 0) {
this.offset = self.PARTICLE_CURSOR;
}
self.count++;
self.PARTICLE_CURSOR++;
if (self.PARTICLE_CURSOR >= self.PARTICLE_COUNT) {
self.PARTICLE_CURSOR = 0;
}
self.particleUpdate = true;
};
this.update = function(time) {
self.time = time;
self.particleShaderMat.uniforms['uTime'].value = time;
this.geometryUpdate();
};
this.geometryUpdate = function() {
if (self.particleUpdate == true) {
self.particleUpdate = false;
// if we can get away with a partial buffer update, do so
if (self.offset + self.count < self.PARTICLE_COUNT) {
self.posStart.updateRange.offset = self.velCol.updateRange.offset = self.offset * 4;
self.posStart.updateRange.count = self.velCol.updateRange.count = self.count * 4;
} else {
self.posStart.updateRange.offset = 0;
self.posStart.updateRange.count = self.velCol.updateRange.count = (self.PARTICLE_COUNT * 4);
}
self.posStart.needsUpdate = true;
self.velCol.needsUpdate = true;
self.offset = 0;
self.count = 0;
}
};
this.init();
};
THREE.GPUParticleContainer.prototype = Object.create(THREE.Object3D.prototype);
THREE.GPUParticleContainer.prototype.constructor = THREE.GPUParticleContainer;

65
node_modules/three/examples/js/Gyroscope.js generated vendored Normal file
View File

@@ -0,0 +1,65 @@
/**
* @author alteredq / http://alteredqualia.com/
*/
THREE.Gyroscope = function () {
THREE.Object3D.call( this );
};
THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype );
THREE.Gyroscope.prototype.constructor = THREE.Gyroscope;
THREE.Gyroscope.prototype.updateMatrixWorld = ( function () {
var translationObject = new THREE.Vector3();
var quaternionObject = new THREE.Quaternion();
var scaleObject = new THREE.Vector3();
var translationWorld = new THREE.Vector3();
var quaternionWorld = new THREE.Quaternion();
var scaleWorld = new THREE.Vector3();
return function updateMatrixWorld( force ) {
this.matrixAutoUpdate && this.updateMatrix();
// update matrixWorld
if ( this.matrixWorldNeedsUpdate || force ) {
if ( this.parent !== null ) {
this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
this.matrixWorld.decompose( translationWorld, quaternionWorld, scaleWorld );
this.matrix.decompose( translationObject, quaternionObject, scaleObject );
this.matrixWorld.compose( translationWorld, quaternionObject, scaleWorld );
} else {
this.matrixWorld.copy( this.matrix );
}
this.matrixWorldNeedsUpdate = false;
force = true;
}
// update children
for ( var i = 0, l = this.children.length; i < l; i ++ ) {
this.children[ i ].updateMatrixWorld( force );
}
};
}() );

71
node_modules/three/examples/js/ImprovedNoise.js generated vendored Normal file
View File

@@ -0,0 +1,71 @@
// http://mrl.nyu.edu/~perlin/noise/
var ImprovedNoise = function () {
var p = [ 151,160,137,91,90,15,131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,
23,190,6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,88,237,149,56,87,
174,20,125,136,171,168,68,175,74,165,71,134,139,48,27,166,77,146,158,231,83,111,229,122,60,211,
133,230,220,105,92,41,55,46,245,40,244,102,143,54,65,25,63,161,1,216,80,73,209,76,132,187,208,
89,18,169,200,196,135,130,116,188,159,86,164,100,109,198,173,186,3,64,52,217,226,250,124,123,5,
202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,223,183,170,213,119,
248,152,2,44,154,163,70,221,153,101,155,167,43,172,9,129,22,39,253,19,98,108,110,79,113,224,232,
178,185,112,104,218,246,97,228,251,34,242,193,238,210,144,12,191,179,162,241,81,51,145,235,249,
14,239,107,49,192,214,31,181,199,106,157,184,84,204,176,115,121,50,45,127,4,150,254,138,236,205,
93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180 ];
for (var i = 0; i < 256 ; i ++) {
p[256 + i] = p[i];
}
function fade(t) {
return t * t * t * (t * (t * 6 - 15) + 10);
}
function lerp(t, a, b) {
return a + t * (b - a);
}
function grad(hash, x, y, z) {
var h = hash & 15;
var u = h < 8 ? x : y, v = h < 4 ? y : h == 12 || h == 14 ? x : z;
return ((h&1) == 0 ? u : -u) + ((h&2) == 0 ? v : -v);
}
return {
noise: function (x, y, z) {
var floorX = Math.floor(x), floorY = Math.floor(y), floorZ = Math.floor(z);
var X = floorX & 255, Y = floorY & 255, Z = floorZ & 255;
x -= floorX;
y -= floorY;
z -= floorZ;
var xMinus1 = x - 1, yMinus1 = y - 1, zMinus1 = z - 1;
var u = fade(x), v = fade(y), w = fade(z);
var A = p[X] + Y, AA = p[A] + Z, AB = p[A + 1] + Z, B = p[X + 1] + Y, BA = p[B] + Z, BB = p[B + 1] + Z;
return lerp(w, lerp(v, lerp(u, grad(p[AA], x, y, z),
grad(p[BA], xMinus1, y, z)),
lerp(u, grad(p[AB], x, yMinus1, z),
grad(p[BB], xMinus1, yMinus1, z))),
lerp(v, lerp(u, grad(p[AA + 1], x, y, zMinus1),
grad(p[BA + 1], xMinus1, y, z - 1)),
lerp(u, grad(p[AB + 1], x, yMinus1, zMinus1),
grad(p[BB + 1], xMinus1, yMinus1, zMinus1))));
}
}
};

254
node_modules/three/examples/js/MD2Character.js generated vendored Normal file
View File

@@ -0,0 +1,254 @@
/**
* @author alteredq / http://alteredqualia.com/
*/
THREE.MD2Character = function () {
var scope = this;
this.scale = 1;
this.animationFPS = 6;
this.root = new THREE.Object3D();
this.meshBody = null;
this.meshWeapon = null;
this.skinsBody = [];
this.skinsWeapon = [];
this.weapons = [];
this.activeAnimation = null;
this.mixer = null;
this.onLoadComplete = function () {};
this.loadCounter = 0;
this.loadParts = function ( config ) {
this.loadCounter = config.weapons.length * 2 + config.skins.length + 1;
var weaponsTextures = [];
for ( var i = 0; i < config.weapons.length; i ++ ) weaponsTextures[ i ] = config.weapons[ i ][ 1 ];
// SKINS
this.skinsBody = loadTextures( config.baseUrl + "skins/", config.skins );
this.skinsWeapon = loadTextures( config.baseUrl + "skins/", weaponsTextures );
// BODY
var loader = new THREE.MD2Loader();
loader.load( config.baseUrl + config.body, function( geo ) {
geo.computeBoundingBox();
scope.root.position.y = - scope.scale * geo.boundingBox.min.y;
var mesh = createPart( geo, scope.skinsBody[ 0 ] );
mesh.scale.set( scope.scale, scope.scale, scope.scale );
scope.root.add( mesh );
scope.meshBody = mesh;
scope.meshBody.clipOffset = 0;
scope.activeAnimationClipName = mesh.geometry.animations[0].name;
scope.mixer = new THREE.AnimationMixer( mesh );
checkLoadingComplete();
} );
// WEAPONS
var generateCallback = function ( index, name ) {
return function( geo ) {
var mesh = createPart( geo, scope.skinsWeapon[ index ] );
mesh.scale.set( scope.scale, scope.scale, scope.scale );
mesh.visible = false;
mesh.name = name;
scope.root.add( mesh );
scope.weapons[ index ] = mesh;
scope.meshWeapon = mesh;
checkLoadingComplete();
}
};
for ( var i = 0; i < config.weapons.length; i ++ ) {
loader.load( config.baseUrl + config.weapons[ i ][ 0 ], generateCallback( i, config.weapons[ i ][ 0 ] ) );
}
};
this.setPlaybackRate = function ( rate ) {
if( rate !== 0 ) {
this.mixer.timeScale = 1 / rate;
}
else {
this.mixer.timeScale = 0;
}
};
this.setWireframe = function ( wireframeEnabled ) {
if ( wireframeEnabled ) {
if ( this.meshBody ) this.meshBody.material = this.meshBody.materialWireframe;
if ( this.meshWeapon ) this.meshWeapon.material = this.meshWeapon.materialWireframe;
} else {
if ( this.meshBody ) this.meshBody.material = this.meshBody.materialTexture;
if ( this.meshWeapon ) this.meshWeapon.material = this.meshWeapon.materialTexture;
}
};
this.setSkin = function( index ) {
if ( this.meshBody && this.meshBody.material.wireframe === false ) {
this.meshBody.material.map = this.skinsBody[ index ];
}
};
this.setWeapon = function ( index ) {
for ( var i = 0; i < this.weapons.length; i ++ ) this.weapons[ i ].visible = false;
var activeWeapon = this.weapons[ index ];
if ( activeWeapon ) {
activeWeapon.visible = true;
this.meshWeapon = activeWeapon;
scope.syncWeaponAnimation();
}
};
this.setAnimation = function ( clipName ) {
if ( this.meshBody ) {
if( this.meshBody.activeAction ) {
this.meshBody.activeAction.stop();
this.meshBody.activeAction = null;
}
var action = this.mixer.clipAction( clipName, this.meshBody );
if( action ) {
this.meshBody.activeAction = action.play();
}
}
scope.activeClipName = clipName;
scope.syncWeaponAnimation();
};
this.syncWeaponAnimation = function() {
var clipName = scope.activeClipName;
if ( scope.meshWeapon ) {
if( this.meshWeapon.activeAction ) {
this.meshWeapon.activeAction.stop();
this.meshWeapon.activeAction = null;
}
var geometry = this.meshWeapon.geometry,
animations = geometry.animations;
var action = this.mixer.clipAction( clipName, this.meshWeapon );
if( action ) {
this.meshWeapon.activeAction =
action.syncWith( this.meshBody.activeAction ).play();
}
}
}
this.update = function ( delta ) {
if( this.mixer ) this.mixer.update( delta );
};
function loadTextures( baseUrl, textureUrls ) {
var textureLoader = new THREE.TextureLoader();
var textures = [];
for ( var i = 0; i < textureUrls.length; i ++ ) {
textures[ i ] = textureLoader.load( baseUrl + textureUrls[ i ], checkLoadingComplete );
textures[ i ].mapping = THREE.UVMapping;
textures[ i ].name = textureUrls[ i ];
}
return textures;
}
function createPart( geometry, skinMap ) {
var materialWireframe = new THREE.MeshLambertMaterial( { color: 0xffaa00, wireframe: true, morphTargets: true, morphNormals: true } );
var materialTexture = new THREE.MeshLambertMaterial( { color: 0xffffff, wireframe: false, map: skinMap, morphTargets: true, morphNormals: true } );
//
var mesh = new THREE.Mesh( geometry, materialTexture );
mesh.rotation.y = - Math.PI / 2;
mesh.castShadow = true;
mesh.receiveShadow = true;
//
mesh.materialTexture = materialTexture;
mesh.materialWireframe = materialWireframe;
return mesh;
}
function checkLoadingComplete() {
scope.loadCounter -= 1;
if ( scope.loadCounter === 0 ) scope.onLoadComplete();
}
};

560
node_modules/three/examples/js/MD2CharacterComplex.js generated vendored Normal file
View File

@@ -0,0 +1,560 @@
/**
* @author alteredq / http://alteredqualia.com/
*/
THREE.MD2CharacterComplex = function () {
var scope = this;
this.scale = 1;
// animation parameters
this.animationFPS = 6;
this.transitionFrames = 15;
// movement model parameters
this.maxSpeed = 275;
this.maxReverseSpeed = - 275;
this.frontAcceleration = 600;
this.backAcceleration = 600;
this.frontDecceleration = 600;
this.angularSpeed = 2.5;
// rig
this.root = new THREE.Object3D();
this.meshBody = null;
this.meshWeapon = null;
this.controls = null;
// skins
this.skinsBody = [];
this.skinsWeapon = [];
this.weapons = [];
this.currentSkin = undefined;
//
this.onLoadComplete = function () {};
// internals
this.meshes = [];
this.animations = {};
this.loadCounter = 0;
// internal movement control variables
this.speed = 0;
this.bodyOrientation = 0;
this.walkSpeed = this.maxSpeed;
this.crouchSpeed = this.maxSpeed * 0.5;
// internal animation parameters
this.activeAnimation = null;
this.oldAnimation = null;
// API
this.enableShadows = function ( enable ) {
for ( var i = 0; i < this.meshes.length; i ++ ) {
this.meshes[ i ].castShadow = enable;
this.meshes[ i ].receiveShadow = enable;
}
};
this.setVisible = function ( enable ) {
for ( var i = 0; i < this.meshes.length; i ++ ) {
this.meshes[ i ].visible = enable;
this.meshes[ i ].visible = enable;
}
};
this.shareParts = function ( original ) {
this.animations = original.animations;
this.walkSpeed = original.walkSpeed;
this.crouchSpeed = original.crouchSpeed;
this.skinsBody = original.skinsBody;
this.skinsWeapon = original.skinsWeapon;
// BODY
var mesh = createPart( original.meshBody.geometry, this.skinsBody[ 0 ] );
mesh.scale.set( this.scale, this.scale, this.scale );
this.root.position.y = original.root.position.y;
this.root.add( mesh );
this.meshBody = mesh;
this.meshes.push( mesh );
// WEAPONS
for ( var i = 0; i < original.weapons.length; i ++ ) {
var meshWeapon = createPart( original.weapons[ i ].geometry, this.skinsWeapon[ i ] );
meshWeapon.scale.set( this.scale, this.scale, this.scale );
meshWeapon.visible = false;
meshWeapon.name = original.weapons[ i ].name;
this.root.add( meshWeapon );
this.weapons[ i ] = meshWeapon;
this.meshWeapon = meshWeapon;
this.meshes.push( meshWeapon );
}
};
this.loadParts = function ( config ) {
this.animations = config.animations;
this.walkSpeed = config.walkSpeed;
this.crouchSpeed = config.crouchSpeed;
this.loadCounter = config.weapons.length * 2 + config.skins.length + 1;
var weaponsTextures = [];
for ( var i = 0; i < config.weapons.length; i ++ ) weaponsTextures[ i ] = config.weapons[ i ][ 1 ];
// SKINS
this.skinsBody = loadTextures( config.baseUrl + "skins/", config.skins );
this.skinsWeapon = loadTextures( config.baseUrl + "skins/", weaponsTextures );
// BODY
var loader = new THREE.MD2Loader();
loader.load( config.baseUrl + config.body, function( geo ) {
geo.computeBoundingBox();
scope.root.position.y = - scope.scale * geo.boundingBox.min.y;
var mesh = createPart( geo, scope.skinsBody[ 0 ] );
mesh.scale.set( scope.scale, scope.scale, scope.scale );
scope.root.add( mesh );
scope.meshBody = mesh;
scope.meshes.push( mesh );
checkLoadingComplete();
} );
// WEAPONS
var generateCallback = function ( index, name ) {
return function( geo ) {
var mesh = createPart( geo, scope.skinsWeapon[ index ] );
mesh.scale.set( scope.scale, scope.scale, scope.scale );
mesh.visible = false;
mesh.name = name;
scope.root.add( mesh );
scope.weapons[ index ] = mesh;
scope.meshWeapon = mesh;
scope.meshes.push( mesh );
checkLoadingComplete();
}
};
for ( var i = 0; i < config.weapons.length; i ++ ) {
loader.load( config.baseUrl + config.weapons[ i ][ 0 ], generateCallback( i, config.weapons[ i ][ 0 ] ) );
}
};
this.setPlaybackRate = function ( rate ) {
if ( this.meshBody ) this.meshBody.duration = this.meshBody.baseDuration / rate;
if ( this.meshWeapon ) this.meshWeapon.duration = this.meshWeapon.baseDuration / rate;
};
this.setWireframe = function ( wireframeEnabled ) {
if ( wireframeEnabled ) {
if ( this.meshBody ) this.meshBody.material = this.meshBody.materialWireframe;
if ( this.meshWeapon ) this.meshWeapon.material = this.meshWeapon.materialWireframe;
} else {
if ( this.meshBody ) this.meshBody.material = this.meshBody.materialTexture;
if ( this.meshWeapon ) this.meshWeapon.material = this.meshWeapon.materialTexture;
}
};
this.setSkin = function( index ) {
if ( this.meshBody && this.meshBody.material.wireframe === false ) {
this.meshBody.material.map = this.skinsBody[ index ];
this.currentSkin = index;
}
};
this.setWeapon = function ( index ) {
for ( var i = 0; i < this.weapons.length; i ++ ) this.weapons[ i ].visible = false;
var activeWeapon = this.weapons[ index ];
if ( activeWeapon ) {
activeWeapon.visible = true;
this.meshWeapon = activeWeapon;
if ( this.activeAnimation ) {
activeWeapon.playAnimation( this.activeAnimation );
this.meshWeapon.setAnimationTime( this.activeAnimation, this.meshBody.getAnimationTime( this.activeAnimation ) );
}
}
};
this.setAnimation = function ( animationName ) {
if ( animationName === this.activeAnimation || ! animationName ) return;
if ( this.meshBody ) {
this.meshBody.setAnimationWeight( animationName, 0 );
this.meshBody.playAnimation( animationName );
this.oldAnimation = this.activeAnimation;
this.activeAnimation = animationName;
this.blendCounter = this.transitionFrames;
}
if ( this.meshWeapon ) {
this.meshWeapon.setAnimationWeight( animationName, 0 );
this.meshWeapon.playAnimation( animationName );
}
};
this.update = function ( delta ) {
if ( this.controls ) this.updateMovementModel( delta );
if ( this.animations ) {
this.updateBehaviors( delta );
this.updateAnimations( delta );
}
};
this.updateAnimations = function ( delta ) {
var mix = 1;
if ( this.blendCounter > 0 ) {
mix = ( this.transitionFrames - this.blendCounter ) / this.transitionFrames;
this.blendCounter -= 1;
}
if ( this.meshBody ) {
this.meshBody.update( delta );
this.meshBody.setAnimationWeight( this.activeAnimation, mix );
this.meshBody.setAnimationWeight( this.oldAnimation, 1 - mix );
}
if ( this.meshWeapon ) {
this.meshWeapon.update( delta );
this.meshWeapon.setAnimationWeight( this.activeAnimation, mix );
this.meshWeapon.setAnimationWeight( this.oldAnimation, 1 - mix );
}
};
this.updateBehaviors = function ( delta ) {
var controls = this.controls;
var animations = this.animations;
var moveAnimation, idleAnimation;
// crouch vs stand
if ( controls.crouch ) {
moveAnimation = animations[ "crouchMove" ];
idleAnimation = animations[ "crouchIdle" ];
} else {
moveAnimation = animations[ "move" ];
idleAnimation = animations[ "idle" ];
}
// actions
if ( controls.jump ) {
moveAnimation = animations[ "jump" ];
idleAnimation = animations[ "jump" ];
}
if ( controls.attack ) {
if ( controls.crouch ) {
moveAnimation = animations[ "crouchAttack" ];
idleAnimation = animations[ "crouchAttack" ];
} else {
moveAnimation = animations[ "attack" ];
idleAnimation = animations[ "attack" ];
}
}
// set animations
if ( controls.moveForward || controls.moveBackward || controls.moveLeft || controls.moveRight ) {
if ( this.activeAnimation !== moveAnimation ) {
this.setAnimation( moveAnimation );
}
}
if ( Math.abs( this.speed ) < 0.2 * this.maxSpeed && ! ( controls.moveLeft || controls.moveRight || controls.moveForward || controls.moveBackward ) ) {
if ( this.activeAnimation !== idleAnimation ) {
this.setAnimation( idleAnimation );
}
}
// set animation direction
if ( controls.moveForward ) {
if ( this.meshBody ) {
this.meshBody.setAnimationDirectionForward( this.activeAnimation );
this.meshBody.setAnimationDirectionForward( this.oldAnimation );
}
if ( this.meshWeapon ) {
this.meshWeapon.setAnimationDirectionForward( this.activeAnimation );
this.meshWeapon.setAnimationDirectionForward( this.oldAnimation );
}
}
if ( controls.moveBackward ) {
if ( this.meshBody ) {
this.meshBody.setAnimationDirectionBackward( this.activeAnimation );
this.meshBody.setAnimationDirectionBackward( this.oldAnimation );
}
if ( this.meshWeapon ) {
this.meshWeapon.setAnimationDirectionBackward( this.activeAnimation );
this.meshWeapon.setAnimationDirectionBackward( this.oldAnimation );
}
}
};
this.updateMovementModel = function ( delta ) {
var controls = this.controls;
// speed based on controls
if ( controls.crouch ) this.maxSpeed = this.crouchSpeed;
else this.maxSpeed = this.walkSpeed;
this.maxReverseSpeed = - this.maxSpeed;
if ( controls.moveForward ) this.speed = THREE.Math.clamp( this.speed + delta * this.frontAcceleration, this.maxReverseSpeed, this.maxSpeed );
if ( controls.moveBackward ) this.speed = THREE.Math.clamp( this.speed - delta * this.backAcceleration, this.maxReverseSpeed, this.maxSpeed );
// orientation based on controls
// (don't just stand while turning)
var dir = 1;
if ( controls.moveLeft ) {
this.bodyOrientation += delta * this.angularSpeed;
this.speed = THREE.Math.clamp( this.speed + dir * delta * this.frontAcceleration, this.maxReverseSpeed, this.maxSpeed );
}
if ( controls.moveRight ) {
this.bodyOrientation -= delta * this.angularSpeed;
this.speed = THREE.Math.clamp( this.speed + dir * delta * this.frontAcceleration, this.maxReverseSpeed, this.maxSpeed );
}
// speed decay
if ( ! ( controls.moveForward || controls.moveBackward ) ) {
if ( this.speed > 0 ) {
var k = exponentialEaseOut( this.speed / this.maxSpeed );
this.speed = THREE.Math.clamp( this.speed - k * delta * this.frontDecceleration, 0, this.maxSpeed );
} else {
var k = exponentialEaseOut( this.speed / this.maxReverseSpeed );
this.speed = THREE.Math.clamp( this.speed + k * delta * this.backAcceleration, this.maxReverseSpeed, 0 );
}
}
// displacement
var forwardDelta = this.speed * delta;
this.root.position.x += Math.sin( this.bodyOrientation ) * forwardDelta;
this.root.position.z += Math.cos( this.bodyOrientation ) * forwardDelta;
// steering
this.root.rotation.y = this.bodyOrientation;
};
// internal helpers
function loadTextures( baseUrl, textureUrls ) {
var textureLoader = new THREE.TextureLoader();
var textures = [];
for ( var i = 0; i < textureUrls.length; i ++ ) {
textures[ i ] = textureLoader.load( baseUrl + textureUrls[ i ], checkLoadingComplete );
textures[ i ].mapping = THREE.UVMapping;
textures[ i ].name = textureUrls[ i ];
}
return textures;
}
function createPart( geometry, skinMap ) {
var materialWireframe = new THREE.MeshLambertMaterial( { color: 0xffaa00, wireframe: true, morphTargets: true, morphNormals: true } );
var materialTexture = new THREE.MeshLambertMaterial( { color: 0xffffff, wireframe: false, map: skinMap, morphTargets: true, morphNormals: true } );
//
var mesh = new THREE.MorphBlendMesh( geometry, materialTexture );
mesh.rotation.y = - Math.PI / 2;
//
mesh.materialTexture = materialTexture;
mesh.materialWireframe = materialWireframe;
//
mesh.autoCreateAnimations( scope.animationFPS );
return mesh;
}
function checkLoadingComplete() {
scope.loadCounter -= 1;
if ( scope.loadCounter === 0 ) scope.onLoadComplete();
}
function exponentialEaseOut( k ) {
return k === 1 ? 1 : - Math.pow( 2, - 10 * k ) + 1;
}
};

1044
node_modules/three/examples/js/MarchingCubes.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

302
node_modules/three/examples/js/Mirror.js generated vendored Normal file
View File

@@ -0,0 +1,302 @@
/**
* @author Slayvin / http://slayvin.net
*/
THREE.ShaderLib[ 'mirror' ] = {
uniforms: {
"mirrorColor": { value: new THREE.Color( 0x7F7F7F ) },
"mirrorSampler": { value: null },
"textureMatrix" : { value: new THREE.Matrix4() }
},
vertexShader: [
"uniform mat4 textureMatrix;",
"varying vec4 mirrorCoord;",
"void main() {",
"vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
"vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
"mirrorCoord = textureMatrix * worldPosition;",
"gl_Position = projectionMatrix * mvPosition;",
"}"
].join( "\n" ),
fragmentShader: [
"uniform vec3 mirrorColor;",
"uniform sampler2D mirrorSampler;",
"varying vec4 mirrorCoord;",
"float blendOverlay(float base, float blend) {",
"return( base < 0.5 ? ( 2.0 * base * blend ) : (1.0 - 2.0 * ( 1.0 - base ) * ( 1.0 - blend ) ) );",
"}",
"void main() {",
"vec4 color = texture2DProj(mirrorSampler, mirrorCoord);",
"color = vec4(blendOverlay(mirrorColor.r, color.r), blendOverlay(mirrorColor.g, color.g), blendOverlay(mirrorColor.b, color.b), 1.0);",
"gl_FragColor = color;",
"}"
].join( "\n" )
};
THREE.Mirror = function ( renderer, camera, options ) {
THREE.Object3D.call( this );
this.name = 'mirror_' + this.id;
options = options || {};
this.matrixNeedsUpdate = true;
var width = options.textureWidth !== undefined ? options.textureWidth : 512;
var height = options.textureHeight !== undefined ? options.textureHeight : 512;
this.clipBias = options.clipBias !== undefined ? options.clipBias : 0.0;
var mirrorColor = options.color !== undefined ? new THREE.Color( options.color ) : new THREE.Color( 0x7F7F7F );
this.renderer = renderer;
this.mirrorPlane = new THREE.Plane();
this.normal = new THREE.Vector3( 0, 0, 1 );
this.mirrorWorldPosition = new THREE.Vector3();
this.cameraWorldPosition = new THREE.Vector3();
this.rotationMatrix = new THREE.Matrix4();
this.lookAtPosition = new THREE.Vector3( 0, 0, - 1 );
this.clipPlane = new THREE.Vector4();
// For debug only, show the normal and plane of the mirror
var debugMode = options.debugMode !== undefined ? options.debugMode : false;
if ( debugMode ) {
var arrow = new THREE.ArrowHelper( new THREE.Vector3( 0, 0, 1 ), new THREE.Vector3( 0, 0, 0 ), 10, 0xffff80 );
var planeGeometry = new THREE.Geometry();
planeGeometry.vertices.push( new THREE.Vector3( - 10, - 10, 0 ) );
planeGeometry.vertices.push( new THREE.Vector3( 10, - 10, 0 ) );
planeGeometry.vertices.push( new THREE.Vector3( 10, 10, 0 ) );
planeGeometry.vertices.push( new THREE.Vector3( - 10, 10, 0 ) );
planeGeometry.vertices.push( planeGeometry.vertices[ 0 ] );
var plane = new THREE.Line( planeGeometry, new THREE.LineBasicMaterial( { color: 0xffff80 } ) );
this.add( arrow );
this.add( plane );
}
if ( camera instanceof THREE.PerspectiveCamera ) {
this.camera = camera;
} else {
this.camera = new THREE.PerspectiveCamera();
console.log( this.name + ': camera is not a Perspective Camera!' );
}
this.textureMatrix = new THREE.Matrix4();
this.mirrorCamera = this.camera.clone();
this.mirrorCamera.matrixAutoUpdate = true;
var parameters = { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBFormat, stencilBuffer: false };
this.renderTarget = new THREE.WebGLRenderTarget( width, height, parameters );
this.renderTarget2 = new THREE.WebGLRenderTarget( width, height, parameters );
var mirrorShader = THREE.ShaderLib[ "mirror" ];
var mirrorUniforms = THREE.UniformsUtils.clone( mirrorShader.uniforms );
this.material = new THREE.ShaderMaterial( {
fragmentShader: mirrorShader.fragmentShader,
vertexShader: mirrorShader.vertexShader,
uniforms: mirrorUniforms
} );
this.material.uniforms.mirrorSampler.value = this.renderTarget.texture;
this.material.uniforms.mirrorColor.value = mirrorColor;
this.material.uniforms.textureMatrix.value = this.textureMatrix;
if ( ! THREE.Math.isPowerOfTwo( width ) || ! THREE.Math.isPowerOfTwo( height ) ) {
this.renderTarget.texture.generateMipmaps = false;
this.renderTarget2.texture.generateMipmaps = false;
}
this.updateTextureMatrix();
this.render();
};
THREE.Mirror.prototype = Object.create( THREE.Object3D.prototype );
THREE.Mirror.prototype.constructor = THREE.Mirror;
THREE.Mirror.prototype.renderWithMirror = function ( otherMirror ) {
// update the mirror matrix to mirror the current view
this.updateTextureMatrix();
this.matrixNeedsUpdate = false;
// set the camera of the other mirror so the mirrored view is the reference view
var tempCamera = otherMirror.camera;
otherMirror.camera = this.mirrorCamera;
// render the other mirror in temp texture
otherMirror.renderTemp();
otherMirror.material.uniforms.mirrorSampler.value = otherMirror.renderTarget2.texture;
// render the current mirror
this.render();
this.matrixNeedsUpdate = true;
// restore material and camera of other mirror
otherMirror.material.uniforms.mirrorSampler.value = otherMirror.renderTarget.texture;
otherMirror.camera = tempCamera;
// restore texture matrix of other mirror
otherMirror.updateTextureMatrix();
};
THREE.Mirror.prototype.updateTextureMatrix = function () {
this.updateMatrixWorld();
this.camera.updateMatrixWorld();
this.mirrorWorldPosition.setFromMatrixPosition( this.matrixWorld );
this.cameraWorldPosition.setFromMatrixPosition( this.camera.matrixWorld );
this.rotationMatrix.extractRotation( this.matrixWorld );
this.normal.set( 0, 0, 1 );
this.normal.applyMatrix4( this.rotationMatrix );
var view = this.mirrorWorldPosition.clone().sub( this.cameraWorldPosition );
view.reflect( this.normal ).negate();
view.add( this.mirrorWorldPosition );
this.rotationMatrix.extractRotation( this.camera.matrixWorld );
this.lookAtPosition.set( 0, 0, - 1 );
this.lookAtPosition.applyMatrix4( this.rotationMatrix );
this.lookAtPosition.add( this.cameraWorldPosition );
var target = this.mirrorWorldPosition.clone().sub( this.lookAtPosition );
target.reflect( this.normal ).negate();
target.add( this.mirrorWorldPosition );
this.up.set( 0, - 1, 0 );
this.up.applyMatrix4( this.rotationMatrix );
this.up.reflect( this.normal ).negate();
this.mirrorCamera.position.copy( view );
this.mirrorCamera.up = this.up;
this.mirrorCamera.lookAt( target );
this.mirrorCamera.updateProjectionMatrix();
this.mirrorCamera.updateMatrixWorld();
this.mirrorCamera.matrixWorldInverse.getInverse( this.mirrorCamera.matrixWorld );
// Update the texture matrix
this.textureMatrix.set( 0.5, 0.0, 0.0, 0.5,
0.0, 0.5, 0.0, 0.5,
0.0, 0.0, 0.5, 0.5,
0.0, 0.0, 0.0, 1.0 );
this.textureMatrix.multiply( this.mirrorCamera.projectionMatrix );
this.textureMatrix.multiply( this.mirrorCamera.matrixWorldInverse );
// Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
// Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
this.mirrorPlane.setFromNormalAndCoplanarPoint( this.normal, this.mirrorWorldPosition );
this.mirrorPlane.applyMatrix4( this.mirrorCamera.matrixWorldInverse );
this.clipPlane.set( this.mirrorPlane.normal.x, this.mirrorPlane.normal.y, this.mirrorPlane.normal.z, this.mirrorPlane.constant );
var q = new THREE.Vector4();
var projectionMatrix = this.mirrorCamera.projectionMatrix;
q.x = ( Math.sign( this.clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
q.y = ( Math.sign( this.clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
q.z = - 1.0;
q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
// Calculate the scaled plane vector
var c = new THREE.Vector4();
c = this.clipPlane.multiplyScalar( 2.0 / this.clipPlane.dot( q ) );
// Replacing the third row of the projection matrix
projectionMatrix.elements[ 2 ] = c.x;
projectionMatrix.elements[ 6 ] = c.y;
projectionMatrix.elements[ 10 ] = c.z + 1.0 - this.clipBias;
projectionMatrix.elements[ 14 ] = c.w;
};
THREE.Mirror.prototype.render = function () {
if ( this.matrixNeedsUpdate ) this.updateTextureMatrix();
this.matrixNeedsUpdate = true;
// Render the mirrored view of the current scene into the target texture
var scene = this;
while ( scene.parent !== null ) {
scene = scene.parent;
}
if ( scene !== undefined && scene instanceof THREE.Scene ) {
// We can't render ourself to ourself
var visible = this.material.visible;
this.material.visible = false;
this.renderer.render( scene, this.mirrorCamera, this.renderTarget, true );
this.material.visible = visible;
}
};
THREE.Mirror.prototype.renderTemp = function () {
if ( this.matrixNeedsUpdate ) this.updateTextureMatrix();
this.matrixNeedsUpdate = true;
// Render the mirrored view of the current scene into the target texture
var scene = this;
while ( scene.parent !== null ) {
scene = scene.parent;
}
if ( scene !== undefined && scene instanceof THREE.Scene ) {
this.renderer.render( scene, this.mirrorCamera, this.renderTarget2, true );
}
};

69
node_modules/three/examples/js/MorphAnimMesh.js generated vendored Normal file
View File

@@ -0,0 +1,69 @@
/**
* @author alteredq / http://alteredqualia.com/
*/
THREE.MorphAnimMesh = function ( geometry, material ) {
THREE.Mesh.call( this, geometry, material );
this.type = 'MorphAnimMesh';
this.mixer = new THREE.AnimationMixer( this );
this.activeAction = null;
};
THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype );
THREE.MorphAnimMesh.prototype.constructor = THREE.MorphAnimMesh;
THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
this.mixer.timeScale = 1.0;
};
THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
this.mixer.timeScale = -1.0;
};
THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
if( this.activeAction ) {
this.activeAction.stop();
this.activeAction = null;
}
var clip = THREE.AnimationClip.findByName( this, label );
if ( clip ) {
var action = this.mixer.clipAction( clip );
action.timeScale = ( clip.tracks.length * fps ) / clip.duration;
this.activeAction = action.play();
} else {
throw new Error( 'THREE.MorphAnimMesh: animations[' + label + '] undefined in .playAnimation()' );
}
};
THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
this.mixer.update( delta );
};
THREE.MorphAnimMesh.prototype.copy = function ( source ) {
THREE.Mesh.prototype.copy.call( this, source );
this.mixer = new THREE.AnimationMixer( this );
return this;
};

73
node_modules/three/examples/js/MorphAnimation.js generated vendored Normal file
View File

@@ -0,0 +1,73 @@
/**
* @author mrdoob / http://mrdoob.com
* @author willy-vvu / http://willy-vvu.github.io
*/
THREE.MorphAnimation = function ( mesh ) {
this.mesh = mesh;
this.frames = mesh.morphTargetInfluences.length;
this.currentTime = 0;
this.duration = 1000;
this.loop = true;
this.lastFrame = 0;
this.currentFrame = 0;
this.isPlaying = false;
};
THREE.MorphAnimation.prototype = {
constructor: THREE.MorphAnimation,
play: function () {
this.isPlaying = true;
},
pause: function () {
this.isPlaying = false;
},
update: function ( delta ) {
if ( this.isPlaying === false ) return;
this.currentTime += delta;
if ( this.loop === true && this.currentTime > this.duration ) {
this.currentTime %= this.duration;
}
this.currentTime = Math.min( this.currentTime, this.duration );
var frameTime = this.duration / this.frames;
var frame = Math.floor( this.currentTime / frameTime );
var influences = this.mesh.morphTargetInfluences;
if ( frame !== this.currentFrame ) {
influences[ this.lastFrame ] = 0;
influences[ this.currentFrame ] = 1;
influences[ frame ] = 0;
this.lastFrame = this.currentFrame;
this.currentFrame = frame;
}
var mix = ( this.currentTime % frameTime ) / frameTime;
influences[ frame ] = mix;
influences[ this.lastFrame ] = 1 - mix;
}
};

359
node_modules/three/examples/js/Ocean.js generated vendored Normal file
View File

@@ -0,0 +1,359 @@
THREE.Ocean = function ( renderer, camera, scene, options ) {
// flag used to trigger parameter changes
this.changed = true;
this.initial = true;
// Assign required parameters as object properties
this.oceanCamera = new THREE.OrthographicCamera(); //camera.clone();
this.oceanCamera.position.z = 1;
this.renderer = renderer;
this.renderer.clearColor( 0xffffff );
this.scene = new THREE.Scene();
// Assign optional parameters as variables and object properties
function optionalParameter( value, defaultValue ) {
return value !== undefined ? value : defaultValue;
}
options = options || {};
this.clearColor = optionalParameter( options.CLEAR_COLOR, [ 1.0, 1.0, 1.0, 0.0 ] );
this.geometryOrigin = optionalParameter( options.GEOMETRY_ORIGIN, [ - 1000.0, - 1000.0 ] );
this.sunDirectionX = optionalParameter( options.SUN_DIRECTION[ 0 ], - 1.0 );
this.sunDirectionY = optionalParameter( options.SUN_DIRECTION[ 1 ], 1.0 );
this.sunDirectionZ = optionalParameter( options.SUN_DIRECTION[ 2 ], 1.0 );
this.oceanColor = optionalParameter( options.OCEAN_COLOR, new THREE.Vector3( 0.004, 0.016, 0.047 ) );
this.skyColor = optionalParameter( options.SKY_COLOR, new THREE.Vector3( 3.2, 9.6, 12.8 ) );
this.exposure = optionalParameter( options.EXPOSURE, 0.35 );
this.geometryResolution = optionalParameter( options.GEOMETRY_RESOLUTION, 32 );
this.geometrySize = optionalParameter( options.GEOMETRY_SIZE, 2000 );
this.resolution = optionalParameter( options.RESOLUTION, 64 );
this.floatSize = optionalParameter( options.SIZE_OF_FLOAT, 4 );
this.windX = optionalParameter( options.INITIAL_WIND[ 0 ], 10.0 );
this.windY = optionalParameter( options.INITIAL_WIND[ 1 ], 10.0 );
this.size = optionalParameter( options.INITIAL_SIZE, 250.0 );
this.choppiness = optionalParameter( options.INITIAL_CHOPPINESS, 1.5 );
//
this.matrixNeedsUpdate = false;
// Setup framebuffer pipeline
var renderTargetType = optionalParameter( options.USE_HALF_FLOAT, false ) ? THREE.HalfFloatType : THREE.FloatType;
var LinearClampParams = {
minFilter: THREE.LinearFilter,
magFilter: THREE.LinearFilter,
wrapS: THREE.ClampToEdgeWrapping,
wrapT: THREE.ClampToEdgeWrapping,
format: THREE.RGBAFormat,
stencilBuffer: false,
depthBuffer: false,
premultiplyAlpha: false,
type: renderTargetType
};
var NearestClampParams = {
minFilter: THREE.NearestFilter,
magFilter: THREE.NearestFilter,
wrapS: THREE.ClampToEdgeWrapping,
wrapT: THREE.ClampToEdgeWrapping,
format: THREE.RGBAFormat,
stencilBuffer: false,
depthBuffer: false,
premultiplyAlpha: false,
type: renderTargetType
};
var NearestRepeatParams = {
minFilter: THREE.NearestFilter,
magFilter: THREE.NearestFilter,
wrapS: THREE.RepeatWrapping,
wrapT: THREE.RepeatWrapping,
format: THREE.RGBAFormat,
stencilBuffer: false,
depthBuffer: false,
premultiplyAlpha: false,
type: renderTargetType
};
this.initialSpectrumFramebuffer = new THREE.WebGLRenderTarget( this.resolution, this.resolution, NearestRepeatParams );
this.spectrumFramebuffer = new THREE.WebGLRenderTarget( this.resolution, this.resolution, NearestClampParams );
this.pingPhaseFramebuffer = new THREE.WebGLRenderTarget( this.resolution, this.resolution, NearestClampParams );
this.pongPhaseFramebuffer = new THREE.WebGLRenderTarget( this.resolution, this.resolution, NearestClampParams );
this.pingTransformFramebuffer = new THREE.WebGLRenderTarget( this.resolution, this.resolution, NearestClampParams );
this.pongTransformFramebuffer = new THREE.WebGLRenderTarget( this.resolution, this.resolution, NearestClampParams );
this.displacementMapFramebuffer = new THREE.WebGLRenderTarget( this.resolution, this.resolution, LinearClampParams );
this.normalMapFramebuffer = new THREE.WebGLRenderTarget( this.resolution, this.resolution, LinearClampParams );
// Define shaders and constant uniforms
////////////////////////////////////////
// 0 - The vertex shader used in all of the simulation steps
var fullscreeenVertexShader = THREE.ShaderLib[ "ocean_sim_vertex" ];
// 1 - Horizontal wave vertices used for FFT
var oceanHorizontalShader = THREE.ShaderLib[ "ocean_subtransform" ];
var oceanHorizontalUniforms = THREE.UniformsUtils.clone( oceanHorizontalShader.uniforms );
this.materialOceanHorizontal = new THREE.ShaderMaterial( {
uniforms: oceanHorizontalUniforms,
vertexShader: fullscreeenVertexShader.vertexShader,
fragmentShader: "#define HORIZONTAL \n" + oceanHorizontalShader.fragmentShader
} );
this.materialOceanHorizontal.uniforms.u_transformSize = { value: this.resolution };
this.materialOceanHorizontal.uniforms.u_subtransformSize = { value: null };
this.materialOceanHorizontal.uniforms.u_input = { value: null };
this.materialOceanHorizontal.depthTest = false;
// 2 - Vertical wave vertices used for FFT
var oceanVerticalShader = THREE.ShaderLib[ "ocean_subtransform" ];
var oceanVerticalUniforms = THREE.UniformsUtils.clone( oceanVerticalShader.uniforms );
this.materialOceanVertical = new THREE.ShaderMaterial( {
uniforms: oceanVerticalUniforms,
vertexShader: fullscreeenVertexShader.vertexShader,
fragmentShader: oceanVerticalShader.fragmentShader
} );
this.materialOceanVertical.uniforms.u_transformSize = { value: this.resolution };
this.materialOceanVertical.uniforms.u_subtransformSize = { value: null };
this.materialOceanVertical.uniforms.u_input = { value: null };
this.materialOceanVertical.depthTest = false;
// 3 - Initial spectrum used to generate height map
var initialSpectrumShader = THREE.ShaderLib[ "ocean_initial_spectrum" ];
var initialSpectrumUniforms = THREE.UniformsUtils.clone( initialSpectrumShader.uniforms );
this.materialInitialSpectrum = new THREE.ShaderMaterial( {
uniforms: initialSpectrumUniforms,
vertexShader: fullscreeenVertexShader.vertexShader,
fragmentShader: initialSpectrumShader.fragmentShader
} );
this.materialInitialSpectrum.uniforms.u_wind = { value: new THREE.Vector2() };
this.materialInitialSpectrum.uniforms.u_resolution = { value: this.resolution };
this.materialInitialSpectrum.depthTest = false;
// 4 - Phases used to animate heightmap
var phaseShader = THREE.ShaderLib[ "ocean_phase" ];
var phaseUniforms = THREE.UniformsUtils.clone( phaseShader.uniforms );
this.materialPhase = new THREE.ShaderMaterial( {
uniforms: phaseUniforms,
vertexShader: fullscreeenVertexShader.vertexShader,
fragmentShader: phaseShader.fragmentShader
} );
this.materialPhase.uniforms.u_resolution = { value: this.resolution };
this.materialPhase.depthTest = false;
// 5 - Shader used to update spectrum
var spectrumShader = THREE.ShaderLib[ "ocean_spectrum" ];
var spectrumUniforms = THREE.UniformsUtils.clone( spectrumShader.uniforms );
this.materialSpectrum = new THREE.ShaderMaterial( {
uniforms: spectrumUniforms,
vertexShader: fullscreeenVertexShader.vertexShader,
fragmentShader: spectrumShader.fragmentShader
} );
this.materialSpectrum.uniforms.u_initialSpectrum = { value: null };
this.materialSpectrum.uniforms.u_resolution = { value: this.resolution };
this.materialSpectrum.depthTest = false;
// 6 - Shader used to update spectrum normals
var normalShader = THREE.ShaderLib[ "ocean_normals" ];
var normalUniforms = THREE.UniformsUtils.clone( normalShader.uniforms );
this.materialNormal = new THREE.ShaderMaterial( {
uniforms: normalUniforms,
vertexShader: fullscreeenVertexShader.vertexShader,
fragmentShader: normalShader.fragmentShader
} );
this.materialNormal.uniforms.u_displacementMap = { value: null };
this.materialNormal.uniforms.u_resolution = { value: this.resolution };
this.materialNormal.depthTest = false;
// 7 - Shader used to update normals
var oceanShader = THREE.ShaderLib[ "ocean_main" ];
var oceanUniforms = THREE.UniformsUtils.clone( oceanShader.uniforms );
this.materialOcean = new THREE.ShaderMaterial( {
uniforms: oceanUniforms,
vertexShader: oceanShader.vertexShader,
fragmentShader: oceanShader.fragmentShader
} );
// this.materialOcean.wireframe = true;
this.materialOcean.uniforms.u_geometrySize = { value: this.resolution };
this.materialOcean.uniforms.u_displacementMap = { value: this.displacementMapFramebuffer.texture };
this.materialOcean.uniforms.u_normalMap = { value: this.normalMapFramebuffer.texture };
this.materialOcean.uniforms.u_oceanColor = { value: this.oceanColor };
this.materialOcean.uniforms.u_skyColor = { value: this.skyColor };
this.materialOcean.uniforms.u_sunDirection = { value: new THREE.Vector3( this.sunDirectionX, this.sunDirectionY, this.sunDirectionZ ) };
this.materialOcean.uniforms.u_exposure = { value: this.exposure };
// Disable blending to prevent default premultiplied alpha values
this.materialOceanHorizontal.blending = 0;
this.materialOceanVertical.blending = 0;
this.materialInitialSpectrum.blending = 0;
this.materialPhase.blending = 0;
this.materialSpectrum.blending = 0;
this.materialNormal.blending = 0;
this.materialOcean.blending = 0;
// Create the simulation plane
this.screenQuad = new THREE.Mesh( new THREE.PlaneBufferGeometry( 2, 2 ) );
this.scene.add( this.screenQuad );
// Initialise spectrum data
this.generateSeedPhaseTexture();
// Generate the ocean mesh
this.generateMesh();
};
THREE.Ocean.prototype.generateMesh = function () {
var geometry = new THREE.PlaneBufferGeometry( this.geometrySize, this.geometrySize, this.geometryResolution, this.geometryResolution );
geometry.rotateX( - Math.PI / 2 );
this.oceanMesh = new THREE.Mesh( geometry, this.materialOcean );
};
THREE.Ocean.prototype.render = function () {
this.scene.overrideMaterial = null;
if ( this.changed )
this.renderInitialSpectrum();
this.renderWavePhase();
this.renderSpectrum();
this.renderSpectrumFFT();
this.renderNormalMap();
this.scene.overrideMaterial = null;
};
THREE.Ocean.prototype.generateSeedPhaseTexture = function() {
// Setup the seed texture
this.pingPhase = true;
var phaseArray = new window.Float32Array( this.resolution * this.resolution * 4 );
for ( var i = 0; i < this.resolution; i ++ ) {
for ( var j = 0; j < this.resolution; j ++ ) {
phaseArray[ i * this.resolution * 4 + j * 4 ] = Math.random() * 2.0 * Math.PI;
phaseArray[ i * this.resolution * 4 + j * 4 + 1 ] = 0.0;
phaseArray[ i * this.resolution * 4 + j * 4 + 2 ] = 0.0;
phaseArray[ i * this.resolution * 4 + j * 4 + 3 ] = 0.0;
}
}
this.pingPhaseTexture = new THREE.DataTexture( phaseArray, this.resolution, this.resolution, THREE.RGBAFormat );
this.pingPhaseTexture.wrapS = THREE.ClampToEdgeWrapping;
this.pingPhaseTexture.wrapT = THREE.ClampToEdgeWrapping;
this.pingPhaseTexture.type = THREE.FloatType;
this.pingPhaseTexture.needsUpdate = true;
};
THREE.Ocean.prototype.renderInitialSpectrum = function () {
this.scene.overrideMaterial = this.materialInitialSpectrum;
this.materialInitialSpectrum.uniforms.u_wind.value.set( this.windX, this.windY );
this.materialInitialSpectrum.uniforms.u_size.value = this.size;
this.renderer.render( this.scene, this.oceanCamera, this.initialSpectrumFramebuffer, true );
};
THREE.Ocean.prototype.renderWavePhase = function () {
this.scene.overrideMaterial = this.materialPhase;
this.screenQuad.material = this.materialPhase;
if ( this.initial ) {
this.materialPhase.uniforms.u_phases.value = this.pingPhaseTexture;
this.initial = false;
}else {
this.materialPhase.uniforms.u_phases.value = this.pingPhase ? this.pingPhaseFramebuffer.texture : this.pongPhaseFramebuffer.texture;
}
this.materialPhase.uniforms.u_deltaTime.value = this.deltaTime;
this.materialPhase.uniforms.u_size.value = this.size;
this.renderer.render( this.scene, this.oceanCamera, this.pingPhase ? this.pongPhaseFramebuffer : this.pingPhaseFramebuffer );
this.pingPhase = ! this.pingPhase;
};
THREE.Ocean.prototype.renderSpectrum = function () {
this.scene.overrideMaterial = this.materialSpectrum;
this.materialSpectrum.uniforms.u_initialSpectrum.value = this.initialSpectrumFramebuffer.texture;
this.materialSpectrum.uniforms.u_phases.value = this.pingPhase ? this.pingPhaseFramebuffer.texture : this.pongPhaseFramebuffer.texture;
this.materialSpectrum.uniforms.u_choppiness.value = this.choppiness;
this.materialSpectrum.uniforms.u_size.value = this.size;
this.renderer.render( this.scene, this.oceanCamera, this.spectrumFramebuffer );
};
THREE.Ocean.prototype.renderSpectrumFFT = function() {
// GPU FFT using Stockham formulation
var iterations = Math.log( this.resolution ) / Math.log( 2 ); // log2
this.scene.overrideMaterial = this.materialOceanHorizontal;
for ( var i = 0; i < iterations; i ++ ) {
if ( i === 0 ) {
this.materialOceanHorizontal.uniforms.u_input.value = this.spectrumFramebuffer.texture;
this.materialOceanHorizontal.uniforms.u_subtransformSize.value = Math.pow( 2, ( i % ( iterations ) ) + 1 );
this.renderer.render( this.scene, this.oceanCamera, this.pingTransformFramebuffer );
} else if ( i % 2 === 1 ) {
this.materialOceanHorizontal.uniforms.u_input.value = this.pingTransformFramebuffer.texture;
this.materialOceanHorizontal.uniforms.u_subtransformSize.value = Math.pow( 2, ( i % ( iterations ) ) + 1 );
this.renderer.render( this.scene, this.oceanCamera, this.pongTransformFramebuffer );
} else {
this.materialOceanHorizontal.uniforms.u_input.value = this.pongTransformFramebuffer.texture;
this.materialOceanHorizontal.uniforms.u_subtransformSize.value = Math.pow( 2, ( i % ( iterations ) ) + 1 );
this.renderer.render( this.scene, this.oceanCamera, this.pingTransformFramebuffer );
}
}
this.scene.overrideMaterial = this.materialOceanVertical;
for ( var i = iterations; i < iterations * 2; i ++ ) {
if ( i === iterations * 2 - 1 ) {
this.materialOceanVertical.uniforms.u_input.value = ( iterations % 2 === 0 ) ? this.pingTransformFramebuffer.texture : this.pongTransformFramebuffer.texture;
this.materialOceanVertical.uniforms.u_subtransformSize.value = Math.pow( 2, ( i % ( iterations ) ) + 1 );
this.renderer.render( this.scene, this.oceanCamera, this.displacementMapFramebuffer );
} else if ( i % 2 === 1 ) {
this.materialOceanVertical.uniforms.u_input.value = this.pingTransformFramebuffer.texture;
this.materialOceanVertical.uniforms.u_subtransformSize.value = Math.pow( 2, ( i % ( iterations ) ) + 1 );
this.renderer.render( this.scene, this.oceanCamera, this.pongTransformFramebuffer );
} else {
this.materialOceanVertical.uniforms.u_input.value = this.pongTransformFramebuffer.texture;
this.materialOceanVertical.uniforms.u_subtransformSize.value = Math.pow( 2, ( i % ( iterations ) ) + 1 );
this.renderer.render( this.scene, this.oceanCamera, this.pingTransformFramebuffer );
}
}
};
THREE.Ocean.prototype.renderNormalMap = function () {
this.scene.overrideMaterial = this.materialNormal;
if ( this.changed ) this.materialNormal.uniforms.u_size.value = this.size;
this.materialNormal.uniforms.u_displacementMap.value = this.displacementMapFramebuffer.texture;
this.renderer.render( this.scene, this.oceanCamera, this.normalMapFramebuffer, true );
};

2137
node_modules/three/examples/js/Octree.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

23
node_modules/three/examples/js/PRNG.js generated vendored Normal file
View File

@@ -0,0 +1,23 @@
// Park-Miller-Carta Pseudo-Random Number Generator
// https://github.com/pnitsch/BitmapData.js/blob/master/js/BitmapData.js
var PRNG = function () {
this.seed = 1;
this.next = function() {
return ( this.gen() / 2147483647 );
};
this.nextRange = function( min, max ) {
return min + ( ( max - min ) * this.next() )
};
this.gen = function() {
return this.seed = ( this.seed * 16807 ) % 2147483647;
};
};

266
node_modules/three/examples/js/ParametricGeometries.js generated vendored Normal file
View File

@@ -0,0 +1,266 @@
/*
* @author zz85
*
* Experimenting of primitive geometry creation using Surface Parametric equations
*
*/
THREE.ParametricGeometries = {
klein: function ( v, u ) {
u *= Math.PI;
v *= 2 * Math.PI;
u = u * 2;
var x, y, z;
if ( u < Math.PI ) {
x = 3 * Math.cos( u ) * ( 1 + Math.sin( u ) ) + ( 2 * ( 1 - Math.cos( u ) / 2 ) ) * Math.cos( u ) * Math.cos( v );
z = - 8 * Math.sin( u ) - 2 * ( 1 - Math.cos( u ) / 2 ) * Math.sin( u ) * Math.cos( v );
} else {
x = 3 * Math.cos( u ) * ( 1 + Math.sin( u ) ) + ( 2 * ( 1 - Math.cos( u ) / 2 ) ) * Math.cos( v + Math.PI );
z = - 8 * Math.sin( u );
}
y = - 2 * ( 1 - Math.cos( u ) / 2 ) * Math.sin( v );
return new THREE.Vector3( x, y, z );
},
plane: function ( width, height ) {
return function( u, v ) {
var x = u * width;
var y = 0;
var z = v * height;
return new THREE.Vector3( x, y, z );
};
},
mobius: function( u, t ) {
// flat mobius strip
// http://www.wolframalpha.com/input/?i=M%C3%B6bius+strip+parametric+equations&lk=1&a=ClashPrefs_*Surface.MoebiusStrip.SurfaceProperty.ParametricEquations-
u = u - 0.5;
var v = 2 * Math.PI * t;
var x, y, z;
var a = 2;
x = Math.cos( v ) * ( a + u * Math.cos( v / 2 ) );
y = Math.sin( v ) * ( a + u * Math.cos( v / 2 ) );
z = u * Math.sin( v / 2 );
return new THREE.Vector3( x, y, z );
},
mobius3d: function( u, t ) {
// volumetric mobius strip
u *= Math.PI;
t *= 2 * Math.PI;
u = u * 2;
var phi = u / 2;
var major = 2.25, a = 0.125, b = 0.65;
var x, y, z;
x = a * Math.cos( t ) * Math.cos( phi ) - b * Math.sin( t ) * Math.sin( phi );
z = a * Math.cos( t ) * Math.sin( phi ) + b * Math.sin( t ) * Math.cos( phi );
y = ( major + x ) * Math.sin( u );
x = ( major + x ) * Math.cos( u );
return new THREE.Vector3( x, y, z );
}
};
/*********************************************
*
* Parametric Replacement for TubeGeometry
*
*********************************************/
THREE.ParametricGeometries.TubeGeometry = function( path, segments, radius, segmentsRadius, closed, debug ) {
this.path = path;
this.segments = segments || 64;
this.radius = radius || 1;
this.segmentsRadius = segmentsRadius || 8;
this.closed = closed || false;
if ( debug ) this.debug = new THREE.Object3D();
var scope = this,
tangent, normal, binormal,
numpoints = this.segments + 1,
x, y, z, tx, ty, tz, u, v,
cx, cy, pos, pos2 = new THREE.Vector3(),
i, j, ip, jp, a, b, c, d, uva, uvb, uvc, uvd;
var frames = path.computeFrenetFrames( segments, closed ),
tangents = frames.tangents,
normals = frames.normals,
binormals = frames.binormals;
// proxy internals
this.tangents = tangents;
this.normals = normals;
this.binormals = binormals;
var ParametricTube = function( u, v ) {
v *= 2 * Math.PI;
i = u * ( numpoints - 1 );
i = Math.floor( i );
pos = path.getPointAt( u );
tangent = tangents[ i ];
normal = normals[ i ];
binormal = binormals[ i ];
if ( scope.debug ) {
scope.debug.add( new THREE.ArrowHelper( tangent, pos, radius, 0x0000ff ) );
scope.debug.add( new THREE.ArrowHelper( normal, pos, radius, 0xff0000 ) );
scope.debug.add( new THREE.ArrowHelper( binormal, pos, radius, 0x00ff00 ) );
}
cx = - scope.radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
cy = scope.radius * Math.sin( v );
pos2.copy( pos );
pos2.x += cx * normal.x + cy * binormal.x;
pos2.y += cx * normal.y + cy * binormal.y;
pos2.z += cx * normal.z + cy * binormal.z;
return pos2.clone();
};
THREE.ParametricGeometry.call( this, ParametricTube, segments, segmentsRadius );
};
THREE.ParametricGeometries.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
THREE.ParametricGeometries.TubeGeometry.prototype.constructor = THREE.ParametricGeometries.TubeGeometry;
/*********************************************
*
* Parametric Replacement for TorusKnotGeometry
*
*********************************************/
THREE.ParametricGeometries.TorusKnotGeometry = function ( radius, tube, segmentsT, segmentsR, p, q ) {
var scope = this;
this.radius = radius || 200;
this.tube = tube || 40;
this.segmentsT = segmentsT || 64;
this.segmentsR = segmentsR || 8;
this.p = p || 2;
this.q = q || 3;
function TorusKnotCurve() {}
TorusKnotCurve.prototype = Object.create( THREE.Curve.prototype );
TorusKnotCurve.prototype.constructor = TorusKnotCurve;
TorusKnotCurve.prototype.getPoint = function( t ){
t *= Math.PI * 2;
var r = 0.5;
var x = ( 1 + r * Math.cos( q * t ) ) * Math.cos( p * t );
var y = ( 1 + r * Math.cos( q * t ) ) * Math.sin( p * t );
var z = r * Math.sin( q * t );
return new THREE.Vector3( x, y, z ).multiplyScalar( radius );
};
var segments = segmentsT;
var radiusSegments = segmentsR;
var extrudePath = new TorusKnotCurve();
THREE.ParametricGeometries.TubeGeometry.call( this, extrudePath, segments, tube, radiusSegments, true, false );
};
THREE.ParametricGeometries.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
THREE.ParametricGeometries.TorusKnotGeometry.prototype.constructor = THREE.ParametricGeometries.TorusKnotGeometry;
/*********************************************
*
* Parametric Replacement for SphereGeometry
*
*********************************************/
THREE.ParametricGeometries.SphereGeometry = function( size, u, v ) {
function sphere( u, v ) {
u *= Math.PI;
v *= 2 * Math.PI;
var x = size * Math.sin( u ) * Math.cos( v );
var y = size * Math.sin( u ) * Math.sin( v );
var z = size * Math.cos( u );
return new THREE.Vector3( x, y, z );
}
THREE.ParametricGeometry.call( this, sphere, u, v, ! true );
};
THREE.ParametricGeometries.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
THREE.ParametricGeometries.SphereGeometry.prototype.constructor = THREE.ParametricGeometries.SphereGeometry;
/*********************************************
*
* Parametric Replacement for PlaneGeometry
*
*********************************************/
THREE.ParametricGeometries.PlaneGeometry = function( width, depth, segmentsWidth, segmentsDepth ) {
function plane( u, v ) {
var x = u * width;
var y = 0;
var z = v * depth;
return new THREE.Vector3( x, y, z );
}
THREE.ParametricGeometry.call( this, plane, segmentsWidth, segmentsDepth );
};
THREE.ParametricGeometries.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
THREE.ParametricGeometries.PlaneGeometry.prototype.constructor = THREE.ParametricGeometries.PlaneGeometry;

544
node_modules/three/examples/js/RollerCoaster.js generated vendored Normal file
View File

@@ -0,0 +1,544 @@
/**
* @author mrdoob / http://mrdoob.com/
*/
var RollerCoasterGeometry = function ( curve, size ) {
THREE.BufferGeometry.call( this );
var vertices = [];
var normals = [];
var colors = [];
var color1 = [ 1, 1, 1 ];
var color2 = [ 1, 1, 0 ];
var up = new THREE.Vector3( 0, 1, 0 );
var forward = new THREE.Vector3();
var right = new THREE.Vector3();
var quaternion = new THREE.Quaternion();
var prevQuaternion = new THREE.Quaternion();
prevQuaternion.setFromAxisAngle( up , Math.PI / 2 );
var point = new THREE.Vector3();
var prevPoint = new THREE.Vector3();
prevPoint.copy( curve.getPointAt( 0 ) );
// shapes
var step = [
new THREE.Vector3( -2.25, 0, 0 ),
new THREE.Vector3( 0, -0.5, 0 ),
new THREE.Vector3( 0, -1.75, 0 ),
new THREE.Vector3( 0, -0.5, 0 ),
new THREE.Vector3( 2.25, 0, 0 ),
new THREE.Vector3( 0, -1.75, 0 )
];
var PI2 = Math.PI * 2;
var sides = 5;
var tube1 = [];
for ( var i = 0; i < sides; i ++ ) {
var angle = ( i / sides ) * PI2;
tube1.push( new THREE.Vector3( Math.sin( angle ) * 0.6, Math.cos( angle ) * 0.6, 0 ) );
}
var sides = 6;
var tube2 = [];
for ( var i = 0; i < sides; i ++ ) {
var angle = ( i / sides ) * PI2;
tube2.push( new THREE.Vector3( Math.sin( angle ) * 0.25, Math.cos( angle ) * 0.25, 0 ) );
}
var vector = new THREE.Vector3();
var normal = new THREE.Vector3();
var drawShape = function ( shape, color ) {
normal.set( 0, 0, -1 ).applyQuaternion( quaternion );
for ( var j = 0; j < shape.length; j ++ ) {
vector.copy( shape[ j ] );
vector.applyQuaternion( quaternion );
vector.add( point );
vertices.push( vector.x, vector.y, vector.z );
normals.push( normal.x, normal.y, normal.z );
colors.push( color[ 0 ], color[ 1 ], color[ 2 ] );
}
normal.set( 0, 0, 1 ).applyQuaternion( quaternion );
for ( var j = shape.length - 1; j >= 0; j -- ) {
vector.copy( shape[ j ] );
vector.applyQuaternion( quaternion );
vector.add( point );
vertices.push( vector.x, vector.y, vector.z );
normals.push( normal.x, normal.y, normal.z );
colors.push( color[ 0 ], color[ 1 ], color[ 2 ] );
}
};
var vector1 = new THREE.Vector3();
var vector2 = new THREE.Vector3();
var vector3 = new THREE.Vector3();
var vector4 = new THREE.Vector3();
var normal1 = new THREE.Vector3();
var normal2 = new THREE.Vector3();
var normal3 = new THREE.Vector3();
var normal4 = new THREE.Vector3();
var extrudeShape = function ( shape, offset, color ) {
for ( var j = 0, jl = shape.length; j < jl; j ++ ) {
var point1 = shape[ j ];
var point2 = shape[ ( j + 1 ) % jl ];
vector1.copy( point1 ).add( offset );
vector1.applyQuaternion( quaternion );
vector1.add( point );
vector2.copy( point2 ).add( offset );
vector2.applyQuaternion( quaternion );
vector2.add( point );
vector3.copy( point2 ).add( offset );
vector3.applyQuaternion( prevQuaternion );
vector3.add( prevPoint );
vector4.copy( point1 ).add( offset );
vector4.applyQuaternion( prevQuaternion );
vector4.add( prevPoint );
vertices.push( vector1.x, vector1.y, vector1.z );
vertices.push( vector2.x, vector2.y, vector2.z );
vertices.push( vector4.x, vector4.y, vector4.z );
vertices.push( vector2.x, vector2.y, vector2.z );
vertices.push( vector3.x, vector3.y, vector3.z );
vertices.push( vector4.x, vector4.y, vector4.z );
//
normal1.copy( point1 );
normal1.applyQuaternion( quaternion );
normal1.normalize();
normal2.copy( point2 );
normal2.applyQuaternion( quaternion );
normal2.normalize();
normal3.copy( point2 );
normal3.applyQuaternion( prevQuaternion );
normal3.normalize();
normal4.copy( point1 );
normal4.applyQuaternion( prevQuaternion );
normal4.normalize();
normals.push( normal1.x, normal1.y, normal1.z );
normals.push( normal2.x, normal2.y, normal2.z );
normals.push( normal4.x, normal4.y, normal4.z );
normals.push( normal2.x, normal2.y, normal2.z );
normals.push( normal3.x, normal3.y, normal3.z );
normals.push( normal4.x, normal4.y, normal4.z );
colors.push( color[ 0 ], color[ 1 ], color[ 2 ] );
colors.push( color[ 0 ], color[ 1 ], color[ 2 ] );
colors.push( color[ 0 ], color[ 1 ], color[ 2 ] );
colors.push( color[ 0 ], color[ 1 ], color[ 2 ] );
colors.push( color[ 0 ], color[ 1 ], color[ 2 ] );
colors.push( color[ 0 ], color[ 1 ], color[ 2 ] );
}
};
var offset = new THREE.Vector3();
for ( var i = 1; i <= size; i ++ ) {
point.copy( curve.getPointAt( i / size ) );
up.set( 0, 1, 0 );
forward.subVectors( point, prevPoint ).normalize();
right.crossVectors( up, forward ).normalize();
up.crossVectors( forward, right );
var angle = Math.atan2( forward.x, forward.z );
quaternion.setFromAxisAngle( up, angle );
if ( i % 2 === 0 ) {
drawShape( step, color2 );
}
extrudeShape( tube1, offset.set( 0, -1.25, 0 ), color2 );
extrudeShape( tube2, offset.set( 2, 0, 0 ), color1 );
extrudeShape( tube2, offset.set( -2, 0, 0 ), color1 );
prevPoint.copy( point );
prevQuaternion.copy( quaternion );
}
// console.log( vertices.length );
this.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array( vertices ), 3 ) );
this.addAttribute( 'normal', new THREE.BufferAttribute( new Float32Array( normals ), 3 ) );
this.addAttribute( 'color', new THREE.BufferAttribute( new Float32Array( colors ), 3 ) );
};
RollerCoasterGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
var RollerCoasterLiftersGeometry = function ( curve, size ) {
THREE.BufferGeometry.call( this );
var vertices = [];
var normals = [];
var quaternion = new THREE.Quaternion();
var up = new THREE.Vector3( 0, 1, 0 );
var point = new THREE.Vector3();
var tangent = new THREE.Vector3();
// shapes
var tube1 = [
new THREE.Vector3( 0, 0.5, -0.5 ),
new THREE.Vector3( 0, 0.5, 0.5 ),
new THREE.Vector3( 0, -0.5, 0 )
];
var tube2 = [
new THREE.Vector3( -0.5, 0, 0.5 ),
new THREE.Vector3( -0.5, 0, -0.5 ),
new THREE.Vector3( 0.5, 0, 0 )
];
var tube3 = [
new THREE.Vector3( 0.5, 0, -0.5 ),
new THREE.Vector3( 0.5, 0, 0.5 ),
new THREE.Vector3( -0.5, 0, 0 )
];
var vector1 = new THREE.Vector3();
var vector2 = new THREE.Vector3();
var vector3 = new THREE.Vector3();
var vector4 = new THREE.Vector3();
var normal1 = new THREE.Vector3();
var normal2 = new THREE.Vector3();
var normal3 = new THREE.Vector3();
var normal4 = new THREE.Vector3();
var extrudeShape = function ( shape, fromPoint, toPoint ) {
for ( var j = 0, jl = shape.length; j < jl; j ++ ) {
var point1 = shape[ j ];
var point2 = shape[ ( j + 1 ) % jl ];
vector1.copy( point1 );
vector1.applyQuaternion( quaternion );
vector1.add( fromPoint );
vector2.copy( point2 );
vector2.applyQuaternion( quaternion );
vector2.add( fromPoint );
vector3.copy( point2 );
vector3.applyQuaternion( quaternion );
vector3.add( toPoint );
vector4.copy( point1 );
vector4.applyQuaternion( quaternion );
vector4.add( toPoint );
vertices.push( vector1.x, vector1.y, vector1.z );
vertices.push( vector2.x, vector2.y, vector2.z );
vertices.push( vector4.x, vector4.y, vector4.z );
vertices.push( vector2.x, vector2.y, vector2.z );
vertices.push( vector3.x, vector3.y, vector3.z );
vertices.push( vector4.x, vector4.y, vector4.z );
//
normal1.copy( point1 );
normal1.applyQuaternion( quaternion );
normal1.normalize();
normal2.copy( point2 );
normal2.applyQuaternion( quaternion );
normal2.normalize();
normal3.copy( point2 );
normal3.applyQuaternion( quaternion );
normal3.normalize();
normal4.copy( point1 );
normal4.applyQuaternion( quaternion );
normal4.normalize();
normals.push( normal1.x, normal1.y, normal1.z );
normals.push( normal2.x, normal2.y, normal2.z );
normals.push( normal4.x, normal4.y, normal4.z );
normals.push( normal2.x, normal2.y, normal2.z );
normals.push( normal3.x, normal3.y, normal3.z );
normals.push( normal4.x, normal4.y, normal4.z );
}
};
var fromPoint = new THREE.Vector3();
var toPoint = new THREE.Vector3();
for ( var i = 1; i <= size; i ++ ) {
point.copy( curve.getPointAt( i / size ) );
tangent.copy( curve.getTangentAt( i / size ) );
var angle = Math.atan2( tangent.x, tangent.z );
quaternion.setFromAxisAngle( up, angle );
//
if ( point.y > 100 ) {
fromPoint.set( -7.5, -3.5, 0 );
fromPoint.applyQuaternion( quaternion );
fromPoint.add( point );
toPoint.set( 7.5, -3.5, 0 );
toPoint.applyQuaternion( quaternion );
toPoint.add( point );
extrudeShape( tube1, fromPoint, toPoint );
fromPoint.set( -7, -3, 0 );
fromPoint.applyQuaternion( quaternion );
fromPoint.add( point );
toPoint.set( -7, -point.y, 0 );
toPoint.applyQuaternion( quaternion );
toPoint.add( point );
extrudeShape( tube2, fromPoint, toPoint );
fromPoint.set( 7, -3, 0 );
fromPoint.applyQuaternion( quaternion );
fromPoint.add( point );
toPoint.set( 7, -point.y, 0 );
toPoint.applyQuaternion( quaternion );
toPoint.add( point );
extrudeShape( tube3, fromPoint, toPoint );
} else {
fromPoint.set( 0, -2, 0 );
fromPoint.applyQuaternion( quaternion );
fromPoint.add( point );
toPoint.set( 0, -point.y, 0 );
toPoint.applyQuaternion( quaternion );
toPoint.add( point );
extrudeShape( tube3, fromPoint, toPoint );
}
}
this.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array( vertices ), 3 ) );
this.addAttribute( 'normal', new THREE.BufferAttribute( new Float32Array( normals ), 3 ) );
};
RollerCoasterLiftersGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
var RollerCoasterShadowGeometry = function ( curve, size ) {
THREE.BufferGeometry.call( this );
var vertices = [];
var up = new THREE.Vector3( 0, 1, 0 );
var forward = new THREE.Vector3();
var quaternion = new THREE.Quaternion();
var prevQuaternion = new THREE.Quaternion();
prevQuaternion.setFromAxisAngle( up , Math.PI / 2 );
var point = new THREE.Vector3();
var prevPoint = new THREE.Vector3();
prevPoint.copy( curve.getPointAt( 0 ) );
prevPoint.y = 0;
var vector1 = new THREE.Vector3();
var vector2 = new THREE.Vector3();
var vector3 = new THREE.Vector3();
var vector4 = new THREE.Vector3();
for ( var i = 1; i <= size; i ++ ) {
point.copy( curve.getPointAt( i / size ) );
point.y = 0;
forward.subVectors( point, prevPoint );
var angle = Math.atan2( forward.x, forward.z );
quaternion.setFromAxisAngle( up, angle );
vector1.set( -3, 0, 0 );
vector1.applyQuaternion( quaternion );
vector1.add( point );
vector2.set( 3, 0, 0 );
vector2.applyQuaternion( quaternion );
vector2.add( point );
vector3.set( 3, 0, 0 );
vector3.applyQuaternion( prevQuaternion );
vector3.add( prevPoint );
vector4.set( -3, 0, 0 );
vector4.applyQuaternion( prevQuaternion );
vector4.add( prevPoint );
vertices.push( vector1.x, vector1.y, vector1.z );
vertices.push( vector2.x, vector2.y, vector2.z );
vertices.push( vector4.x, vector4.y, vector4.z );
vertices.push( vector2.x, vector2.y, vector2.z );
vertices.push( vector3.x, vector3.y, vector3.z );
vertices.push( vector4.x, vector4.y, vector4.z );
prevPoint.copy( point );
prevQuaternion.copy( quaternion );
}
this.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array( vertices ), 3 ) );
};
RollerCoasterShadowGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
var SkyGeometry = function () {
THREE.BufferGeometry.call( this );
var vertices = [];
for ( var i = 0; i < 100; i ++ ) {
var x = Math.random() * 8000 - 4000;
var y = Math.random() * 500 + 500;
var z = Math.random() * 8000 - 4000;
var size = Math.random() * 400 + 200;
vertices.push( x - size, y, z - size );
vertices.push( x + size, y, z - size );
vertices.push( x - size, y, z + size );
vertices.push( x + size, y, z - size );
vertices.push( x + size, y, z + size );
vertices.push( x - size, y, z + size );
}
this.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array( vertices ), 3 ) );
};
SkyGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
var TreesGeometry = function ( landscape ) {
THREE.BufferGeometry.call( this );
var vertices = [];
var colors = [];
var raycaster = new THREE.Raycaster();
raycaster.ray.direction.set( 0, -1, 0 );
for ( var i = 0; i < 2000; i ++ ) {
var x = Math.random() * 5000 - 2500;
var z = Math.random() * 5000 - 2500;
raycaster.ray.origin.set( x, 500, z );
var intersections = raycaster.intersectObject( landscape );
if ( intersections.length === 0 ) continue;
var y = intersections[ 0 ].point.y;
var height = Math.random() * 50 + 5;
var angle = Math.random() * Math.PI * 2;
vertices.push( x + Math.sin( angle ) * 10, y, z + Math.cos( angle ) * 10 );
vertices.push( x, y + height, z );
vertices.push( x + Math.sin( angle + Math.PI ) * 10, y, z + Math.cos( angle + Math.PI ) * 10 );
angle += Math.PI / 2;
vertices.push( x + Math.sin( angle ) * 10, y, z + Math.cos( angle ) * 10 );
vertices.push( x, y + height, z );
vertices.push( x + Math.sin( angle + Math.PI ) * 10, y, z + Math.cos( angle + Math.PI ) * 10 );
var random = Math.random() * 0.1;
for ( var j = 0; j < 6; j ++ ) {
colors.push( 0.2 + random, 0.4 + random, 0 );
}
}
this.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array( vertices ), 3 ) );
this.addAttribute( 'color', new THREE.BufferAttribute( new Float32Array( colors ), 3 ) );
};
TreesGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );

295
node_modules/three/examples/js/ShaderGodRays.js generated vendored Normal file
View File

@@ -0,0 +1,295 @@
/**
* @author huwb / http://huwbowles.com/
*
* God-rays (crepuscular rays)
*
* Similar implementation to the one used by Crytek for CryEngine 2 [Sousa2008].
* Blurs a mask generated from the depth map along radial lines emanating from the light
* source. The blur repeatedly applies a blur filter of increasing support but constant
* sample count to produce a blur filter with large support.
*
* My implementation performs 3 passes, similar to the implementation from Sousa. I found
* just 6 samples per pass produced acceptible results. The blur is applied three times,
* with decreasing filter support. The result is equivalent to a single pass with
* 6*6*6 = 216 samples.
*
* References:
*
* Sousa2008 - Crysis Next Gen Effects, GDC2008, http://www.crytek.com/sites/default/files/GDC08_SousaT_CrysisEffects.ppt
*/
THREE.ShaderGodRays = {
/**
* The god-ray generation shader.
*
* First pass:
*
* The input is the depth map. I found that the output from the
* THREE.MeshDepthMaterial material was directly suitable without
* requiring any treatment whatsoever.
*
* The depth map is blurred along radial lines towards the "sun". The
* output is written to a temporary render target (I used a 1/4 sized
* target).
*
* Pass two & three:
*
* The results of the previous pass are re-blurred, each time with a
* decreased distance between samples.
*/
'godrays_generate': {
uniforms: {
tInput: {
value: null
},
fStepSize: {
value: 1.0
},
vSunPositionScreenSpace: {
value: new THREE.Vector2( 0.5, 0.5 )
}
},
vertexShader: [
"varying vec2 vUv;",
"void main() {",
"vUv = uv;",
"gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
"}"
].join( "\n" ),
fragmentShader: [
"#define TAPS_PER_PASS 6.0",
"varying vec2 vUv;",
"uniform sampler2D tInput;",
"uniform vec2 vSunPositionScreenSpace;",
"uniform float fStepSize;", // filter step size
"void main() {",
// delta from current pixel to "sun" position
"vec2 delta = vSunPositionScreenSpace - vUv;",
"float dist = length( delta );",
// Step vector (uv space)
"vec2 stepv = fStepSize * delta / dist;",
// Number of iterations between pixel and sun
"float iters = dist/fStepSize;",
"vec2 uv = vUv.xy;",
"float col = 0.0;",
// This breaks ANGLE in Chrome 22
// - see http://code.google.com/p/chromium/issues/detail?id=153105
/*
// Unrolling didnt do much on my hardware (ATI Mobility Radeon 3450),
// so i've just left the loop
"for ( float i = 0.0; i < TAPS_PER_PASS; i += 1.0 ) {",
// Accumulate samples, making sure we dont walk past the light source.
// The check for uv.y < 1 would not be necessary with "border" UV wrap
// mode, with a black border colour. I don't think this is currently
// exposed by three.js. As a result there might be artifacts when the
// sun is to the left, right or bottom of screen as these cases are
// not specifically handled.
"col += ( i <= iters && uv.y < 1.0 ? texture2D( tInput, uv ).r : 0.0 );",
"uv += stepv;",
"}",
*/
// Unrolling loop manually makes it work in ANGLE
"if ( 0.0 <= iters && uv.y < 1.0 ) col += texture2D( tInput, uv ).r;",
"uv += stepv;",
"if ( 1.0 <= iters && uv.y < 1.0 ) col += texture2D( tInput, uv ).r;",
"uv += stepv;",
"if ( 2.0 <= iters && uv.y < 1.0 ) col += texture2D( tInput, uv ).r;",
"uv += stepv;",
"if ( 3.0 <= iters && uv.y < 1.0 ) col += texture2D( tInput, uv ).r;",
"uv += stepv;",
"if ( 4.0 <= iters && uv.y < 1.0 ) col += texture2D( tInput, uv ).r;",
"uv += stepv;",
"if ( 5.0 <= iters && uv.y < 1.0 ) col += texture2D( tInput, uv ).r;",
"uv += stepv;",
// Should technically be dividing by 'iters', but 'TAPS_PER_PASS' smooths out
// objectionable artifacts, in particular near the sun position. The side
// effect is that the result is darker than it should be around the sun, as
// TAPS_PER_PASS is greater than the number of samples actually accumulated.
// When the result is inverted (in the shader 'godrays_combine', this produces
// a slight bright spot at the position of the sun, even when it is occluded.
"gl_FragColor = vec4( col/TAPS_PER_PASS );",
"gl_FragColor.a = 1.0;",
"}"
].join( "\n" )
},
/**
* Additively applies god rays from texture tGodRays to a background (tColors).
* fGodRayIntensity attenuates the god rays.
*/
'godrays_combine': {
uniforms: {
tColors: {
value: null
},
tGodRays: {
value: null
},
fGodRayIntensity: {
value: 0.69
},
vSunPositionScreenSpace: {
value: new THREE.Vector2( 0.5, 0.5 )
}
},
vertexShader: [
"varying vec2 vUv;",
"void main() {",
"vUv = uv;",
"gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
"}"
].join( "\n" ),
fragmentShader: [
"varying vec2 vUv;",
"uniform sampler2D tColors;",
"uniform sampler2D tGodRays;",
"uniform vec2 vSunPositionScreenSpace;",
"uniform float fGodRayIntensity;",
"void main() {",
// Since THREE.MeshDepthMaterial renders foreground objects white and background
// objects black, the god-rays will be white streaks. Therefore value is inverted
// before being combined with tColors
"gl_FragColor = texture2D( tColors, vUv ) + fGodRayIntensity * vec4( 1.0 - texture2D( tGodRays, vUv ).r );",
"gl_FragColor.a = 1.0;",
"}"
].join( "\n" )
},
/**
* A dodgy sun/sky shader. Makes a bright spot at the sun location. Would be
* cheaper/faster/simpler to implement this as a simple sun sprite.
*/
'godrays_fake_sun': {
uniforms: {
vSunPositionScreenSpace: {
value: new THREE.Vector2( 0.5, 0.5 )
},
fAspect: {
value: 1.0
},
sunColor: {
value: new THREE.Color( 0xffee00 )
},
bgColor: {
value: new THREE.Color( 0x000000 )
}
},
vertexShader: [
"varying vec2 vUv;",
"void main() {",
"vUv = uv;",
"gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
"}"
].join( "\n" ),
fragmentShader: [
"varying vec2 vUv;",
"uniform vec2 vSunPositionScreenSpace;",
"uniform float fAspect;",
"uniform vec3 sunColor;",
"uniform vec3 bgColor;",
"void main() {",
"vec2 diff = vUv - vSunPositionScreenSpace;",
// Correct for aspect ratio
"diff.x *= fAspect;",
"float prop = clamp( length( diff ) / 0.5, 0.0, 1.0 );",
"prop = 0.35 * pow( 1.0 - prop, 3.0 );",
"gl_FragColor.xyz = mix( sunColor, bgColor, 1.0 - prop );",
"gl_FragColor.w = 1.0;",
"}"
].join( "\n" )
}
};

698
node_modules/three/examples/js/ShaderSkin.js generated vendored Normal file
View File

@@ -0,0 +1,698 @@
/**
* @author alteredq / http://alteredqualia.com/
*
*/
THREE.ShaderSkin = {
/* ------------------------------------------------------------------------------------------
// Simple skin shader
// - per-pixel Blinn-Phong diffuse term mixed with half-Lambert wrap-around term (per color component)
// - physically based specular term (Kelemen/Szirmay-Kalos specular reflectance)
//
// - diffuse map
// - bump map
// - specular map
// - point, directional and hemisphere lights (use with "lights: true" material option)
// - fog (use with "fog: true" material option)
// - shadow maps
//
// ------------------------------------------------------------------------------------------ */
'skinSimple' : {
uniforms: THREE.UniformsUtils.merge( [
THREE.UniformsLib[ "fog" ],
THREE.UniformsLib[ "lights" ],
{
"enableBump": { value: 0 },
"enableSpecular": { value: 0 },
"tDiffuse": { value: null },
"tBeckmann": { value: null },
"diffuse": { value: new THREE.Color( 0xeeeeee ) },
"specular": { value: new THREE.Color( 0x111111 ) },
"opacity": { value: 1 },
"uRoughness": { value: 0.15 },
"uSpecularBrightness": { value: 0.75 },
"bumpMap": { value: null },
"bumpScale": { value: 1 },
"specularMap": { value: null },
"offsetRepeat": { value: new THREE.Vector4( 0, 0, 1, 1 ) },
"uWrapRGB": { value: new THREE.Vector3( 0.75, 0.375, 0.1875 ) }
}
] ),
fragmentShader: [
"#define USE_BUMPMAP",
"uniform bool enableBump;",
"uniform bool enableSpecular;",
"uniform vec3 diffuse;",
"uniform vec3 specular;",
"uniform float opacity;",
"uniform float uRoughness;",
"uniform float uSpecularBrightness;",
"uniform vec3 uWrapRGB;",
"uniform sampler2D tDiffuse;",
"uniform sampler2D tBeckmann;",
"uniform sampler2D specularMap;",
"varying vec3 vNormal;",
"varying vec2 vUv;",
"varying vec3 vViewPosition;",
THREE.ShaderChunk[ "common" ],
THREE.ShaderChunk[ "bsdfs" ],
THREE.ShaderChunk[ "packing" ],
THREE.ShaderChunk[ "lights_pars" ],
THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
THREE.ShaderChunk[ "fog_pars_fragment" ],
THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
// Fresnel term
"float fresnelReflectance( vec3 H, vec3 V, float F0 ) {",
"float base = 1.0 - dot( V, H );",
"float exponential = pow( base, 5.0 );",
"return exponential + F0 * ( 1.0 - exponential );",
"}",
// Kelemen/Szirmay-Kalos specular BRDF
"float KS_Skin_Specular( vec3 N,", // Bumped surface normal
"vec3 L,", // Points to light
"vec3 V,", // Points to eye
"float m,", // Roughness
"float rho_s", // Specular brightness
") {",
"float result = 0.0;",
"float ndotl = dot( N, L );",
"if( ndotl > 0.0 ) {",
"vec3 h = L + V;", // Unnormalized half-way vector
"vec3 H = normalize( h );",
"float ndoth = dot( N, H );",
"float PH = pow( 2.0 * texture2D( tBeckmann, vec2( ndoth, m ) ).x, 10.0 );",
"float F = fresnelReflectance( H, V, 0.028 );",
"float frSpec = max( PH * F / dot( h, h ), 0.0 );",
"result = ndotl * rho_s * frSpec;", // BRDF * dot(N,L) * rho_s
"}",
"return result;",
"}",
"void main() {",
"vec3 outgoingLight = vec3( 0.0 );", // outgoing light does not have an alpha, the surface does
"vec4 diffuseColor = vec4( diffuse, opacity );",
"vec4 colDiffuse = texture2D( tDiffuse, vUv );",
"colDiffuse.rgb *= colDiffuse.rgb;",
"diffuseColor = diffuseColor * colDiffuse;",
"vec3 normal = normalize( vNormal );",
"vec3 viewerDirection = normalize( vViewPosition );",
"float specularStrength;",
"if ( enableSpecular ) {",
"vec4 texelSpecular = texture2D( specularMap, vUv );",
"specularStrength = texelSpecular.r;",
"} else {",
"specularStrength = 1.0;",
"}",
"#ifdef USE_BUMPMAP",
"if ( enableBump ) normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );",
"#endif",
// point lights
"vec3 totalSpecularLight = vec3( 0.0 );",
"vec3 totalDiffuseLight = vec3( 0.0 );",
"#if NUM_POINT_LIGHTS > 0",
"for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {",
"vec3 lVector = pointLights[ i ].position + vViewPosition.xyz;",
"float attenuation = calcLightAttenuation( length( lVector ), pointLights[ i ].distance, pointLights[ i ].decay );",
"lVector = normalize( lVector );",
"float pointDiffuseWeightFull = max( dot( normal, lVector ), 0.0 );",
"float pointDiffuseWeightHalf = max( 0.5 * dot( normal, lVector ) + 0.5, 0.0 );",
"vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), uWrapRGB );",
"float pointSpecularWeight = KS_Skin_Specular( normal, lVector, viewerDirection, uRoughness, uSpecularBrightness );",
"totalDiffuseLight += pointLight[ i ].color * ( pointDiffuseWeight * attenuation );",
"totalSpecularLight += pointLight[ i ].color * specular * ( pointSpecularWeight * specularStrength * attenuation );",
"}",
"#endif",
// directional lights
"#if NUM_DIR_LIGHTS > 0",
"for( int i = 0; i < NUM_DIR_LIGHTS; i++ ) {",
"vec3 dirVector = directionalLights[ i ].direction;",
"float dirDiffuseWeightFull = max( dot( normal, dirVector ), 0.0 );",
"float dirDiffuseWeightHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );",
"vec3 dirDiffuseWeight = mix( vec3 ( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), uWrapRGB );",
"float dirSpecularWeight = KS_Skin_Specular( normal, dirVector, viewerDirection, uRoughness, uSpecularBrightness );",
"totalDiffuseLight += directionalLights[ i ].color * dirDiffuseWeight;",
"totalSpecularLight += directionalLights[ i ].color * ( dirSpecularWeight * specularStrength );",
"}",
"#endif",
// hemisphere lights
"#if NUM_HEMI_LIGHTS > 0",
"for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {",
"vec3 lVector = hemisphereLightDirection[ i ];",
"float dotProduct = dot( normal, lVector );",
"float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
"totalDiffuseLight += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
// specular (sky light)
"float hemiSpecularWeight = 0.0;",
"hemiSpecularWeight += KS_Skin_Specular( normal, lVector, viewerDirection, uRoughness, uSpecularBrightness );",
// specular (ground light)
"vec3 lVectorGround = -lVector;",
"hemiSpecularWeight += KS_Skin_Specular( normal, lVectorGround, viewerDirection, uRoughness, uSpecularBrightness );",
"vec3 hemiSpecularColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
"totalSpecularLight += hemiSpecularColor * specular * ( hemiSpecularWeight * specularStrength );",
"}",
"#endif",
"outgoingLight += diffuseColor.xyz * ( totalDiffuseLight + ambientLightColor * diffuse ) + totalSpecularLight;",
"gl_FragColor = linearToOutputTexel( vec4( outgoingLight, diffuseColor.a ) );", // TODO, this should be pre-multiplied to allow for bright highlights on very transparent objects
THREE.ShaderChunk[ "fog_fragment" ],
"}"
].join( "\n" ),
vertexShader: [
"uniform vec4 offsetRepeat;",
"varying vec3 vNormal;",
"varying vec2 vUv;",
"varying vec3 vViewPosition;",
THREE.ShaderChunk[ "common" ],
THREE.ShaderChunk[ "lights_pars" ],
THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
THREE.ShaderChunk[ "fog_pars_vertex" ],
"void main() {",
"vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
"vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
"vViewPosition = -mvPosition.xyz;",
"vNormal = normalize( normalMatrix * normal );",
"vUv = uv * offsetRepeat.zw + offsetRepeat.xy;",
"gl_Position = projectionMatrix * mvPosition;",
THREE.ShaderChunk[ "shadowmap_vertex" ],
THREE.ShaderChunk[ "fog_vertex" ],
"}"
].join( "\n" )
},
/* ------------------------------------------------------------------------------------------
// Skin shader
// - Blinn-Phong diffuse term (using normal + diffuse maps)
// - subsurface scattering approximation by four blur layers
// - physically based specular term (Kelemen/Szirmay-Kalos specular reflectance)
//
// - point and directional lights (use with "lights: true" material option)
//
// - based on Nvidia Advanced Skin Rendering GDC 2007 presentation
// and GPU Gems 3 Chapter 14. Advanced Techniques for Realistic Real-Time Skin Rendering
//
// http://developer.download.nvidia.com/presentations/2007/gdc/Advanced_Skin.pdf
// http://http.developer.nvidia.com/GPUGems3/gpugems3_ch14.html
// ------------------------------------------------------------------------------------------ */
'skin' : {
uniforms: THREE.UniformsUtils.merge( [
THREE.UniformsLib[ "fog" ],
THREE.UniformsLib[ "lights" ],
{
"passID": { value: 0 },
"tDiffuse" : { value: null },
"tNormal" : { value: null },
"tBlur1" : { value: null },
"tBlur2" : { value: null },
"tBlur3" : { value: null },
"tBlur4" : { value: null },
"tBeckmann" : { value: null },
"uNormalScale": { value: 1.0 },
"diffuse": { value: new THREE.Color( 0xeeeeee ) },
"specular": { value: new THREE.Color( 0x111111 ) },
"opacity": { value: 1 },
"uRoughness": { value: 0.15 },
"uSpecularBrightness": { value: 0.75 }
}
] ),
fragmentShader: [
"uniform vec3 diffuse;",
"uniform vec3 specular;",
"uniform float opacity;",
"uniform float uRoughness;",
"uniform float uSpecularBrightness;",
"uniform int passID;",
"uniform sampler2D tDiffuse;",
"uniform sampler2D tNormal;",
"uniform sampler2D tBlur1;",
"uniform sampler2D tBlur2;",
"uniform sampler2D tBlur3;",
"uniform sampler2D tBlur4;",
"uniform sampler2D tBeckmann;",
"uniform float uNormalScale;",
"varying vec3 vNormal;",
"varying vec2 vUv;",
"varying vec3 vViewPosition;",
THREE.ShaderChunk[ "common" ],
THREE.ShaderChunk[ "lights_pars" ],
THREE.ShaderChunk[ "fog_pars_fragment" ],
"float fresnelReflectance( vec3 H, vec3 V, float F0 ) {",
"float base = 1.0 - dot( V, H );",
"float exponential = pow( base, 5.0 );",
"return exponential + F0 * ( 1.0 - exponential );",
"}",
// Kelemen/Szirmay-Kalos specular BRDF
"float KS_Skin_Specular( vec3 N,", // Bumped surface normal
"vec3 L,", // Points to light
"vec3 V,", // Points to eye
"float m,", // Roughness
"float rho_s", // Specular brightness
") {",
"float result = 0.0;",
"float ndotl = dot( N, L );",
"if( ndotl > 0.0 ) {",
"vec3 h = L + V;", // Unnormalized half-way vector
"vec3 H = normalize( h );",
"float ndoth = dot( N, H );",
"float PH = pow( 2.0 * texture2D( tBeckmann, vec2( ndoth, m ) ).x, 10.0 );",
"float F = fresnelReflectance( H, V, 0.028 );",
"float frSpec = max( PH * F / dot( h, h ), 0.0 );",
"result = ndotl * rho_s * frSpec;", // BRDF * dot(N,L) * rho_s
"}",
"return result;",
"}",
"void main() {",
"vec3 outgoingLight = vec3( 0.0 );", // outgoing light does not have an alpha, the surface does
"vec4 diffuseColor = vec4( diffuse, opacity );",
"vec4 mSpecular = vec4( specular, opacity );",
"vec4 colDiffuse = texture2D( tDiffuse, vUv );",
"colDiffuse *= colDiffuse;",
"diffuseColor *= colDiffuse;",
// normal mapping
"vec4 posAndU = vec4( -vViewPosition, vUv.x );",
"vec4 posAndU_dx = dFdx( posAndU ), posAndU_dy = dFdy( posAndU );",
"vec3 tangent = posAndU_dx.w * posAndU_dx.xyz + posAndU_dy.w * posAndU_dy.xyz;",
"vec3 normal = normalize( vNormal );",
"vec3 binormal = normalize( cross( tangent, normal ) );",
"tangent = cross( normal, binormal );", // no normalization required
"mat3 tsb = mat3( tangent, binormal, normal );",
"vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
"normalTex.xy *= uNormalScale;",
"normalTex = normalize( normalTex );",
"vec3 finalNormal = tsb * normalTex;",
"normal = normalize( finalNormal );",
"vec3 viewerDirection = normalize( vViewPosition );",
// point lights
"vec3 totalDiffuseLight = vec3( 0.0 );",
"vec3 totalSpecularLight = vec3( 0.0 );",
"#if NUM_POINT_LIGHTS > 0",
"for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {",
"vec3 pointVector = normalize( pointLights[ i ].direction );",
"float attenuation = calcLightAttenuation( length( lVector ), pointLights[ i ].distance, pointLights[ i ].decay );",
"float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",
"totalDiffuseLight += pointLightColor[ i ] * ( pointDiffuseWeight * attenuation );",
"if ( passID == 1 ) {",
"float pointSpecularWeight = KS_Skin_Specular( normal, pointVector, viewerDirection, uRoughness, uSpecularBrightness );",
"totalSpecularLight += pointLightColor[ i ] * mSpecular.xyz * ( pointSpecularWeight * attenuation );",
"}",
"}",
"#endif",
// directional lights
"#if NUM_DIR_LIGHTS > 0",
"for( int i = 0; i < NUM_DIR_LIGHTS; i++ ) {",
"vec3 dirVector = directionalLights[ i ].direction;",
"float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
"totalDiffuseLight += directionalLights[ i ].color * dirDiffuseWeight;",
"if ( passID == 1 ) {",
"float dirSpecularWeight = KS_Skin_Specular( normal, dirVector, viewerDirection, uRoughness, uSpecularBrightness );",
"totalSpecularLight += directionalLights[ i ].color * mSpecular.xyz * dirSpecularWeight;",
"}",
"}",
"#endif",
"outgoingLight += diffuseColor.rgb * ( totalDiffuseLight + totalSpecularLight );",
"if ( passID == 0 ) {",
"outgoingLight = sqrt( outgoingLight );",
"} else if ( passID == 1 ) {",
//"#define VERSION1",
"#ifdef VERSION1",
"vec3 nonblurColor = sqrt(outgoingLight );",
"#else",
"vec3 nonblurColor = outgoingLight;",
"#endif",
"vec3 blur1Color = texture2D( tBlur1, vUv ).xyz;",
"vec3 blur2Color = texture2D( tBlur2, vUv ).xyz;",
"vec3 blur3Color = texture2D( tBlur3, vUv ).xyz;",
"vec3 blur4Color = texture2D( tBlur4, vUv ).xyz;",
//"gl_FragColor = vec4( blur1Color, gl_FragColor.w );",
//"gl_FragColor = vec4( vec3( 0.22, 0.5, 0.7 ) * nonblurColor + vec3( 0.2, 0.5, 0.3 ) * blur1Color + vec3( 0.58, 0.0, 0.0 ) * blur2Color, gl_FragColor.w );",
//"gl_FragColor = vec4( vec3( 0.25, 0.6, 0.8 ) * nonblurColor + vec3( 0.15, 0.25, 0.2 ) * blur1Color + vec3( 0.15, 0.15, 0.0 ) * blur2Color + vec3( 0.45, 0.0, 0.0 ) * blur3Color, gl_FragColor.w );",
"outgoingLight = vec3( vec3( 0.22, 0.437, 0.635 ) * nonblurColor + ",
"vec3( 0.101, 0.355, 0.365 ) * blur1Color + ",
"vec3( 0.119, 0.208, 0.0 ) * blur2Color + ",
"vec3( 0.114, 0.0, 0.0 ) * blur3Color + ",
"vec3( 0.444, 0.0, 0.0 ) * blur4Color );",
"outgoingLight *= sqrt( colDiffuse.xyz );",
"outgoingLight += ambientLightColor * diffuse * colDiffuse.xyz + totalSpecularLight;",
"#ifndef VERSION1",
"outgoingLight = sqrt( outgoingLight );",
"#endif",
"}",
"gl_FragColor = vec4( outgoingLight, diffuseColor.a );", // TODO, this should be pre-multiplied to allow for bright highlights on very transparent objects
THREE.ShaderChunk[ "fog_fragment" ],
"}"
].join( "\n" ),
vertexShader: [
"#ifdef VERTEX_TEXTURES",
"uniform sampler2D tDisplacement;",
"uniform float uDisplacementScale;",
"uniform float uDisplacementBias;",
"#endif",
"varying vec3 vNormal;",
"varying vec2 vUv;",
"varying vec3 vViewPosition;",
THREE.ShaderChunk[ "common" ],
THREE.ShaderChunk[ "fog_pars_vertex" ],
"void main() {",
"vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
"vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
"vViewPosition = -mvPosition.xyz;",
"vNormal = normalize( normalMatrix * normal );",
"vUv = uv;",
// displacement mapping
"#ifdef VERTEX_TEXTURES",
"vec3 dv = texture2D( tDisplacement, uv ).xyz;",
"float df = uDisplacementScale * dv.x + uDisplacementBias;",
"vec4 displacedPosition = vec4( vNormal.xyz * df, 0.0 ) + mvPosition;",
"gl_Position = projectionMatrix * displacedPosition;",
"#else",
"gl_Position = projectionMatrix * mvPosition;",
"#endif",
THREE.ShaderChunk[ "fog_vertex" ],
"}",
].join( "\n" ),
vertexShaderUV: [
"varying vec3 vNormal;",
"varying vec2 vUv;",
"varying vec3 vViewPosition;",
THREE.ShaderChunk[ "common" ],
"void main() {",
"vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
"vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
"vViewPosition = -mvPosition.xyz;",
"vNormal = normalize( normalMatrix * normal );",
"vUv = uv;",
"gl_Position = vec4( uv.x * 2.0 - 1.0, uv.y * 2.0 - 1.0, 0.0, 1.0 );",
"}"
].join( "\n" )
},
/* ------------------------------------------------------------------------------------------
// Beckmann distribution function
// - to be used in specular term of skin shader
// - render a screen-aligned quad to precompute a 512 x 512 texture
//
// - from http://developer.nvidia.com/node/171
------------------------------------------------------------------------------------------ */
"beckmann" : {
uniforms: {},
vertexShader: [
"varying vec2 vUv;",
"void main() {",
"vUv = uv;",
"gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
"}"
].join( "\n" ),
fragmentShader: [
"varying vec2 vUv;",
"float PHBeckmann( float ndoth, float m ) {",
"float alpha = acos( ndoth );",
"float ta = tan( alpha );",
"float val = 1.0 / ( m * m * pow( ndoth, 4.0 ) ) * exp( -( ta * ta ) / ( m * m ) );",
"return val;",
"}",
"float KSTextureCompute( vec2 tex ) {",
// Scale the value to fit within [0,1] invert upon lookup.
"return 0.5 * pow( PHBeckmann( tex.x, tex.y ), 0.1 );",
"}",
"void main() {",
"float x = KSTextureCompute( vUv );",
"gl_FragColor = vec4( x, x, x, 1.0 );",
"}"
].join( "\n" )
}
};

324
node_modules/three/examples/js/ShaderTerrain.js generated vendored Normal file
View File

@@ -0,0 +1,324 @@
/**
* @author alteredq / http://alteredqualia.com/
*
*/
THREE.ShaderTerrain = {
/* -------------------------------------------------------------------------
// Dynamic terrain shader
// - Blinn-Phong
// - height + normal + diffuse1 + diffuse2 + specular + detail maps
// - point, directional and hemisphere lights (use with "lights: true" material option)
// - shadow maps receiving
------------------------------------------------------------------------- */
'terrain' : {
uniforms: THREE.UniformsUtils.merge( [
THREE.UniformsLib[ "fog" ],
THREE.UniformsLib[ "lights" ],
{
"enableDiffuse1": { value: 0 },
"enableDiffuse2": { value: 0 },
"enableSpecular": { value: 0 },
"enableReflection": { value: 0 },
"tDiffuse1": { value: null },
"tDiffuse2": { value: null },
"tDetail": { value: null },
"tNormal": { value: null },
"tSpecular": { value: null },
"tDisplacement": { value: null },
"uNormalScale": { value: 1.0 },
"uDisplacementBias": { value: 0.0 },
"uDisplacementScale": { value: 1.0 },
"diffuse": { value: new THREE.Color( 0xeeeeee ) },
"specular": { value: new THREE.Color( 0x111111 ) },
"shininess": { value: 30 },
"opacity": { value: 1 },
"uRepeatBase": { value: new THREE.Vector2( 1, 1 ) },
"uRepeatOverlay": { value: new THREE.Vector2( 1, 1 ) },
"uOffset": { value: new THREE.Vector2( 0, 0 ) }
}
] ),
fragmentShader: [
"uniform vec3 diffuse;",
"uniform vec3 specular;",
"uniform float shininess;",
"uniform float opacity;",
"uniform bool enableDiffuse1;",
"uniform bool enableDiffuse2;",
"uniform bool enableSpecular;",
"uniform sampler2D tDiffuse1;",
"uniform sampler2D tDiffuse2;",
"uniform sampler2D tDetail;",
"uniform sampler2D tNormal;",
"uniform sampler2D tSpecular;",
"uniform sampler2D tDisplacement;",
"uniform float uNormalScale;",
"uniform vec2 uRepeatOverlay;",
"uniform vec2 uRepeatBase;",
"uniform vec2 uOffset;",
"varying vec3 vTangent;",
"varying vec3 vBinormal;",
"varying vec3 vNormal;",
"varying vec2 vUv;",
"varying vec3 vViewPosition;",
THREE.ShaderChunk[ "common" ],
THREE.ShaderChunk[ "bsdfs" ],
THREE.ShaderChunk[ "lights_pars" ],
THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
THREE.ShaderChunk[ "fog_pars_fragment" ],
"float calcLightAttenuation( float lightDistance, float cutoffDistance, float decayExponent ) {",
"if ( decayExponent > 0.0 ) {",
"return pow( saturate( - lightDistance / cutoffDistance + 1.0 ), decayExponent );",
"}",
"return 1.0;",
"}",
"void main() {",
"vec3 outgoingLight = vec3( 0.0 );", // outgoing light does not have an alpha, the surface does
"vec4 diffuseColor = vec4( diffuse, opacity );",
"vec3 specularTex = vec3( 1.0 );",
"vec2 uvOverlay = uRepeatOverlay * vUv + uOffset;",
"vec2 uvBase = uRepeatBase * vUv;",
"vec3 normalTex = texture2D( tDetail, uvOverlay ).xyz * 2.0 - 1.0;",
"normalTex.xy *= uNormalScale;",
"normalTex = normalize( normalTex );",
"if( enableDiffuse1 && enableDiffuse2 ) {",
"vec4 colDiffuse1 = texture2D( tDiffuse1, uvOverlay );",
"vec4 colDiffuse2 = texture2D( tDiffuse2, uvOverlay );",
"colDiffuse1 = GammaToLinear( colDiffuse1, float( GAMMA_FACTOR ) );",
"colDiffuse2 = GammaToLinear( colDiffuse2, float( GAMMA_FACTOR ) );",
"diffuseColor *= mix ( colDiffuse1, colDiffuse2, 1.0 - texture2D( tDisplacement, uvBase ) );",
" } else if( enableDiffuse1 ) {",
"diffuseColor *= texture2D( tDiffuse1, uvOverlay );",
"} else if( enableDiffuse2 ) {",
"diffuseColor *= texture2D( tDiffuse2, uvOverlay );",
"}",
"if( enableSpecular )",
"specularTex = texture2D( tSpecular, uvOverlay ).xyz;",
"mat3 tsb = mat3( vTangent, vBinormal, vNormal );",
"vec3 finalNormal = tsb * normalTex;",
"vec3 normal = normalize( finalNormal );",
"vec3 viewPosition = normalize( vViewPosition );",
"vec3 totalDiffuseLight = vec3( 0.0 );",
"vec3 totalSpecularLight = vec3( 0.0 );",
// point lights
"#if NUM_POINT_LIGHTS > 0",
"for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {",
"vec3 lVector = pointLights[ i ].position + vViewPosition.xyz;",
"float attenuation = calcLightAttenuation( length( lVector ), pointLights[ i ].distance, pointLights[ i ].decay );",
"lVector = normalize( lVector );",
"vec3 pointHalfVector = normalize( lVector + viewPosition );",
"float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
"float pointDiffuseWeight = max( dot( normal, lVector ), 0.0 );",
"float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
"totalDiffuseLight += attenuation * pointLights[ i ].color * pointDiffuseWeight;",
"totalSpecularLight += attenuation * pointLights[ i ].color * specular * pointSpecularWeight * pointDiffuseWeight;",
"}",
"#endif",
// directional lights
"#if NUM_DIR_LIGHTS > 0",
"vec3 dirDiffuse = vec3( 0.0 );",
"vec3 dirSpecular = vec3( 0.0 );",
"for( int i = 0; i < NUM_DIR_LIGHTS; i++ ) {",
"vec3 dirVector = directionalLights[ i ].direction;",
"vec3 dirHalfVector = normalize( dirVector + viewPosition );",
"float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
"float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
"float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
"totalDiffuseLight += directionalLights[ i ].color * dirDiffuseWeight;",
"totalSpecularLight += directionalLights[ i ].color * specular * dirSpecularWeight * dirDiffuseWeight;",
"}",
"#endif",
// hemisphere lights
"#if NUM_HEMI_LIGHTS > 0",
"vec3 hemiDiffuse = vec3( 0.0 );",
"vec3 hemiSpecular = vec3( 0.0 );",
"for( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {",
"vec3 lVector = hemisphereLightDirection[ i ];",
// diffuse
"float dotProduct = dot( normal, lVector );",
"float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
"totalDiffuseLight += mix( hemisphereLights[ i ].groundColor, hemisphereLights[ i ].skyColor, hemiDiffuseWeight );",
// specular (sky light)
"float hemiSpecularWeight = 0.0;",
"vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
"float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
"hemiSpecularWeight += specularTex.r * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );",
// specular (ground light)
"vec3 lVectorGround = -lVector;",
"vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
"float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
"hemiSpecularWeight += specularTex.r * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );",
"totalSpecularLight += specular * mix( hemisphereLights[ i ].groundColor, hemisphereLights[ i ].skyColor, hemiDiffuseWeight ) * hemiSpecularWeight * hemiDiffuseWeight;",
"}",
"#endif",
"outgoingLight += diffuseColor.xyz * ( totalDiffuseLight + ambientLightColor + totalSpecularLight );",
"gl_FragColor = vec4( outgoingLight, diffuseColor.a );", // TODO, this should be pre-multiplied to allow for bright highlights on very transparent objects
THREE.ShaderChunk[ "fog_fragment" ],
"}"
].join( "\n" ),
vertexShader: [
"attribute vec4 tangent;",
"uniform vec2 uRepeatBase;",
"uniform sampler2D tNormal;",
"#ifdef VERTEX_TEXTURES",
"uniform sampler2D tDisplacement;",
"uniform float uDisplacementScale;",
"uniform float uDisplacementBias;",
"#endif",
"varying vec3 vTangent;",
"varying vec3 vBinormal;",
"varying vec3 vNormal;",
"varying vec2 vUv;",
"varying vec3 vViewPosition;",
THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
THREE.ShaderChunk[ "fog_pars_vertex" ],
"void main() {",
"vNormal = normalize( normalMatrix * normal );",
// tangent and binormal vectors
"vTangent = normalize( normalMatrix * tangent.xyz );",
"vBinormal = cross( vNormal, vTangent ) * tangent.w;",
"vBinormal = normalize( vBinormal );",
// texture coordinates
"vUv = uv;",
"vec2 uvBase = uv * uRepeatBase;",
// displacement mapping
"#ifdef VERTEX_TEXTURES",
"vec3 dv = texture2D( tDisplacement, uvBase ).xyz;",
"float df = uDisplacementScale * dv.x + uDisplacementBias;",
"vec3 displacedPosition = normal * df + position;",
"vec4 worldPosition = modelMatrix * vec4( displacedPosition, 1.0 );",
"vec4 mvPosition = modelViewMatrix * vec4( displacedPosition, 1.0 );",
"#else",
"vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
"vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
"#endif",
"gl_Position = projectionMatrix * mvPosition;",
"vViewPosition = -mvPosition.xyz;",
"vec3 normalTex = texture2D( tNormal, uvBase ).xyz * 2.0 - 1.0;",
"vNormal = normalMatrix * normalTex;",
THREE.ShaderChunk[ "shadowmap_vertex" ],
THREE.ShaderChunk[ "fog_vertex" ],
"}"
].join( "\n" )
}
};

331
node_modules/three/examples/js/ShaderToon.js generated vendored Normal file
View File

@@ -0,0 +1,331 @@
/**
* @author mrdoob / http://mrdoob.com/
* @author alteredq / http://alteredqualia.com/
*
* ShaderToon currently contains:
*
* toon1
* toon2
* hatching
* dotted
*/
THREE.ShaderToon = {
'toon1' : {
uniforms: {
"uDirLightPos": { value: new THREE.Vector3() },
"uDirLightColor": { value: new THREE.Color( 0xeeeeee ) },
"uAmbientLightColor": { value: new THREE.Color( 0x050505 ) },
"uBaseColor": { value: new THREE.Color( 0xffffff ) }
},
vertexShader: [
"varying vec3 vNormal;",
"varying vec3 vRefract;",
"void main() {",
"vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
"vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
"vec3 worldNormal = normalize ( mat3( modelMatrix[0].xyz, modelMatrix[1].xyz, modelMatrix[2].xyz ) * normal );",
"vNormal = normalize( normalMatrix * normal );",
"vec3 I = worldPosition.xyz - cameraPosition;",
"vRefract = refract( normalize( I ), worldNormal, 1.02 );",
"gl_Position = projectionMatrix * mvPosition;",
"}"
].join( "\n" ),
fragmentShader: [
"uniform vec3 uBaseColor;",
"uniform vec3 uDirLightPos;",
"uniform vec3 uDirLightColor;",
"uniform vec3 uAmbientLightColor;",
"varying vec3 vNormal;",
"varying vec3 vRefract;",
"void main() {",
"float directionalLightWeighting = max( dot( normalize( vNormal ), uDirLightPos ), 0.0);",
"vec3 lightWeighting = uAmbientLightColor + uDirLightColor * directionalLightWeighting;",
"float intensity = smoothstep( - 0.5, 1.0, pow( length(lightWeighting), 20.0 ) );",
"intensity += length(lightWeighting) * 0.2;",
"float cameraWeighting = dot( normalize( vNormal ), vRefract );",
"intensity += pow( 1.0 - length( cameraWeighting ), 6.0 );",
"intensity = intensity * 0.2 + 0.3;",
"if ( intensity < 0.50 ) {",
"gl_FragColor = vec4( 2.0 * intensity * uBaseColor, 1.0 );",
"} else {",
"gl_FragColor = vec4( 1.0 - 2.0 * ( 1.0 - intensity ) * ( 1.0 - uBaseColor ), 1.0 );",
"}",
"}"
].join( "\n" )
},
'toon2' : {
uniforms: {
"uDirLightPos": { value: new THREE.Vector3() },
"uDirLightColor": { value: new THREE.Color( 0xeeeeee ) },
"uAmbientLightColor": { value: new THREE.Color( 0x050505 ) },
"uBaseColor": { value: new THREE.Color( 0xeeeeee ) },
"uLineColor1": { value: new THREE.Color( 0x808080 ) },
"uLineColor2": { value: new THREE.Color( 0x000000 ) },
"uLineColor3": { value: new THREE.Color( 0x000000 ) },
"uLineColor4": { value: new THREE.Color( 0x000000 ) }
},
vertexShader: [
"varying vec3 vNormal;",
"void main() {",
"gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
"vNormal = normalize( normalMatrix * normal );",
"}"
].join( "\n" ),
fragmentShader: [
"uniform vec3 uBaseColor;",
"uniform vec3 uLineColor1;",
"uniform vec3 uLineColor2;",
"uniform vec3 uLineColor3;",
"uniform vec3 uLineColor4;",
"uniform vec3 uDirLightPos;",
"uniform vec3 uDirLightColor;",
"uniform vec3 uAmbientLightColor;",
"varying vec3 vNormal;",
"void main() {",
"float camera = max( dot( normalize( vNormal ), vec3( 0.0, 0.0, 1.0 ) ), 0.4);",
"float light = max( dot( normalize( vNormal ), uDirLightPos ), 0.0);",
"gl_FragColor = vec4( uBaseColor, 1.0 );",
"if ( length(uAmbientLightColor + uDirLightColor * light) < 1.00 ) {",
"gl_FragColor *= vec4( uLineColor1, 1.0 );",
"}",
"if ( length(uAmbientLightColor + uDirLightColor * camera) < 0.50 ) {",
"gl_FragColor *= vec4( uLineColor2, 1.0 );",
"}",
"}"
].join( "\n" )
},
'hatching' : {
uniforms: {
"uDirLightPos": { value: new THREE.Vector3() },
"uDirLightColor": { value: new THREE.Color( 0xeeeeee ) },
"uAmbientLightColor": { value: new THREE.Color( 0x050505 ) },
"uBaseColor": { value: new THREE.Color( 0xffffff ) },
"uLineColor1": { value: new THREE.Color( 0x000000 ) },
"uLineColor2": { value: new THREE.Color( 0x000000 ) },
"uLineColor3": { value: new THREE.Color( 0x000000 ) },
"uLineColor4": { value: new THREE.Color( 0x000000 ) }
},
vertexShader: [
"varying vec3 vNormal;",
"void main() {",
"gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
"vNormal = normalize( normalMatrix * normal );",
"}"
].join( "\n" ),
fragmentShader: [
"uniform vec3 uBaseColor;",
"uniform vec3 uLineColor1;",
"uniform vec3 uLineColor2;",
"uniform vec3 uLineColor3;",
"uniform vec3 uLineColor4;",
"uniform vec3 uDirLightPos;",
"uniform vec3 uDirLightColor;",
"uniform vec3 uAmbientLightColor;",
"varying vec3 vNormal;",
"void main() {",
"float directionalLightWeighting = max( dot( normalize(vNormal), uDirLightPos ), 0.0);",
"vec3 lightWeighting = uAmbientLightColor + uDirLightColor * directionalLightWeighting;",
"gl_FragColor = vec4( uBaseColor, 1.0 );",
"if ( length(lightWeighting) < 1.00 ) {",
"if ( mod(gl_FragCoord.x + gl_FragCoord.y, 10.0) == 0.0) {",
"gl_FragColor = vec4( uLineColor1, 1.0 );",
"}",
"}",
"if ( length(lightWeighting) < 0.75 ) {",
"if (mod(gl_FragCoord.x - gl_FragCoord.y, 10.0) == 0.0) {",
"gl_FragColor = vec4( uLineColor2, 1.0 );",
"}",
"}",
"if ( length(lightWeighting) < 0.50 ) {",
"if (mod(gl_FragCoord.x + gl_FragCoord.y - 5.0, 10.0) == 0.0) {",
"gl_FragColor = vec4( uLineColor3, 1.0 );",
"}",
"}",
"if ( length(lightWeighting) < 0.3465 ) {",
"if (mod(gl_FragCoord.x - gl_FragCoord.y - 5.0, 10.0) == 0.0) {",
"gl_FragColor = vec4( uLineColor4, 1.0 );",
"}",
"}",
"}"
].join( "\n" )
},
'dotted' : {
uniforms: {
"uDirLightPos": { value: new THREE.Vector3() },
"uDirLightColor": { value: new THREE.Color( 0xeeeeee ) },
"uAmbientLightColor": { value: new THREE.Color( 0x050505 ) },
"uBaseColor": { value: new THREE.Color( 0xffffff ) },
"uLineColor1": { value: new THREE.Color( 0x000000 ) }
},
vertexShader: [
"varying vec3 vNormal;",
"void main() {",
"gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
"vNormal = normalize( normalMatrix * normal );",
"}"
].join( "\n" ),
fragmentShader: [
"uniform vec3 uBaseColor;",
"uniform vec3 uLineColor1;",
"uniform vec3 uLineColor2;",
"uniform vec3 uLineColor3;",
"uniform vec3 uLineColor4;",
"uniform vec3 uDirLightPos;",
"uniform vec3 uDirLightColor;",
"uniform vec3 uAmbientLightColor;",
"varying vec3 vNormal;",
"void main() {",
"float directionalLightWeighting = max( dot( normalize(vNormal), uDirLightPos ), 0.0);",
"vec3 lightWeighting = uAmbientLightColor + uDirLightColor * directionalLightWeighting;",
"gl_FragColor = vec4( uBaseColor, 1.0 );",
"if ( length(lightWeighting) < 1.00 ) {",
"if ( ( mod(gl_FragCoord.x, 4.001) + mod(gl_FragCoord.y, 4.0) ) > 6.00 ) {",
"gl_FragColor = vec4( uLineColor1, 1.0 );",
"}",
"}",
"if ( length(lightWeighting) < 0.50 ) {",
"if ( ( mod(gl_FragCoord.x + 2.0, 4.001) + mod(gl_FragCoord.y + 2.0, 4.0) ) > 6.00 ) {",
"gl_FragColor = vec4( uLineColor1, 1.0 );",
"}",
"}",
"}"
].join( "\n" )
}
};

324
node_modules/three/examples/js/SimplexNoise.js generated vendored Normal file
View File

@@ -0,0 +1,324 @@
// Ported from Stefan Gustavson's java implementation
// http://staffwww.itn.liu.se/~stegu/simplexnoise/simplexnoise.pdf
// Read Stefan's excellent paper for details on how this code works.
//
// Sean McCullough banksean@gmail.com
//
// Added 4D noise
// Joshua Koo zz85nus@gmail.com
/**
* You can pass in a random number generator object if you like.
* It is assumed to have a random() method.
*/
var SimplexNoise = function(r) {
if (r == undefined) r = Math;
this.grad3 = [[ 1,1,0 ],[ -1,1,0 ],[ 1,-1,0 ],[ -1,-1,0 ],
[ 1,0,1 ],[ -1,0,1 ],[ 1,0,-1 ],[ -1,0,-1 ],
[ 0,1,1 ],[ 0,-1,1 ],[ 0,1,-1 ],[ 0,-1,-1 ]];
this.grad4 = [[ 0,1,1,1 ], [ 0,1,1,-1 ], [ 0,1,-1,1 ], [ 0,1,-1,-1 ],
[ 0,-1,1,1 ], [ 0,-1,1,-1 ], [ 0,-1,-1,1 ], [ 0,-1,-1,-1 ],
[ 1,0,1,1 ], [ 1,0,1,-1 ], [ 1,0,-1,1 ], [ 1,0,-1,-1 ],
[ -1,0,1,1 ], [ -1,0,1,-1 ], [ -1,0,-1,1 ], [ -1,0,-1,-1 ],
[ 1,1,0,1 ], [ 1,1,0,-1 ], [ 1,-1,0,1 ], [ 1,-1,0,-1 ],
[ -1,1,0,1 ], [ -1,1,0,-1 ], [ -1,-1,0,1 ], [ -1,-1,0,-1 ],
[ 1,1,1,0 ], [ 1,1,-1,0 ], [ 1,-1,1,0 ], [ 1,-1,-1,0 ],
[ -1,1,1,0 ], [ -1,1,-1,0 ], [ -1,-1,1,0 ], [ -1,-1,-1,0 ]];
this.p = [];
for (var i = 0; i < 256; i ++) {
this.p[i] = Math.floor(r.random() * 256);
}
// To remove the need for index wrapping, double the permutation table length
this.perm = [];
for (var i = 0; i < 512; i ++) {
this.perm[i] = this.p[i & 255];
}
// A lookup table to traverse the simplex around a given point in 4D.
// Details can be found where this table is used, in the 4D noise method.
this.simplex = [
[ 0,1,2,3 ],[ 0,1,3,2 ],[ 0,0,0,0 ],[ 0,2,3,1 ],[ 0,0,0,0 ],[ 0,0,0,0 ],[ 0,0,0,0 ],[ 1,2,3,0 ],
[ 0,2,1,3 ],[ 0,0,0,0 ],[ 0,3,1,2 ],[ 0,3,2,1 ],[ 0,0,0,0 ],[ 0,0,0,0 ],[ 0,0,0,0 ],[ 1,3,2,0 ],
[ 0,0,0,0 ],[ 0,0,0,0 ],[ 0,0,0,0 ],[ 0,0,0,0 ],[ 0,0,0,0 ],[ 0,0,0,0 ],[ 0,0,0,0 ],[ 0,0,0,0 ],
[ 1,2,0,3 ],[ 0,0,0,0 ],[ 1,3,0,2 ],[ 0,0,0,0 ],[ 0,0,0,0 ],[ 0,0,0,0 ],[ 2,3,0,1 ],[ 2,3,1,0 ],
[ 1,0,2,3 ],[ 1,0,3,2 ],[ 0,0,0,0 ],[ 0,0,0,0 ],[ 0,0,0,0 ],[ 2,0,3,1 ],[ 0,0,0,0 ],[ 2,1,3,0 ],
[ 0,0,0,0 ],[ 0,0,0,0 ],[ 0,0,0,0 ],[ 0,0,0,0 ],[ 0,0,0,0 ],[ 0,0,0,0 ],[ 0,0,0,0 ],[ 0,0,0,0 ],
[ 2,0,1,3 ],[ 0,0,0,0 ],[ 0,0,0,0 ],[ 0,0,0,0 ],[ 3,0,1,2 ],[ 3,0,2,1 ],[ 0,0,0,0 ],[ 3,1,2,0 ],
[ 2,1,0,3 ],[ 0,0,0,0 ],[ 0,0,0,0 ],[ 0,0,0,0 ],[ 3,1,0,2 ],[ 0,0,0,0 ],[ 3,2,0,1 ],[ 3,2,1,0 ]];
};
SimplexNoise.prototype.dot = function(g, x, y) {
return g[0] * x + g[1] * y;
};
SimplexNoise.prototype.dot3 = function(g, x, y, z) {
return g[0] * x + g[1] * y + g[2] * z;
};
SimplexNoise.prototype.dot4 = function(g, x, y, z, w) {
return g[0] * x + g[1] * y + g[2] * z + g[3] * w;
};
SimplexNoise.prototype.noise = function(xin, yin) {
var n0, n1, n2; // Noise contributions from the three corners
// Skew the input space to determine which simplex cell we're in
var F2 = 0.5 * (Math.sqrt(3.0) - 1.0);
var s = (xin + yin) * F2; // Hairy factor for 2D
var i = Math.floor(xin + s);
var j = Math.floor(yin + s);
var G2 = (3.0 - Math.sqrt(3.0)) / 6.0;
var t = (i + j) * G2;
var X0 = i - t; // Unskew the cell origin back to (x,y) space
var Y0 = j - t;
var x0 = xin - X0; // The x,y distances from the cell origin
var y0 = yin - Y0;
// For the 2D case, the simplex shape is an equilateral triangle.
// Determine which simplex we are in.
var i1, j1; // Offsets for second (middle) corner of simplex in (i,j) coords
if (x0 > y0) {i1 = 1; j1 = 0;} // lower triangle, XY order: (0,0)->(1,0)->(1,1)
else {i1 = 0; j1 = 1;} // upper triangle, YX order: (0,0)->(0,1)->(1,1)
// A step of (1,0) in (i,j) means a step of (1-c,-c) in (x,y), and
// a step of (0,1) in (i,j) means a step of (-c,1-c) in (x,y), where
// c = (3-sqrt(3))/6
var x1 = x0 - i1 + G2; // Offsets for middle corner in (x,y) unskewed coords
var y1 = y0 - j1 + G2;
var x2 = x0 - 1.0 + 2.0 * G2; // Offsets for last corner in (x,y) unskewed coords
var y2 = y0 - 1.0 + 2.0 * G2;
// Work out the hashed gradient indices of the three simplex corners
var ii = i & 255;
var jj = j & 255;
var gi0 = this.perm[ii + this.perm[jj]] % 12;
var gi1 = this.perm[ii + i1 + this.perm[jj + j1]] % 12;
var gi2 = this.perm[ii + 1 + this.perm[jj + 1]] % 12;
// Calculate the contribution from the three corners
var t0 = 0.5 - x0 * x0 - y0 * y0;
if (t0 < 0) n0 = 0.0;
else {
t0 *= t0;
n0 = t0 * t0 * this.dot(this.grad3[gi0], x0, y0); // (x,y) of grad3 used for 2D gradient
}
var t1 = 0.5 - x1 * x1 - y1 * y1;
if (t1 < 0) n1 = 0.0;
else {
t1 *= t1;
n1 = t1 * t1 * this.dot(this.grad3[gi1], x1, y1);
}
var t2 = 0.5 - x2 * x2 - y2 * y2;
if (t2 < 0) n2 = 0.0;
else {
t2 *= t2;
n2 = t2 * t2 * this.dot(this.grad3[gi2], x2, y2);
}
// Add contributions from each corner to get the final noise value.
// The result is scaled to return values in the interval [-1,1].
return 70.0 * (n0 + n1 + n2);
};
// 3D simplex noise
SimplexNoise.prototype.noise3d = function(xin, yin, zin) {
var n0, n1, n2, n3; // Noise contributions from the four corners
// Skew the input space to determine which simplex cell we're in
var F3 = 1.0 / 3.0;
var s = (xin + yin + zin) * F3; // Very nice and simple skew factor for 3D
var i = Math.floor(xin + s);
var j = Math.floor(yin + s);
var k = Math.floor(zin + s);
var G3 = 1.0 / 6.0; // Very nice and simple unskew factor, too
var t = (i + j + k) * G3;
var X0 = i - t; // Unskew the cell origin back to (x,y,z) space
var Y0 = j - t;
var Z0 = k - t;
var x0 = xin - X0; // The x,y,z distances from the cell origin
var y0 = yin - Y0;
var z0 = zin - Z0;
// For the 3D case, the simplex shape is a slightly irregular tetrahedron.
// Determine which simplex we are in.
var i1, j1, k1; // Offsets for second corner of simplex in (i,j,k) coords
var i2, j2, k2; // Offsets for third corner of simplex in (i,j,k) coords
if (x0 >= y0) {
if (y0 >= z0)
{ i1 = 1; j1 = 0; k1 = 0; i2 = 1; j2 = 1; k2 = 0; } // X Y Z order
else if (x0 >= z0) { i1 = 1; j1 = 0; k1 = 0; i2 = 1; j2 = 0; k2 = 1; } // X Z Y order
else { i1 = 0; j1 = 0; k1 = 1; i2 = 1; j2 = 0; k2 = 1; } // Z X Y order
}
else { // x0<y0
if (y0 < z0) { i1 = 0; j1 = 0; k1 = 1; i2 = 0; j2 = 1; k2 = 1; } // Z Y X order
else if (x0 < z0) { i1 = 0; j1 = 1; k1 = 0; i2 = 0; j2 = 1; k2 = 1; } // Y Z X order
else { i1 = 0; j1 = 1; k1 = 0; i2 = 1; j2 = 1; k2 = 0; } // Y X Z order
}
// A step of (1,0,0) in (i,j,k) means a step of (1-c,-c,-c) in (x,y,z),
// a step of (0,1,0) in (i,j,k) means a step of (-c,1-c,-c) in (x,y,z), and
// a step of (0,0,1) in (i,j,k) means a step of (-c,-c,1-c) in (x,y,z), where
// c = 1/6.
var x1 = x0 - i1 + G3; // Offsets for second corner in (x,y,z) coords
var y1 = y0 - j1 + G3;
var z1 = z0 - k1 + G3;
var x2 = x0 - i2 + 2.0 * G3; // Offsets for third corner in (x,y,z) coords
var y2 = y0 - j2 + 2.0 * G3;
var z2 = z0 - k2 + 2.0 * G3;
var x3 = x0 - 1.0 + 3.0 * G3; // Offsets for last corner in (x,y,z) coords
var y3 = y0 - 1.0 + 3.0 * G3;
var z3 = z0 - 1.0 + 3.0 * G3;
// Work out the hashed gradient indices of the four simplex corners
var ii = i & 255;
var jj = j & 255;
var kk = k & 255;
var gi0 = this.perm[ii + this.perm[jj + this.perm[kk]]] % 12;
var gi1 = this.perm[ii + i1 + this.perm[jj + j1 + this.perm[kk + k1]]] % 12;
var gi2 = this.perm[ii + i2 + this.perm[jj + j2 + this.perm[kk + k2]]] % 12;
var gi3 = this.perm[ii + 1 + this.perm[jj + 1 + this.perm[kk + 1]]] % 12;
// Calculate the contribution from the four corners
var t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0;
if (t0 < 0) n0 = 0.0;
else {
t0 *= t0;
n0 = t0 * t0 * this.dot3(this.grad3[gi0], x0, y0, z0);
}
var t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1;
if (t1 < 0) n1 = 0.0;
else {
t1 *= t1;
n1 = t1 * t1 * this.dot3(this.grad3[gi1], x1, y1, z1);
}
var t2 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2;
if (t2 < 0) n2 = 0.0;
else {
t2 *= t2;
n2 = t2 * t2 * this.dot3(this.grad3[gi2], x2, y2, z2);
}
var t3 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3;
if (t3 < 0) n3 = 0.0;
else {
t3 *= t3;
n3 = t3 * t3 * this.dot3(this.grad3[gi3], x3, y3, z3);
}
// Add contributions from each corner to get the final noise value.
// The result is scaled to stay just inside [-1,1]
return 32.0 * (n0 + n1 + n2 + n3);
};
// 4D simplex noise
SimplexNoise.prototype.noise4d = function( x, y, z, w ) {
// For faster and easier lookups
var grad4 = this.grad4;
var simplex = this.simplex;
var perm = this.perm;
// The skewing and unskewing factors are hairy again for the 4D case
var F4 = (Math.sqrt(5.0) - 1.0) / 4.0;
var G4 = (5.0 - Math.sqrt(5.0)) / 20.0;
var n0, n1, n2, n3, n4; // Noise contributions from the five corners
// Skew the (x,y,z,w) space to determine which cell of 24 simplices we're in
var s = (x + y + z + w) * F4; // Factor for 4D skewing
var i = Math.floor(x + s);
var j = Math.floor(y + s);
var k = Math.floor(z + s);
var l = Math.floor(w + s);
var t = (i + j + k + l) * G4; // Factor for 4D unskewing
var X0 = i - t; // Unskew the cell origin back to (x,y,z,w) space
var Y0 = j - t;
var Z0 = k - t;
var W0 = l - t;
var x0 = x - X0; // The x,y,z,w distances from the cell origin
var y0 = y - Y0;
var z0 = z - Z0;
var w0 = w - W0;
// For the 4D case, the simplex is a 4D shape I won't even try to describe.
// To find out which of the 24 possible simplices we're in, we need to
// determine the magnitude ordering of x0, y0, z0 and w0.
// The method below is a good way of finding the ordering of x,y,z,w and
// then find the correct traversal order for the simplex were in.
// First, six pair-wise comparisons are performed between each possible pair
// of the four coordinates, and the results are used to add up binary bits
// for an integer index.
var c1 = (x0 > y0) ? 32 : 0;
var c2 = (x0 > z0) ? 16 : 0;
var c3 = (y0 > z0) ? 8 : 0;
var c4 = (x0 > w0) ? 4 : 0;
var c5 = (y0 > w0) ? 2 : 0;
var c6 = (z0 > w0) ? 1 : 0;
var c = c1 + c2 + c3 + c4 + c5 + c6;
var i1, j1, k1, l1; // The integer offsets for the second simplex corner
var i2, j2, k2, l2; // The integer offsets for the third simplex corner
var i3, j3, k3, l3; // The integer offsets for the fourth simplex corner
// simplex[c] is a 4-vector with the numbers 0, 1, 2 and 3 in some order.
// Many values of c will never occur, since e.g. x>y>z>w makes x<z, y<w and x<w
// impossible. Only the 24 indices which have non-zero entries make any sense.
// We use a thresholding to set the coordinates in turn from the largest magnitude.
// The number 3 in the "simplex" array is at the position of the largest coordinate.
i1 = simplex[c][0] >= 3 ? 1 : 0;
j1 = simplex[c][1] >= 3 ? 1 : 0;
k1 = simplex[c][2] >= 3 ? 1 : 0;
l1 = simplex[c][3] >= 3 ? 1 : 0;
// The number 2 in the "simplex" array is at the second largest coordinate.
i2 = simplex[c][0] >= 2 ? 1 : 0;
j2 = simplex[c][1] >= 2 ? 1 : 0; k2 = simplex[c][2] >= 2 ? 1 : 0;
l2 = simplex[c][3] >= 2 ? 1 : 0;
// The number 1 in the "simplex" array is at the second smallest coordinate.
i3 = simplex[c][0] >= 1 ? 1 : 0;
j3 = simplex[c][1] >= 1 ? 1 : 0;
k3 = simplex[c][2] >= 1 ? 1 : 0;
l3 = simplex[c][3] >= 1 ? 1 : 0;
// The fifth corner has all coordinate offsets = 1, so no need to look that up.
var x1 = x0 - i1 + G4; // Offsets for second corner in (x,y,z,w) coords
var y1 = y0 - j1 + G4;
var z1 = z0 - k1 + G4;
var w1 = w0 - l1 + G4;
var x2 = x0 - i2 + 2.0 * G4; // Offsets for third corner in (x,y,z,w) coords
var y2 = y0 - j2 + 2.0 * G4;
var z2 = z0 - k2 + 2.0 * G4;
var w2 = w0 - l2 + 2.0 * G4;
var x3 = x0 - i3 + 3.0 * G4; // Offsets for fourth corner in (x,y,z,w) coords
var y3 = y0 - j3 + 3.0 * G4;
var z3 = z0 - k3 + 3.0 * G4;
var w3 = w0 - l3 + 3.0 * G4;
var x4 = x0 - 1.0 + 4.0 * G4; // Offsets for last corner in (x,y,z,w) coords
var y4 = y0 - 1.0 + 4.0 * G4;
var z4 = z0 - 1.0 + 4.0 * G4;
var w4 = w0 - 1.0 + 4.0 * G4;
// Work out the hashed gradient indices of the five simplex corners
var ii = i & 255;
var jj = j & 255;
var kk = k & 255;
var ll = l & 255;
var gi0 = perm[ii + perm[jj + perm[kk + perm[ll]]]] % 32;
var gi1 = perm[ii + i1 + perm[jj + j1 + perm[kk + k1 + perm[ll + l1]]]] % 32;
var gi2 = perm[ii + i2 + perm[jj + j2 + perm[kk + k2 + perm[ll + l2]]]] % 32;
var gi3 = perm[ii + i3 + perm[jj + j3 + perm[kk + k3 + perm[ll + l3]]]] % 32;
var gi4 = perm[ii + 1 + perm[jj + 1 + perm[kk + 1 + perm[ll + 1]]]] % 32;
// Calculate the contribution from the five corners
var t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0 - w0 * w0;
if (t0 < 0) n0 = 0.0;
else {
t0 *= t0;
n0 = t0 * t0 * this.dot4(grad4[gi0], x0, y0, z0, w0);
}
var t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1 - w1 * w1;
if (t1 < 0) n1 = 0.0;
else {
t1 *= t1;
n1 = t1 * t1 * this.dot4(grad4[gi1], x1, y1, z1, w1);
}
var t2 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2 - w2 * w2;
if (t2 < 0) n2 = 0.0;
else {
t2 *= t2;
n2 = t2 * t2 * this.dot4(grad4[gi2], x2, y2, z2, w2);
} var t3 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3 - w3 * w3;
if (t3 < 0) n3 = 0.0;
else {
t3 *= t3;
n3 = t3 * t3 * this.dot4(grad4[gi3], x3, y3, z3, w3);
}
var t4 = 0.6 - x4 * x4 - y4 * y4 - z4 * z4 - w4 * w4;
if (t4 < 0) n4 = 0.0;
else {
t4 *= t4;
n4 = t4 * t4 * this.dot4(grad4[gi4], x4, y4, z4, w4);
}
// Sum up and scale the result to cover the range [-1,1]
return 27.0 * (n0 + n1 + n2 + n3 + n4);
};

238
node_modules/three/examples/js/SkyShader.js generated vendored Normal file
View File

@@ -0,0 +1,238 @@
/**
* @author zz85 / https://github.com/zz85
*
* Based on "A Practical Analytic Model for Daylight"
* aka The Preetham Model, the de facto standard analytic skydome model
* http://www.cs.utah.edu/~shirley/papers/sunsky/sunsky.pdf
*
* First implemented by Simon Wallner
* http://www.simonwallner.at/projects/atmospheric-scattering
*
* Improved by Martin Upitis
* http://blenderartists.org/forum/showthread.php?245954-preethams-sky-impementation-HDR
*
* Three.js integration by zz85 http://twitter.com/blurspline
*/
THREE.ShaderLib[ 'sky' ] = {
uniforms: {
luminance: { value: 1 },
turbidity: { value: 2 },
rayleigh: { value: 1 },
mieCoefficient: { value: 0.005 },
mieDirectionalG: { value: 0.8 },
sunPosition: { value: new THREE.Vector3() }
},
vertexShader: [
"uniform vec3 sunPosition;",
"uniform float rayleigh;",
"uniform float turbidity;",
"uniform float mieCoefficient;",
"varying vec3 vWorldPosition;",
"varying vec3 vSunDirection;",
"varying float vSunfade;",
"varying vec3 vBetaR;",
"varying vec3 vBetaM;",
"varying float vSunE;",
"const vec3 up = vec3( 0.0, 1.0, 0.0 );",
// constants for atmospheric scattering
"const float e = 2.71828182845904523536028747135266249775724709369995957;",
"const float pi = 3.141592653589793238462643383279502884197169;",
// wavelength of used primaries, according to preetham
"const vec3 lambda = vec3( 680E-9, 550E-9, 450E-9 );",
// this pre-calcuation replaces older TotalRayleigh(vec3 lambda) function:
// (8.0 * pow(pi, 3.0) * pow(pow(n, 2.0) - 1.0, 2.0) * (6.0 + 3.0 * pn)) / (3.0 * N * pow(lambda, vec3(4.0)) * (6.0 - 7.0 * pn))
"const vec3 totalRayleigh = vec3( 5.804542996261093E-6, 1.3562911419845635E-5, 3.0265902468824876E-5 );",
// mie stuff
// K coefficient for the primaries
"const float v = 4.0;",
"const vec3 K = vec3( 0.686, 0.678, 0.666 );",
// MieConst = pi * pow( ( 2.0 * pi ) / lambda, vec3( v - 2.0 ) ) * K
"const vec3 MieConst = vec3( 1.8399918514433978E14, 2.7798023919660528E14, 4.0790479543861094E14 );",
// earth shadow hack
// cutoffAngle = pi / 1.95;
"const float cutoffAngle = 1.6110731556870734;",
"const float steepness = 1.5;",
"const float EE = 1000.0;",
"float sunIntensity( float zenithAngleCos )",
"{",
"zenithAngleCos = clamp( zenithAngleCos, -1.0, 1.0 );",
"return EE * max( 0.0, 1.0 - pow( e, -( ( cutoffAngle - acos( zenithAngleCos ) ) / steepness ) ) );",
"}",
"vec3 totalMie( float T )",
"{",
"float c = ( 0.2 * T ) * 10E-18;",
"return 0.434 * c * MieConst;",
"}",
"void main() {",
"vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
"vWorldPosition = worldPosition.xyz;",
"gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
"vSunDirection = normalize( sunPosition );",
"vSunE = sunIntensity( dot( vSunDirection, up ) );",
"vSunfade = 1.0 - clamp( 1.0 - exp( ( sunPosition.y / 450000.0 ) ), 0.0, 1.0 );",
"float rayleighCoefficient = rayleigh - ( 1.0 * ( 1.0 - vSunfade ) );",
// extinction (absorbtion + out scattering)
// rayleigh coefficients
"vBetaR = totalRayleigh * rayleighCoefficient;",
// mie coefficients
"vBetaM = totalMie( turbidity ) * mieCoefficient;",
"}"
].join( "\n" ),
fragmentShader: [
"varying vec3 vWorldPosition;",
"varying vec3 vSunDirection;",
"varying float vSunfade;",
"varying vec3 vBetaR;",
"varying vec3 vBetaM;",
"varying float vSunE;",
"uniform float luminance;",
"uniform float mieDirectionalG;",
"const vec3 cameraPos = vec3( 0.0, 0.0, 0.0 );",
// constants for atmospheric scattering
"const float pi = 3.141592653589793238462643383279502884197169;",
"const float n = 1.0003;", // refractive index of air
"const float N = 2.545E25;", // number of molecules per unit volume for air at
// 288.15K and 1013mb (sea level -45 celsius)
// optical length at zenith for molecules
"const float rayleighZenithLength = 8.4E3;",
"const float mieZenithLength = 1.25E3;",
"const vec3 up = vec3( 0.0, 1.0, 0.0 );",
// 66 arc seconds -> degrees, and the cosine of that
"const float sunAngularDiameterCos = 0.999956676946448443553574619906976478926848692873900859324;",
// 3.0 / ( 16.0 * pi )
"const float THREE_OVER_SIXTEENPI = 0.05968310365946075;",
// 1.0 / ( 4.0 * pi )
"const float ONE_OVER_FOURPI = 0.07957747154594767;",
"float rayleighPhase( float cosTheta )",
"{",
"return THREE_OVER_SIXTEENPI * ( 1.0 + pow( cosTheta, 2.0 ) );",
"}",
"float hgPhase( float cosTheta, float g )",
"{",
"float g2 = pow( g, 2.0 );",
"float inverse = 1.0 / pow( 1.0 - 2.0 * g * cosTheta + g2, 1.5 );",
"return ONE_OVER_FOURPI * ( ( 1.0 - g2 ) * inverse );",
"}",
// Filmic ToneMapping http://filmicgames.com/archives/75
"const float A = 0.15;",
"const float B = 0.50;",
"const float C = 0.10;",
"const float D = 0.20;",
"const float E = 0.02;",
"const float F = 0.30;",
"const float whiteScale = 1.0748724675633854;", // 1.0 / Uncharted2Tonemap(1000.0)
"vec3 Uncharted2Tonemap( vec3 x )",
"{",
"return ( ( x * ( A * x + C * B ) + D * E ) / ( x * ( A * x + B ) + D * F ) ) - E / F;",
"}",
"void main() ",
"{",
// optical length
// cutoff angle at 90 to avoid singularity in next formula.
"float zenithAngle = acos( max( 0.0, dot( up, normalize( vWorldPosition - cameraPos ) ) ) );",
"float inverse = 1.0 / ( cos( zenithAngle ) + 0.15 * pow( 93.885 - ( ( zenithAngle * 180.0 ) / pi ), -1.253 ) );",
"float sR = rayleighZenithLength * inverse;",
"float sM = mieZenithLength * inverse;",
// combined extinction factor
"vec3 Fex = exp( -( vBetaR * sR + vBetaM * sM ) );",
// in scattering
"float cosTheta = dot( normalize( vWorldPosition - cameraPos ), vSunDirection );",
"float rPhase = rayleighPhase( cosTheta * 0.5 + 0.5 );",
"vec3 betaRTheta = vBetaR * rPhase;",
"float mPhase = hgPhase( cosTheta, mieDirectionalG );",
"vec3 betaMTheta = vBetaM * mPhase;",
"vec3 Lin = pow( vSunE * ( ( betaRTheta + betaMTheta ) / ( vBetaR + vBetaM ) ) * ( 1.0 - Fex ), vec3( 1.5 ) );",
"Lin *= mix( vec3( 1.0 ), pow( vSunE * ( ( betaRTheta + betaMTheta ) / ( vBetaR + vBetaM ) ) * Fex, vec3( 1.0 / 2.0 ) ), clamp( pow( 1.0 - dot( up, vSunDirection ), 5.0 ), 0.0, 1.0 ) );",
//nightsky
"vec3 direction = normalize( vWorldPosition - cameraPos );",
"float theta = acos( direction.y ); // elevation --> y-axis, [-pi/2, pi/2]",
"float phi = atan( direction.z, direction.x ); // azimuth --> x-axis [-pi/2, pi/2]",
"vec2 uv = vec2( phi, theta ) / vec2( 2.0 * pi, pi ) + vec2( 0.5, 0.0 );",
"vec3 L0 = vec3( 0.1 ) * Fex;",
// composition + solar disc
"float sundisk = smoothstep( sunAngularDiameterCos, sunAngularDiameterCos + 0.00002, cosTheta );",
"L0 += ( vSunE * 19000.0 * Fex ) * sundisk;",
"vec3 texColor = ( Lin + L0 ) * 0.04 + vec3( 0.0, 0.0003, 0.00075 );",
"vec3 curr = Uncharted2Tonemap( ( log2( 2.0 / pow( luminance, 4.0 ) ) ) * texColor );",
"vec3 color = curr * whiteScale;",
"vec3 retColor = pow( color, vec3( 1.0 / ( 1.2 + ( 1.2 * vSunfade ) ) ) );",
"gl_FragColor.rgb = retColor;",
"gl_FragColor.a = 1.0;",
"}"
].join( "\n" )
};
THREE.Sky = function () {
var skyShader = THREE.ShaderLib[ "sky" ];
var skyUniforms = THREE.UniformsUtils.clone( skyShader.uniforms );
var skyMat = new THREE.ShaderMaterial( {
fragmentShader: skyShader.fragmentShader,
vertexShader: skyShader.vertexShader,
uniforms: skyUniforms,
side: THREE.BackSide
} );
var skyGeo = new THREE.SphereBufferGeometry( 450000, 32, 15 );
var skyMesh = new THREE.Mesh( skyGeo, skyMat );
// Expose variables
this.mesh = skyMesh;
this.uniforms = skyUniforms;
};

280
node_modules/three/examples/js/TimelinerController.js generated vendored Normal file
View File

@@ -0,0 +1,280 @@
/**
* Controller class for the Timeliner GUI.
*
* Timeliner GUI library (required to use this class):
*
* ./libs/timeliner_gui.min.js
*
* Source code:
*
* https://github.com/tschw/timeliner_gui
* https://github.com/zz85/timeliner (fork's origin)
*
* @author tschw
*
*/
THREE.TimelinerController = function TimelinerController( scene, trackInfo, onUpdate ) {
this._scene = scene;
this._trackInfo = trackInfo;
this._onUpdate = onUpdate;
this._mixer = new THREE.AnimationMixer( scene );
this._clip = null;
this._action = null;
this._tracks = {};
this._propRefs = {};
this._channelNames = [];
};
THREE.TimelinerController.prototype = {
constructor: THREE.TimelinerController,
init: function( timeliner ) {
var tracks = [],
trackInfo = this._trackInfo;
for ( var i = 0, n = trackInfo.length; i !== n; ++ i ) {
var spec = trackInfo[ i ];
tracks.push( this._addTrack(
spec.type, spec.propertyPath,
spec.initialValue, spec.interpolation ) );
}
this._clip = new THREE.AnimationClip( 'editclip', 0, tracks );
this._action = this._mixer.clipAction( this._clip ).play();
},
setDisplayTime: function( time ) {
this._action.time = time;
this._mixer.update( 0 );
this._onUpdate();
},
setDuration: function( duration ) {
this._clip.duration = duration;
},
getChannelNames: function() {
return this._channelNames;
},
getChannelKeyTimes: function( channelName ) {
return this._tracks[ channelName ].times;
},
setKeyframe: function( channelName, time ) {
var track = this._tracks[ channelName ],
times = track.times,
index = Timeliner.binarySearch( times, time ),
values = track.values,
stride = track.getValueSize(),
offset = index * stride;
if ( index < 0 ) {
// insert new keyframe
index = ~ index;
offset = index * stride;
var nTimes = times.length + 1,
nValues = values.length + stride;
for ( var i = nTimes - 1; i !== index; -- i ) {
times[ i ] = times[ i - 1 ];
}
for ( var i = nValues - 1,
e = offset + stride - 1; i !== e; -- i ) {
values[ i ] = values[ i - stride ];
}
}
times[ index ] = time;
this._propRefs[ channelName ].getValue( values, offset );
},
delKeyframe: function( channelName, time ) {
var track = this._tracks[ channelName ],
times = track.times,
index = Timeliner.binarySearch( times, time );
// we disallow to remove the keyframe when it is the last one we have,
// since the animation system is designed to always produce a defined
// state
if ( times.length > 1 && index >= 0 ) {
var nTimes = times.length - 1,
values = track.values,
stride = track.getValueSize(),
nValues = values.length - stride;
// note: no track.getValueSize when array sizes are out of sync
for ( var i = index; i !== nTimes; ++ i ) {
times[ i ] = times[ i + 1 ];
}
times.pop();
for ( var offset = index * stride; offset !== nValues; ++ offset ) {
values[ offset ] = values[ offset + stride ];
}
values.length = nValues;
}
},
moveKeyframe: function( channelName, time, delta, moveRemaining ) {
var track = this._tracks[ channelName ],
times = track.times,
index = Timeliner.binarySearch( times, time );
if ( index >= 0 ) {
var endAt = moveRemaining ? times.length : index + 1,
needsSort = times[ index - 1 ] <= time ||
! moveRemaining && time >= times[ index + 1 ];
while ( index !== endAt ) times[ index ++ ] += delta;
if ( needsSort ) this._sort( track );
}
},
serialize: function() {
var result = {
duration: this._clip.duration,
channels: {}
},
names = this._channelNames,
tracks = this._tracks,
channels = result.channels;
for ( var i = 0, n = names.length; i !== n; ++ i ) {
var name = names[ i ],
track = tracks[ name ];
channels[ name ] = {
times: track.times,
values: track.values
};
}
return result;
},
deserialize: function( structs ) {
var names = this._channelNames,
tracks = this._tracks,
channels = structs.channels;
this.setDuration( structs.duration );
for ( var i = 0, n = names.length; i !== n; ++ i ) {
var name = names[ i ],
track = tracks[ name ];
data = channels[ name ];
this._setArray( track.times, data.times );
this._setArray( track.values, data.values );
}
// update display
this.setDisplayTime( this._mixer.time );
},
_sort: function( track ) {
var times = track.times,
order = THREE.AnimationUtils.getKeyframeOrder( times );
this._setArray( times,
THREE.AnimationUtils.sortedArray( times, 1, order ) );
var values = track.values,
stride = track.getValueSize();
this._setArray( values,
THREE.AnimationUtils.sortedArray( values, stride, order ) );
},
_setArray: function( dst, src ) {
dst.length = 0;
dst.push.apply( dst, src );
},
_addTrack: function( type, prop, initialValue, interpolation ) {
var track = new type(
prop, [ 0 ], initialValue, interpolation );
// data must be in JS arrays so it can be resized
track.times = Array.prototype.slice.call( track.times );
track.values = Array.prototype.slice.call( track.values );
this._channelNames.push( prop );
this._tracks[ prop ] = track;
// for recording the state:
this._propRefs[ prop ] =
new THREE.PropertyBinding( this._scene, prop );
return track;
}
};

602
node_modules/three/examples/js/TypedArrayUtils.js generated vendored Normal file
View File

@@ -0,0 +1,602 @@
THREE.TypedArrayUtils = {};
/**
* In-place quicksort for typed arrays (e.g. for Float32Array)
* provides fast sorting
* useful e.g. for a custom shader and/or BufferGeometry
*
* @author Roman Bolzern <roman.bolzern@fhnw.ch>, 2013
* @author I4DS http://www.fhnw.ch/i4ds, 2013
* @license MIT License <http://www.opensource.org/licenses/mit-license.php>
*
* Complexity: http://bigocheatsheet.com/ see Quicksort
*
* Example:
* points: [x, y, z, x, y, z, x, y, z, ...]
* eleSize: 3 //because of (x, y, z)
* orderElement: 0 //order according to x
*/
THREE.TypedArrayUtils.quicksortIP = function ( arr, eleSize, orderElement ) {
var stack = [];
var sp = - 1;
var left = 0;
var right = arr.length / eleSize - 1;
var tmp = 0.0, x = 0, y = 0;
var swapF = function ( a, b ) {
a *= eleSize; b *= eleSize;
for ( y = 0; y < eleSize; y ++ ) {
tmp = arr[ a + y ];
arr[ a + y ] = arr[ b + y ];
arr[ b + y ] = tmp;
}
};
var i, j, swap = new Float32Array( eleSize ), temp = new Float32Array( eleSize );
while ( true ) {
if ( right - left <= 25 ) {
for ( j = left + 1; j <= right; j ++ ) {
for ( x = 0; x < eleSize; x ++ ) {
swap[ x ] = arr[ j * eleSize + x ];
}
i = j - 1;
while ( i >= left && arr[ i * eleSize + orderElement ] > swap[ orderElement ] ) {
for ( x = 0; x < eleSize; x ++ ) {
arr[ ( i + 1 ) * eleSize + x ] = arr[ i * eleSize + x ];
}
i --;
}
for ( x = 0; x < eleSize; x ++ ) {
arr[ ( i + 1 ) * eleSize + x ] = swap[ x ];
}
}
if ( sp == - 1 ) break;
right = stack[ sp -- ]; //?
left = stack[ sp -- ];
} else {
var median = ( left + right ) >> 1;
i = left + 1;
j = right;
swapF( median, i );
if ( arr[ left * eleSize + orderElement ] > arr[ right * eleSize + orderElement ] ) {
swapF( left, right );
}
if ( arr[ i * eleSize + orderElement ] > arr[ right * eleSize + orderElement ] ) {
swapF( i, right );
}
if ( arr[ left * eleSize + orderElement ] > arr[ i * eleSize + orderElement ] ) {
swapF( left, i );
}
for ( x = 0; x < eleSize; x ++ ) {
temp[ x ] = arr[ i * eleSize + x ];
}
while ( true ) {
do i ++; while ( arr[ i * eleSize + orderElement ] < temp[ orderElement ] );
do j --; while ( arr[ j * eleSize + orderElement ] > temp[ orderElement ] );
if ( j < i ) break;
swapF( i, j );
}
for ( x = 0; x < eleSize; x ++ ) {
arr[ ( left + 1 ) * eleSize + x ] = arr[ j * eleSize + x ];
arr[ j * eleSize + x ] = temp[ x ];
}
if ( right - i + 1 >= j - left ) {
stack[ ++ sp ] = i;
stack[ ++ sp ] = right;
right = j - 1;
} else {
stack[ ++ sp ] = left;
stack[ ++ sp ] = j - 1;
left = i;
}
}
}
return arr;
};
/**
* k-d Tree for typed arrays (e.g. for Float32Array), in-place
* provides fast nearest neighbour search
* useful e.g. for a custom shader and/or BufferGeometry, saves tons of memory
* has no insert and remove, only buildup and neares neighbour search
*
* Based on https://github.com/ubilabs/kd-tree-javascript by Ubilabs
*
* @author Roman Bolzern <roman.bolzern@fhnw.ch>, 2013
* @author I4DS http://www.fhnw.ch/i4ds, 2013
* @license MIT License <http://www.opensource.org/licenses/mit-license.php>
*
* Requires typed array quicksort
*
* Example:
* points: [x, y, z, x, y, z, x, y, z, ...]
* metric: function(a, b){ return Math.pow(a[0] - b[0], 2) + Math.pow(a[1] - b[1], 2) + Math.pow(a[2] - b[2], 2); } //Manhatten distance
* eleSize: 3 //because of (x, y, z)
*
* Further information (including mathematical properties)
* http://en.wikipedia.org/wiki/Binary_tree
* http://en.wikipedia.org/wiki/K-d_tree
*
* If you want to further minimize memory usage, remove Node.depth and replace in search algorithm with a traversal to root node (see comments at THREE.TypedArrayUtils.Kdtree.prototype.Node)
*/
THREE.TypedArrayUtils.Kdtree = function ( points, metric, eleSize ) {
var self = this;
var maxDepth = 0;
var getPointSet = function ( points, pos ) {
return points.subarray( pos * eleSize, pos * eleSize + eleSize );
};
function buildTree( points, depth, parent, pos ) {
var dim = depth % eleSize,
median,
node,
plength = points.length / eleSize;
if ( depth > maxDepth ) maxDepth = depth;
if ( plength === 0 ) return null;
if ( plength === 1 ) {
return new self.Node( getPointSet( points, 0 ), depth, parent, pos );
}
THREE.TypedArrayUtils.quicksortIP( points, eleSize, dim );
median = Math.floor( plength / 2 );
node = new self.Node( getPointSet( points, median ), depth, parent, median + pos );
node.left = buildTree( points.subarray( 0, median * eleSize ), depth + 1, node, pos );
node.right = buildTree( points.subarray( ( median + 1 ) * eleSize, points.length ), depth + 1, node, pos + median + 1 );
return node;
}
this.root = buildTree( points, 0, null, 0 );
this.getMaxDepth = function () {
return maxDepth;
};
this.nearest = function ( point, maxNodes, maxDistance ) {
/* point: array of size eleSize
maxNodes: max amount of nodes to return
maxDistance: maximum distance to point result nodes should have
condition (not implemented): function to test node before it's added to the result list, e.g. test for view frustum
*/
var i,
result,
bestNodes;
bestNodes = new THREE.TypedArrayUtils.Kdtree.BinaryHeap(
function ( e ) {
return - e[ 1 ];
}
);
function nearestSearch( node ) {
var bestChild,
dimension = node.depth % eleSize,
ownDistance = metric( point, node.obj ),
linearDistance = 0,
otherChild,
i,
linearPoint = [];
function saveNode( node, distance ) {
bestNodes.push( [ node, distance ] );
if ( bestNodes.size() > maxNodes ) {
bestNodes.pop();
}
}
for ( i = 0; i < eleSize; i += 1 ) {
if ( i === node.depth % eleSize ) {
linearPoint[ i ] = point[ i ];
} else {
linearPoint[ i ] = node.obj[ i ];
}
}
linearDistance = metric( linearPoint, node.obj );
// if it's a leaf
if ( node.right === null && node.left === null ) {
if ( bestNodes.size() < maxNodes || ownDistance < bestNodes.peek()[ 1 ] ) {
saveNode( node, ownDistance );
}
return;
}
if ( node.right === null ) {
bestChild = node.left;
} else if ( node.left === null ) {
bestChild = node.right;
} else {
if ( point[ dimension ] < node.obj[ dimension ] ) {
bestChild = node.left;
} else {
bestChild = node.right;
}
}
// recursive search
nearestSearch( bestChild );
if ( bestNodes.size() < maxNodes || ownDistance < bestNodes.peek()[ 1 ] ) {
saveNode( node, ownDistance );
}
// if there's still room or the current distance is nearer than the best distance
if ( bestNodes.size() < maxNodes || Math.abs( linearDistance ) < bestNodes.peek()[ 1 ] ) {
if ( bestChild === node.left ) {
otherChild = node.right;
} else {
otherChild = node.left;
}
if ( otherChild !== null ) {
nearestSearch( otherChild );
}
}
}
if ( maxDistance ) {
for ( i = 0; i < maxNodes; i += 1 ) {
bestNodes.push( [ null, maxDistance ] );
}
}
nearestSearch( self.root );
result = [];
for ( i = 0; i < maxNodes; i += 1 ) {
if ( bestNodes.content[ i ][ 0 ] ) {
result.push( [ bestNodes.content[ i ][ 0 ], bestNodes.content[ i ][ 1 ] ] );
}
}
return result;
};
};
/**
* If you need to free up additional memory and agree with an additional O( log n ) traversal time you can get rid of "depth" and "pos" in Node:
* Depth can be easily done by adding 1 for every parent (care: root node has depth 0, not 1)
* Pos is a bit tricky: Assuming the tree is balanced (which is the case when after we built it up), perform the following steps:
* By traversing to the root store the path e.g. in a bit pattern (01001011, 0 is left, 1 is right)
* From buildTree we know that "median = Math.floor( plength / 2 );", therefore for each bit...
* 0: amountOfNodesRelevantForUs = Math.floor( (pamountOfNodesRelevantForUs - 1) / 2 );
* 1: amountOfNodesRelevantForUs = Math.ceil( (pamountOfNodesRelevantForUs - 1) / 2 );
* pos += Math.floor( (pamountOfNodesRelevantForUs - 1) / 2 );
* when recursion done, we still need to add all left children of target node:
* pos += Math.floor( (pamountOfNodesRelevantForUs - 1) / 2 );
* and I think you need to +1 for the current position, not sure.. depends, try it out ^^
*
* I experienced that for 200'000 nodes you can get rid of 4 MB memory each, leading to 8 MB memory saved.
*/
THREE.TypedArrayUtils.Kdtree.prototype.Node = function ( obj, depth, parent, pos ) {
this.obj = obj;
this.left = null;
this.right = null;
this.parent = parent;
this.depth = depth;
this.pos = pos;
};
/**
* Binary heap implementation
* @author http://eloquentjavascript.net/appendix2.htm
*/
THREE.TypedArrayUtils.Kdtree.BinaryHeap = function ( scoreFunction ) {
this.content = [];
this.scoreFunction = scoreFunction;
};
THREE.TypedArrayUtils.Kdtree.BinaryHeap.prototype = {
push: function ( element ) {
// Add the new element to the end of the array.
this.content.push( element );
// Allow it to bubble up.
this.bubbleUp( this.content.length - 1 );
},
pop: function () {
// Store the first element so we can return it later.
var result = this.content[ 0 ];
// Get the element at the end of the array.
var end = this.content.pop();
// If there are any elements left, put the end element at the
// start, and let it sink down.
if ( this.content.length > 0 ) {
this.content[ 0 ] = end;
this.sinkDown( 0 );
}
return result;
},
peek: function () {
return this.content[ 0 ];
},
remove: function ( node ) {
var len = this.content.length;
// To remove a value, we must search through the array to find it.
for ( var i = 0; i < len; i ++ ) {
if ( this.content[ i ] == node ) {
// When it is found, the process seen in 'pop' is repeated
// to fill up the hole.
var end = this.content.pop();
if ( i != len - 1 ) {
this.content[ i ] = end;
if ( this.scoreFunction( end ) < this.scoreFunction( node ) ) {
this.bubbleUp( i );
} else {
this.sinkDown( i );
}
}
return;
}
}
throw new Error( "Node not found." );
},
size: function () {
return this.content.length;
},
bubbleUp: function ( n ) {
// Fetch the element that has to be moved.
var element = this.content[ n ];
// When at 0, an element can not go up any further.
while ( n > 0 ) {
// Compute the parent element's index, and fetch it.
var parentN = Math.floor( ( n + 1 ) / 2 ) - 1,
parent = this.content[ parentN ];
// Swap the elements if the parent is greater.
if ( this.scoreFunction( element ) < this.scoreFunction( parent ) ) {
this.content[ parentN ] = element;
this.content[ n ] = parent;
// Update 'n' to continue at the new position.
n = parentN;
} else {
// Found a parent that is less, no need to move it further.
break;
}
}
},
sinkDown: function ( n ) {
// Look up the target element and its score.
var length = this.content.length,
element = this.content[ n ],
elemScore = this.scoreFunction( element );
while ( true ) {
// Compute the indices of the child elements.
var child2N = ( n + 1 ) * 2, child1N = child2N - 1;
// This is used to store the new position of the element, if any.
var swap = null;
// If the first child exists (is inside the array)...
if ( child1N < length ) {
// Look it up and compute its score.
var child1 = this.content[ child1N ],
child1Score = this.scoreFunction( child1 );
// If the score is less than our element's, we need to swap.
if ( child1Score < elemScore ) swap = child1N;
}
// Do the same checks for the other child.
if ( child2N < length ) {
var child2 = this.content[ child2N ],
child2Score = this.scoreFunction( child2 );
if ( child2Score < ( swap === null ? elemScore : child1Score ) ) swap = child2N;
}
// If the element needs to be moved, swap it, and continue.
if ( swap !== null ) {
this.content[ n ] = this.content[ swap ];
this.content[ swap ] = element;
n = swap;
} else {
// Otherwise, we are done.
break;
}
}
}
};

141
node_modules/three/examples/js/UCSCharacter.js generated vendored Normal file
View File

@@ -0,0 +1,141 @@
THREE.UCSCharacter = function() {
var scope = this;
var mesh;
this.scale = 1;
this.root = new THREE.Object3D();
this.numSkins = undefined;
this.numMorphs = undefined;
this.skins = [];
this.materials = [];
this.morphs = [];
this.mixer = new THREE.AnimationMixer( this.root );
this.onLoadComplete = function () {};
this.loadCounter = 0;
this.loadParts = function ( config ) {
this.numSkins = config.skins.length;
this.numMorphs = config.morphs.length;
// Character geometry + number of skins
this.loadCounter = 1 + config.skins.length;
// SKINS
this.skins = loadTextures( config.baseUrl + "skins/", config.skins );
this.materials = createMaterials( this.skins );
// MORPHS
this.morphs = config.morphs;
// CHARACTER
var loader = new THREE.JSONLoader();
console.log( config.baseUrl + config.character );
loader.load( config.baseUrl + config.character, function( geometry ) {
geometry.computeBoundingBox();
geometry.computeVertexNormals();
mesh = new THREE.SkinnedMesh( geometry, new THREE.MultiMaterial() );
mesh.name = config.character;
scope.root.add( mesh );
var bb = geometry.boundingBox;
scope.root.scale.set( config.s, config.s, config.s );
scope.root.position.set( config.x, config.y - bb.min.y * config.s, config.z );
mesh.castShadow = true;
mesh.receiveShadow = true;
scope.mixer.clipAction( geometry.animations[0], mesh ).play();
scope.setSkin( 0 );
scope.checkLoadComplete();
} );
};
this.setSkin = function( index ) {
if ( mesh && scope.materials ) {
mesh.material = scope.materials[ index ];
}
};
this.updateMorphs = function( influences ) {
if ( mesh ) {
for ( var i = 0; i < scope.numMorphs; i ++ ) {
mesh.morphTargetInfluences[ i ] = influences[ scope.morphs[ i ] ] / 100;
}
}
};
function loadTextures( baseUrl, textureUrls ) {
var textureLoader = new THREE.TextureLoader();
var textures = [];
for ( var i = 0; i < textureUrls.length; i ++ ) {
textures[ i ] = textureLoader.load( baseUrl + textureUrls[ i ], scope.checkLoadComplete );
textures[ i ].mapping = THREE.UVMapping;
textures[ i ].name = textureUrls[ i ];
}
return textures;
}
function createMaterials( skins ) {
var materials = [];
for ( var i = 0; i < skins.length; i ++ ) {
materials[ i ] = new THREE.MeshLambertMaterial( {
color: 0xeeeeee,
specular: 10.0,
map: skins[ i ],
skinning: true,
morphTargets: true
} );
}
return materials;
}
this.checkLoadComplete = function () {
scope.loadCounter -= 1;
if ( scope.loadCounter === 0 ) {
scope.onLoadComplete();
}
}
};

447
node_modules/three/examples/js/Volume.js generated vendored Normal file
View File

@@ -0,0 +1,447 @@
/**
* This class had been written to handle the output of the NRRD loader.
* It contains a volume of data and informations about it.
* For now it only handles 3 dimensional data.
* See the webgl_loader_nrrd.html example and the loaderNRRD.js file to see how to use this class.
* @class
* @author Valentin Demeusy / https://github.com/stity
* @param {number} xLength Width of the volume
* @param {number} yLength Length of the volume
* @param {number} zLength Depth of the volume
* @param {string} type The type of data (uint8, uint16, ...)
* @param {ArrayBuffer} arrayBuffer The buffer with volume data
*/
THREE.Volume = function( xLength, yLength, zLength, type, arrayBuffer ) {
if ( arguments.length > 0 ) {
/**
* @member {number} xLength Width of the volume in the IJK coordinate system
*/
this.xLength = Number( xLength ) || 1;
/**
* @member {number} yLength Height of the volume in the IJK coordinate system
*/
this.yLength = Number( yLength ) || 1;
/**
* @member {number} zLength Depth of the volume in the IJK coordinate system
*/
this.zLength = Number( zLength ) || 1;
/**
* @member {TypedArray} data Data of the volume
*/
switch ( type ) {
case 'Uint8' :
case 'uint8' :
case 'uchar' :
case 'unsigned char' :
case 'uint8_t' :
this.data = new Uint8Array( arrayBuffer );
break;
case 'Int8' :
case 'int8' :
case 'signed char' :
case 'int8_t' :
this.data = new Int8Array( arrayBuffer );
break;
case 'Int16' :
case 'int16' :
case 'short' :
case 'short int' :
case 'signed short' :
case 'signed short int' :
case 'int16_t' :
this.data = new Int16Array( arrayBuffer );
break;
case 'Uint16' :
case 'uint16' :
case 'ushort' :
case 'unsigned short' :
case 'unsigned short int' :
case 'uint16_t' :
this.data = new Uint16Array( arrayBuffer );
break;
case 'Int32' :
case 'int32' :
case 'int' :
case 'signed int' :
case 'int32_t' :
this.data = new Int32Array( arrayBuffer );
break;
case 'Uint32' :
case 'uint32' :
case 'uint' :
case 'unsigned int' :
case 'uint32_t' :
this.data = new Uint32Array( arrayBuffer );
break;
case 'longlong' :
case 'long long' :
case 'long long int' :
case 'signed long long' :
case 'signed long long int' :
case 'int64' :
case 'int64_t' :
case 'ulonglong' :
case 'unsigned long long' :
case 'unsigned long long int' :
case 'uint64' :
case 'uint64_t' :
throw 'Error in THREE.Volume constructor : this type is not supported in JavaScript';
break;
case 'Float32' :
case 'float32' :
case 'float' :
this.data = new Float32Array( arrayBuffer );
break;
case 'Float64' :
case 'float64' :
case 'double' :
this.data = new Float64Array( arrayBuffer );
break;
default :
this.data = new Uint8Array( arrayBuffer );
}
if ( this.data.length !== this.xLength * this.yLength * this.zLength ) {
throw 'Error in THREE.Volume constructor, lengths are not matching arrayBuffer size';
}
}
/**
* @member {Array} spacing Spacing to apply to the volume from IJK to RAS coordinate system
*/
this.spacing = [ 1, 1, 1 ];
/**
* @member {Array} offset Offset of the volume in the RAS coordinate system
*/
this.offset = [ 0, 0, 0 ];
/**
* @member {THREE.Martrix3} matrix The IJK to RAS matrix
*/
this.matrix = new THREE.Matrix3();
this.matrix.identity();
/**
* @member {THREE.Martrix3} inverseMatrix The RAS to IJK matrix
*/
/**
* @member {number} lowerThreshold The voxels with values under this threshold won't appear in the slices.
* If changed, geometryNeedsUpdate is automatically set to true on all the slices associated to this volume
*/
var lowerThreshold = - Infinity;
Object.defineProperty( this, 'lowerThreshold', {
get : function() {
return lowerThreshold;
},
set : function( value ) {
lowerThreshold = value;
this.sliceList.forEach( function( slice ) {
slice.geometryNeedsUpdate = true
} );
}
} );
/**
* @member {number} upperThreshold The voxels with values over this threshold won't appear in the slices.
* If changed, geometryNeedsUpdate is automatically set to true on all the slices associated to this volume
*/
var upperThreshold = Infinity;
Object.defineProperty( this, 'upperThreshold', {
get : function() {
return upperThreshold;
},
set : function( value ) {
upperThreshold = value;
this.sliceList.forEach( function( slice ) {
slice.geometryNeedsUpdate = true;
} );
}
} );
/**
* @member {Array} sliceList The list of all the slices associated to this volume
*/
this.sliceList = [];
/**
* @member {Array} RASDimensions This array holds the dimensions of the volume in the RAS space
*/
};
THREE.Volume.prototype = {
constructor : THREE.Volume,
/**
* @member {Function} getData Shortcut for data[access(i,j,k)]
* @memberof THREE.Volume
* @param {number} i First coordinate
* @param {number} j Second coordinate
* @param {number} k Third coordinate
* @returns {number} value in the data array
*/
getData : function( i, j, k ) {
return this.data[ k * this.xLength * this.yLength + j * this.xLength + i ];
},
/**
* @member {Function} access compute the index in the data array corresponding to the given coordinates in IJK system
* @memberof THREE.Volume
* @param {number} i First coordinate
* @param {number} j Second coordinate
* @param {number} k Third coordinate
* @returns {number} index
*/
access : function( i, j, k ) {
return k * this.xLength * this.yLength + j * this.xLength + i;
},
/**
* @member {Function} reverseAccess Retrieve the IJK coordinates of the voxel corresponding of the given index in the data
* @memberof THREE.Volume
* @param {number} index index of the voxel
* @returns {Array} [x,y,z]
*/
reverseAccess : function( index ) {
var z = Math.floor( index / ( this.yLength * this.xLength ) );
var y = Math.floor( ( index - z * this.yLength * this.xLength ) / this.xLength );
var x = index - z * this.yLength * this.xLength - y * this.xLength;
return [ x, y, z ];
},
/**
* @member {Function} map Apply a function to all the voxels, be careful, the value will be replaced
* @memberof THREE.Volume
* @param {Function} functionToMap A function to apply to every voxel, will be called with the following parameters :
* value of the voxel
* index of the voxel
* the data (TypedArray)
* @param {Object} context You can specify a context in which call the function, default if this Volume
* @returns {THREE.Volume} this
*/
map : function( functionToMap, context ) {
var length = this.data.length;
context = context || this;
for ( var i = 0; i < length; i ++ ) {
this.data[ i ] = functionToMap.call( context, this.data[ i ], i, this.data );
}
return this;
},
/**
* @member {Function} extractPerpendicularPlane Compute the orientation of the slice and returns all the information relative to the geometry such as sliceAccess, the plane matrix (orientation and position in RAS coordinate) and the dimensions of the plane in both coordinate system.
* @memberof THREE.Volume
* @param {string} axis the normal axis to the slice 'x' 'y' or 'z'
* @param {number} index the index of the slice
* @returns {Object} an object containing all the usefull information on the geometry of the slice
*/
extractPerpendicularPlane : function( axis, RASIndex ) {
var iLength,
jLength,
sliceAccess,
planeMatrix = ( new THREE.Matrix4() ).identity(),
volume = this,
planeWidth,
planeHeight,
firstSpacing,
secondSpacing,
positionOffset,
IJKIndex;
var axisInIJK = new THREE.Vector3(),
firstDirection = new THREE.Vector3(),
secondDirection = new THREE.Vector3();
var dimensions = new THREE.Vector3( this.xLength, this.yLength, this.zLength );
switch ( axis ) {
case 'x' :
axisInIJK.set( 1, 0, 0 );
firstDirection.set( 0, 0, - 1 );
secondDirection.set( 0, - 1, 0 );
firstSpacing = this.spacing[ 2 ];
secondSpacing = this.spacing[ 1 ];
IJKIndex = new THREE.Vector3( RASIndex, 0, 0 );
planeMatrix.multiply( ( new THREE.Matrix4() ).makeRotationY( Math.PI / 2 ) );
positionOffset = ( volume.RASDimensions[ 0 ] - 1 ) / 2;
planeMatrix.setPosition( new THREE.Vector3( RASIndex - positionOffset, 0, 0 ) );
break;
case 'y' :
axisInIJK.set( 0, 1, 0 );
firstDirection.set( 1, 0, 0 );
secondDirection.set( 0, 0, 1 );
firstSpacing = this.spacing[ 0 ];
secondSpacing = this.spacing[ 2 ];
IJKIndex = new THREE.Vector3( 0, RASIndex, 0 );
planeMatrix.multiply( ( new THREE.Matrix4() ).makeRotationX( - Math.PI / 2 ) );
positionOffset = ( volume.RASDimensions[ 1 ] - 1 ) / 2;
planeMatrix.setPosition( new THREE.Vector3( 0, RASIndex - positionOffset, 0 ) );
break;
case 'z' :
default :
axisInIJK.set( 0, 0, 1 );
firstDirection.set( 1, 0, 0 );
secondDirection.set( 0, - 1, 0 );
firstSpacing = this.spacing[ 0 ];
secondSpacing = this.spacing[ 1 ];
IJKIndex = new THREE.Vector3( 0, 0, RASIndex );
positionOffset = ( volume.RASDimensions[ 2 ] - 1 ) / 2;
planeMatrix.setPosition( new THREE.Vector3( 0, 0, RASIndex - positionOffset ) );
break;
}
firstDirection.applyMatrix4( volume.inverseMatrix ).normalize();
firstDirection.argVar = 'i';
secondDirection.applyMatrix4( volume.inverseMatrix ).normalize();
secondDirection.argVar = 'j';
axisInIJK.applyMatrix4( volume.inverseMatrix ).normalize();
iLength = Math.floor( Math.abs( firstDirection.dot( dimensions ) ) );
jLength = Math.floor( Math.abs( secondDirection.dot( dimensions ) ) );
planeWidth = Math.abs( iLength * firstSpacing );
planeHeight = Math.abs( jLength * secondSpacing );
IJKIndex = Math.abs( Math.round( IJKIndex.applyMatrix4( volume.inverseMatrix ).dot( axisInIJK ) ) );
var base = [ new THREE.Vector3( 1, 0, 0 ), new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, 0, 1 ) ];
var iDirection = [ firstDirection, secondDirection, axisInIJK ].find( function( x ) {
return Math.abs( x.dot( base[ 0 ] ) ) > 0.9;
} );
var jDirection = [ firstDirection, secondDirection, axisInIJK ].find( function( x ) {
return Math.abs( x.dot( base[ 1 ] ) ) > 0.9;
} );
var kDirection = [ firstDirection, secondDirection, axisInIJK ].find( function( x ) {
return Math.abs( x.dot( base[ 2 ] ) ) > 0.9;
} );
var argumentsWithInversion = [ 'volume.xLength-1-', 'volume.yLength-1-', 'volume.zLength-1-' ];
var arguments = [ 'i', 'j', 'k' ];
var argArray = [ iDirection, jDirection, kDirection ].map( function( direction, n ) {
return ( direction.dot( base[ n ] ) > 0 ? '' : argumentsWithInversion[ n ] ) + ( direction === axisInIJK ? 'IJKIndex' : direction.argVar )
} );
var argString = argArray.join( ',' );
sliceAccess = eval( '(function sliceAccess (i,j) {return volume.access( ' + argString + ');})' );
return {
iLength : iLength,
jLength : jLength,
sliceAccess : sliceAccess,
matrix : planeMatrix,
planeWidth : planeWidth,
planeHeight : planeHeight
}
},
/**
* @member {Function} extractSlice Returns a slice corresponding to the given axis and index
* The coordinate are given in the Right Anterior Superior coordinate format
* @memberof THREE.Volume
* @param {string} axis the normal axis to the slice 'x' 'y' or 'z'
* @param {number} index the index of the slice
* @returns {THREE.VolumeSlice} the extracted slice
*/
extractSlice : function( axis, index ) {
var slice = new THREE.VolumeSlice( this, index, axis );
this.sliceList.push( slice );
return slice;
},
/**
* @member {Function} repaintAllSlices Call repaint on all the slices extracted from this volume
* @see THREE.VolumeSlice.repaint
* @memberof THREE.Volume
* @returns {THREE.Volume} this
*/
repaintAllSlices : function() {
this.sliceList.forEach( function( slice ) {
slice.repaint();
} );
return this;
},
/**
* @member {Function} computeMinMax Compute the minimum and the maximum of the data in the volume
* @memberof THREE.Volume
* @returns {Array} [min,max]
*/
computeMinMax : function() {
var min = Infinity;
var max = - Infinity;
// buffer the length
var datasize = this.data.length;
var i = 0;
for ( i = 0; i < datasize; i ++ ) {
if ( ! isNaN( this.data[ i ] ) ) {
var value = this.data[ i ];
min = Math.min( min, value );
max = Math.max( max, value );
}
}
this.min = min;
this.max = max;
return [ min, max ];
}
};

217
node_modules/three/examples/js/VolumeSlice.js generated vendored Normal file
View File

@@ -0,0 +1,217 @@
/**
* This class has been made to hold a slice of a volume data
* @class
* @author Valentin Demeusy / https://github.com/stity
* @param {THREE.Volume} volume The associated volume
* @param {number} [index=0] The index of the slice
* @param {string} [axis='z'] For now only 'x', 'y' or 'z' but later it will change to a normal vector
* @see THREE.Volume
*/
THREE.VolumeSlice = function( volume, index, axis ) {
var slice = this;
/**
* @member {THREE.Volume} volume The associated volume
*/
this.volume = volume;
/**
* @member {Number} index The index of the slice, if changed, will automatically call updateGeometry at the next repaint
*/
index = index || 0;
Object.defineProperty( this, 'index', {
get : function() {
return index;
},
set : function( value ) {
index = value;
slice.geometryNeedsUpdate = true;
return index;
}
} );
/**
* @member {String} axis The normal axis
*/
this.axis = axis || 'z';
/**
* @member {HTMLCanvasElement} canvas The final canvas used for the texture
*/
/**
* @member {CanvasRenderingContext2D} ctx Context of the canvas
*/
this.canvas = document.createElement( 'canvas' );
/**
* @member {HTMLCanvasElement} canvasBuffer The intermediary canvas used to paint the data
*/
/**
* @member {CanvasRenderingContext2D} ctxBuffer Context of the canvas buffer
*/
this.canvasBuffer = document.createElement( 'canvas' );
this.updateGeometry();
var canvasMap = new THREE.Texture( this.canvas );
canvasMap.minFilter = THREE.LinearFilter;
canvasMap.wrapS = canvasMap.wrapT = THREE.ClampToEdgeWrapping;
var material = new THREE.MeshBasicMaterial( { map: canvasMap, side: THREE.DoubleSide, transparent : true } );
/**
* @member {THREE.Mesh} mesh The mesh ready to get used in the scene
*/
this.mesh = new THREE.Mesh( this.geometry, material );
/**
* @member {Boolean} geometryNeedsUpdate If set to true, updateGeometry will be triggered at the next repaint
*/
this.geometryNeedsUpdate = true;
this.repaint();
/**
* @member {Number} iLength Width of slice in the original coordinate system, corresponds to the width of the buffer canvas
*/
/**
* @member {Number} jLength Height of slice in the original coordinate system, corresponds to the height of the buffer canvas
*/
/**
* @member {Function} sliceAccess Function that allow the slice to access right data
* @see THREE.Volume.extractPerpendicularPlane
* @param {Number} i The first coordinate
* @param {Number} j The second coordinate
* @returns {Number} the index corresponding to the voxel in volume.data of the given position in the slice
*/
};
THREE.VolumeSlice.prototype = {
constructor : THREE.VolumeSlice,
/**
* @member {Function} repaint Refresh the texture and the geometry if geometryNeedsUpdate is set to true
* @memberof THREE.VolumeSlice
*/
repaint : function() {
if ( this.geometryNeedsUpdate ) {
this.updateGeometry();
}
var iLength = this.iLength,
jLength = this.jLength,
sliceAccess = this.sliceAccess,
volume = this.volume,
axis = this.axis,
index = this.index,
canvas = this.canvasBuffer,
ctx = this.ctxBuffer;
// get the imageData and pixel array from the canvas
var imgData = ctx.getImageData( 0, 0, iLength, jLength );
var data = imgData.data;
var volumeData = volume.data;
var upperThreshold = volume.upperThreshold;
var lowerThreshold = volume.lowerThreshold;
var windowLow = volume.windowLow;
var windowHigh = volume.windowHigh;
// manipulate some pixel elements
var pixelCount = 0;
if ( volume.dataType === 'label' ) {
//this part is currently useless but will be used when colortables will be handled
for ( var j = 0; j < jLength; j ++ ) {
for ( var i = 0; i < iLength; i ++ ) {
var label = volumeData[ sliceAccess( i, j ) ];
label = label >= this.colorMap.length ? ( label % this.colorMap.length ) + 1 : label;
var color = this.colorMap[ label ];
data[ 4 * pixelCount ] = ( color >> 24 ) & 0xff;
data[ 4 * pixelCount + 1 ] = ( color >> 16 ) & 0xff;
data[ 4 * pixelCount + 2 ] = ( color >> 8 ) & 0xff;
data[ 4 * pixelCount + 3 ] = color & 0xff;
pixelCount ++;
}
}
}
else {
for ( var j = 0; j < jLength; j ++ ) {
for ( var i = 0; i < iLength; i ++ ) {
var value = volumeData[ sliceAccess( i, j ) ];
var alpha = 0xff;
//apply threshold
alpha = upperThreshold >= value ? ( lowerThreshold <= value ? alpha : 0 ) : 0;
//apply window level
value = Math.floor( 255 * ( value - windowLow ) / ( windowHigh - windowLow ) );
value = value > 255 ? 255 : ( value < 0 ? 0 : value | 0 );
data[ 4 * pixelCount ] = value;
data[ 4 * pixelCount + 1 ] = value;
data[ 4 * pixelCount + 2 ] = value;
data[ 4 * pixelCount + 3 ] = alpha;
pixelCount ++;
}
}
}
ctx.putImageData( imgData, 0, 0 );
this.ctx.drawImage( canvas, 0, 0, iLength, jLength, 0, 0, this.canvas.width, this.canvas.height );
this.mesh.material.map.needsUpdate = true;
},
/**
* @member {Function} Refresh the geometry according to axis and index
* @see THREE.Volume.extractPerpendicularPlane
* @memberof THREE.VolumeSlice
*/
updateGeometry : function() {
var extracted = this.volume.extractPerpendicularPlane( this.axis, this.index );
this.sliceAccess = extracted.sliceAccess;
this.jLength = extracted.jLength;
this.iLength = extracted.iLength;
this.matrix = extracted.matrix;
this.canvas.width = extracted.planeWidth;
this.canvas.height = extracted.planeHeight;
this.canvasBuffer.width = this.iLength;
this.canvasBuffer.height = this.jLength;
this.ctx = this.canvas.getContext( '2d' );
this.ctxBuffer = this.canvasBuffer.getContext( '2d' );
this.geometry = new THREE.PlaneGeometry( extracted.planeWidth, extracted.planeHeight );
if ( this.mesh ) {
this.mesh.geometry = this.geometry;
//reset mesh matrix
this.mesh.matrix = ( new THREE.Matrix4() ).identity();
this.mesh.applyMatrix( this.matrix );
}
this.geometryNeedsUpdate = false;
}
};

302
node_modules/three/examples/js/WaterShader.js generated vendored Normal file
View File

@@ -0,0 +1,302 @@
/**
* @author jbouny / https://github.com/jbouny
*
* Work based on :
* @author Slayvin / http://slayvin.net : Flat mirror for three.js
* @author Stemkoski / http://www.adelphi.edu/~stemkoski : An implementation of water shader based on the flat mirror
* @author Jonas Wagner / http://29a.ch/ && http://29a.ch/slides/2012/webglwater/ : Water shader explanations in WebGL
*/
THREE.ShaderLib[ 'water' ] = {
uniforms: THREE.UniformsUtils.merge( [
THREE.UniformsLib[ "fog" ], {
"normalSampler": { value: null },
"mirrorSampler": { value: null },
"alpha": { value: 1.0 },
"time": { value: 0.0 },
"distortionScale": { value: 20.0 },
"noiseScale": { value: 1.0 },
"textureMatrix" : { value: new THREE.Matrix4() },
"sunColor": { value: new THREE.Color( 0x7F7F7F ) },
"sunDirection": { value: new THREE.Vector3( 0.70707, 0.70707, 0 ) },
"eye": { value: new THREE.Vector3() },
"waterColor": { value: new THREE.Color( 0x555555 ) }
}
] ),
vertexShader: [
'uniform mat4 textureMatrix;',
'uniform float time;',
'varying vec4 mirrorCoord;',
'varying vec3 worldPosition;',
THREE.ShaderChunk[ "fog_pars_vertex"],
'void main()',
'{',
' mirrorCoord = modelMatrix * vec4( position, 1.0 );',
' worldPosition = mirrorCoord.xyz;',
' mirrorCoord = textureMatrix * mirrorCoord;',
' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );',
THREE.ShaderChunk[ "fog_vertex"],
'}'
].join( '\n' ),
fragmentShader: [
'precision highp float;',
'uniform sampler2D mirrorSampler;',
'uniform float alpha;',
'uniform float time;',
'uniform float distortionScale;',
'uniform sampler2D normalSampler;',
'uniform vec3 sunColor;',
'uniform vec3 sunDirection;',
'uniform vec3 eye;',
'uniform vec3 waterColor;',
'varying vec4 mirrorCoord;',
'varying vec3 worldPosition;',
'vec4 getNoise( vec2 uv )',
'{',
' vec2 uv0 = ( uv / 103.0 ) + vec2(time / 17.0, time / 29.0);',
' vec2 uv1 = uv / 107.0-vec2( time / -19.0, time / 31.0 );',
' vec2 uv2 = uv / vec2( 8907.0, 9803.0 ) + vec2( time / 101.0, time / 97.0 );',
' vec2 uv3 = uv / vec2( 1091.0, 1027.0 ) - vec2( time / 109.0, time / -113.0 );',
' vec4 noise = texture2D( normalSampler, uv0 ) +',
' texture2D( normalSampler, uv1 ) +',
' texture2D( normalSampler, uv2 ) +',
' texture2D( normalSampler, uv3 );',
' return noise * 0.5 - 1.0;',
'}',
'void sunLight( const vec3 surfaceNormal, const vec3 eyeDirection, float shiny, float spec, float diffuse, inout vec3 diffuseColor, inout vec3 specularColor )',
'{',
' vec3 reflection = normalize( reflect( -sunDirection, surfaceNormal ) );',
' float direction = max( 0.0, dot( eyeDirection, reflection ) );',
' specularColor += pow( direction, shiny ) * sunColor * spec;',
' diffuseColor += max( dot( sunDirection, surfaceNormal ), 0.0 ) * sunColor * diffuse;',
'}',
THREE.ShaderChunk[ "common" ],
THREE.ShaderChunk[ "fog_pars_fragment" ],
'void main()',
'{',
' vec4 noise = getNoise( worldPosition.xz );',
' vec3 surfaceNormal = normalize( noise.xzy * vec3( 1.5, 1.0, 1.5 ) );',
' vec3 diffuseLight = vec3(0.0);',
' vec3 specularLight = vec3(0.0);',
' vec3 worldToEye = eye-worldPosition;',
' vec3 eyeDirection = normalize( worldToEye );',
' sunLight( surfaceNormal, eyeDirection, 100.0, 2.0, 0.5, diffuseLight, specularLight );',
' float distance = length(worldToEye);',
' vec2 distortion = surfaceNormal.xz * ( 0.001 + 1.0 / distance ) * distortionScale;',
' vec3 reflectionSample = vec3( texture2D( mirrorSampler, mirrorCoord.xy / mirrorCoord.z + distortion ) );',
' float theta = max( dot( eyeDirection, surfaceNormal ), 0.0 );',
' float rf0 = 0.3;',
' float reflectance = rf0 + ( 1.0 - rf0 ) * pow( ( 1.0 - theta ), 5.0 );',
' vec3 scatter = max( 0.0, dot( surfaceNormal, eyeDirection ) ) * waterColor;',
' vec3 albedo = mix( sunColor * diffuseLight * 0.3 + scatter, ( vec3( 0.1 ) + reflectionSample * 0.9 + reflectionSample * specularLight ), reflectance );',
' vec3 outgoingLight = albedo;',
THREE.ShaderChunk[ "fog_fragment" ],
' gl_FragColor = vec4( outgoingLight, alpha );',
'}'
].join( '\n' )
};
THREE.Water = function ( renderer, camera, scene, options ) {
THREE.Object3D.call( this );
this.name = 'water_' + this.id;
function optionalParameter ( value, defaultValue ) {
return value !== undefined ? value : defaultValue;
}
options = options || {};
this.matrixNeedsUpdate = true;
var width = optionalParameter( options.textureWidth, 512 );
var height = optionalParameter( options.textureHeight, 512 );
this.clipBias = optionalParameter( options.clipBias, 0.0 );
this.alpha = optionalParameter( options.alpha, 1.0 );
this.time = optionalParameter( options.time, 0.0 );
this.normalSampler = optionalParameter( options.waterNormals, null );
this.sunDirection = optionalParameter( options.sunDirection, new THREE.Vector3( 0.70707, 0.70707, 0.0 ) );
this.sunColor = new THREE.Color( optionalParameter( options.sunColor, 0xffffff ) );
this.waterColor = new THREE.Color( optionalParameter( options.waterColor, 0x7F7F7F ) );
this.eye = optionalParameter( options.eye, new THREE.Vector3( 0, 0, 0 ) );
this.distortionScale = optionalParameter( options.distortionScale, 20.0 );
this.side = optionalParameter( options.side, THREE.FrontSide );
this.fog = optionalParameter( options.fog, false );
this.renderer = renderer;
this.scene = scene;
this.mirrorPlane = new THREE.Plane();
this.normal = new THREE.Vector3( 0, 0, 1 );
this.mirrorWorldPosition = new THREE.Vector3();
this.cameraWorldPosition = new THREE.Vector3();
this.rotationMatrix = new THREE.Matrix4();
this.lookAtPosition = new THREE.Vector3( 0, 0, - 1 );
this.clipPlane = new THREE.Vector4();
if ( camera instanceof THREE.PerspectiveCamera ) {
this.camera = camera;
} else {
this.camera = new THREE.PerspectiveCamera();
console.log( this.name + ': camera is not a Perspective Camera!' );
}
this.textureMatrix = new THREE.Matrix4();
this.mirrorCamera = this.camera.clone();
this.renderTarget = new THREE.WebGLRenderTarget( width, height );
this.renderTarget2 = new THREE.WebGLRenderTarget( width, height );
var mirrorShader = THREE.ShaderLib[ "water" ];
var mirrorUniforms = THREE.UniformsUtils.clone( mirrorShader.uniforms );
this.material = new THREE.ShaderMaterial( {
fragmentShader: mirrorShader.fragmentShader,
vertexShader: mirrorShader.vertexShader,
uniforms: mirrorUniforms,
transparent: true,
side: this.side,
fog: this.fog
} );
this.material.uniforms.mirrorSampler.value = this.renderTarget.texture;
this.material.uniforms.textureMatrix.value = this.textureMatrix;
this.material.uniforms.alpha.value = this.alpha;
this.material.uniforms.time.value = this.time;
this.material.uniforms.normalSampler.value = this.normalSampler;
this.material.uniforms.sunColor.value = this.sunColor;
this.material.uniforms.waterColor.value = this.waterColor;
this.material.uniforms.sunDirection.value = this.sunDirection;
this.material.uniforms.distortionScale.value = this.distortionScale;
this.material.uniforms.eye.value = this.eye;
if ( ! THREE.Math.isPowerOfTwo( width ) || ! THREE.Math.isPowerOfTwo( height ) ) {
this.renderTarget.texture.generateMipmaps = false;
this.renderTarget.texture.minFilter = THREE.LinearFilter;
this.renderTarget2.texture.generateMipmaps = false;
this.renderTarget2.texture.minFilter = THREE.LinearFilter;
}
this.updateTextureMatrix();
this.render();
};
THREE.Water.prototype = Object.create( THREE.Mirror.prototype );
THREE.Water.prototype.constructor = THREE.Water;
THREE.Water.prototype.updateTextureMatrix = function () {
function sign( x ) {
return x ? x < 0 ? - 1 : 1 : 0;
}
this.updateMatrixWorld();
this.camera.updateMatrixWorld();
this.mirrorWorldPosition.setFromMatrixPosition( this.matrixWorld );
this.cameraWorldPosition.setFromMatrixPosition( this.camera.matrixWorld );
this.rotationMatrix.extractRotation( this.matrixWorld );
this.normal.set( 0, 0, 1 );
this.normal.applyMatrix4( this.rotationMatrix );
var view = this.mirrorWorldPosition.clone().sub( this.cameraWorldPosition );
view.reflect( this.normal ).negate();
view.add( this.mirrorWorldPosition );
this.rotationMatrix.extractRotation( this.camera.matrixWorld );
this.lookAtPosition.set( 0, 0, - 1 );
this.lookAtPosition.applyMatrix4( this.rotationMatrix );
this.lookAtPosition.add( this.cameraWorldPosition );
var target = this.mirrorWorldPosition.clone().sub( this.lookAtPosition );
target.reflect( this.normal ).negate();
target.add( this.mirrorWorldPosition );
this.up.set( 0, - 1, 0 );
this.up.applyMatrix4( this.rotationMatrix );
this.up.reflect( this.normal ).negate();
this.mirrorCamera.position.copy( view );
this.mirrorCamera.up = this.up;
this.mirrorCamera.lookAt( target );
this.mirrorCamera.aspect = this.camera.aspect;
this.mirrorCamera.updateProjectionMatrix();
this.mirrorCamera.updateMatrixWorld();
this.mirrorCamera.matrixWorldInverse.getInverse( this.mirrorCamera.matrixWorld );
// Update the texture matrix
this.textureMatrix.set( 0.5, 0.0, 0.0, 0.5,
0.0, 0.5, 0.0, 0.5,
0.0, 0.0, 0.5, 0.5,
0.0, 0.0, 0.0, 1.0 );
this.textureMatrix.multiply( this.mirrorCamera.projectionMatrix );
this.textureMatrix.multiply( this.mirrorCamera.matrixWorldInverse );
// Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
// Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
this.mirrorPlane.setFromNormalAndCoplanarPoint( this.normal, this.mirrorWorldPosition );
this.mirrorPlane.applyMatrix4( this.mirrorCamera.matrixWorldInverse );
this.clipPlane.set( this.mirrorPlane.normal.x, this.mirrorPlane.normal.y, this.mirrorPlane.normal.z, this.mirrorPlane.constant );
var q = new THREE.Vector4();
var projectionMatrix = this.mirrorCamera.projectionMatrix;
q.x = ( sign( this.clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
q.y = ( sign( this.clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
q.z = - 1.0;
q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
// Calculate the scaled plane vector
var c = new THREE.Vector4();
c = this.clipPlane.multiplyScalar( 2.0 / this.clipPlane.dot( q ) );
// Replacing the third row of the projection matrix
projectionMatrix.elements[ 2 ] = c.x;
projectionMatrix.elements[ 6 ] = c.y;
projectionMatrix.elements[ 10 ] = c.z + 1.0 - this.clipBias;
projectionMatrix.elements[ 14 ] = c.w;
var worldCoordinates = new THREE.Vector3();
worldCoordinates.setFromMatrixPosition( this.camera.matrixWorld );
this.eye = worldCoordinates;
this.material.uniforms.eye.value = this.eye;
};

417
node_modules/three/examples/js/animation/CCDIKSolver.js generated vendored Normal file
View File

@@ -0,0 +1,417 @@
/**
* @author takahiro / https://github.com/takahirox
*
* CCD Algorithm
* https://sites.google.com/site/auraliusproject/ccd-algorithm
*
* mesh.geometry needs to have iks array.
*
* // ik parameter example
* //
* // target, effector, index in links are bone index in skeleton.
* // the bones relation should be
* // <-- parent child -->
* // links[ n ], links[ n - 1 ], ..., links[ 0 ], effector
* ik = {
* target: 1,
* effector: 2,
* links: [ { index: 5, limitation: new THREE.Vector3( 1, 0, 0 ) }, { index: 4, enabled: false }, { index : 3 } ],
* iteration: 10,
* minAngle: 0.0,
* maxAngle: 1.0,
* };
*/
THREE.CCDIKSolver = function ( mesh ) {
this.mesh = mesh;
this._valid();
};
THREE.CCDIKSolver.prototype = {
constructor: THREE.CCDIKSolver,
_valid: function () {
var iks = this.mesh.geometry.iks;
var bones = this.mesh.skeleton.bones;
for ( var i = 0, il = iks.length; i < il; i ++ ) {
var ik = iks[ i ];
var effector = bones[ ik.effector ];
var links = ik.links;
var link0, link1;
link0 = effector;
for ( var j = 0, jl = links.length; j < jl; j ++ ) {
link1 = bones[ links[ j ].index ];
if ( link0.parent !== link1 ) {
console.warn( 'THREE.CCDIKSolver: bone ' + link0.name + ' is not the child of bone ' + link1.name );
}
link0 = link1;
}
}
},
/*
* save the bone matrices before solving IK.
* they're used for generating VMD and VPD.
*/
_saveOriginalBonesInfo: function () {
var bones = this.mesh.skeleton.bones;
for ( var i = 0, il = bones.length; i < il; i ++ ) {
var bone = bones[ i ];
if ( bone.userData.ik === undefined ) bone.userData.ik = {};
bone.userData.ik.originalMatrix = bone.matrix.toArray();
}
},
update: function ( saveOriginalBones ) {
var q = new THREE.Quaternion();
var targetPos = new THREE.Vector3();
var targetVec = new THREE.Vector3();
var effectorPos = new THREE.Vector3();
var effectorVec = new THREE.Vector3();
var linkPos = new THREE.Vector3();
var invLinkQ = new THREE.Quaternion();
var linkScale = new THREE.Vector3();
var axis = new THREE.Vector3();
var bones = this.mesh.skeleton.bones;
var iks = this.mesh.geometry.iks;
var boneParams = this.mesh.geometry.bones;
// for reference overhead reduction in loop
var math = Math;
this.mesh.updateMatrixWorld( true );
if ( saveOriginalBones === true ) this._saveOriginalBonesInfo();
for ( var i = 0, il = iks.length; i < il; i++ ) {
var ik = iks[ i ];
var effector = bones[ ik.effector ];
var target = bones[ ik.target ];
// don't use getWorldPosition() here for the performance
// because it calls updateMatrixWorld( true ) inside.
targetPos.setFromMatrixPosition( target.matrixWorld );
var links = ik.links;
var iteration = ik.iteration !== undefined ? ik.iteration : 1;
for ( var j = 0; j < iteration; j++ ) {
var rotated = false;
for ( var k = 0, kl = links.length; k < kl; k++ ) {
var link = bones[ links[ k ].index ];
// skip this link and following links.
// this skip is used for MMD performance optimization.
if ( links[ k ].enabled === false ) break;
var limitation = links[ k ].limitation;
// don't use getWorldPosition/Quaternion() here for the performance
// because they call updateMatrixWorld( true ) inside.
link.matrixWorld.decompose( linkPos, invLinkQ, linkScale );
invLinkQ.inverse();
effectorPos.setFromMatrixPosition( effector.matrixWorld );
// work in link world
effectorVec.subVectors( effectorPos, linkPos );
effectorVec.applyQuaternion( invLinkQ );
effectorVec.normalize();
targetVec.subVectors( targetPos, linkPos );
targetVec.applyQuaternion( invLinkQ );
targetVec.normalize();
var angle = targetVec.dot( effectorVec );
if ( angle > 1.0 ) {
angle = 1.0;
} else if ( angle < -1.0 ) {
angle = -1.0;
}
angle = math.acos( angle );
// skip if changing angle is too small to prevent vibration of bone
// Refer to http://www20.atpages.jp/katwat/three.js_r58/examples/mytest37/mmd.three.js
if ( angle < 1e-5 ) continue;
if ( ik.minAngle !== undefined && angle < ik.minAngle ) {
angle = ik.minAngle;
}
if ( ik.maxAngle !== undefined && angle > ik.maxAngle ) {
angle = ik.maxAngle;
}
axis.crossVectors( effectorVec, targetVec );
axis.normalize();
q.setFromAxisAngle( axis, angle );
link.quaternion.multiply( q );
// TODO: re-consider the limitation specification
if ( limitation !== undefined ) {
var c = link.quaternion.w;
if ( c > 1.0 ) {
c = 1.0;
}
var c2 = math.sqrt( 1 - c * c );
link.quaternion.set( limitation.x * c2,
limitation.y * c2,
limitation.z * c2,
c );
}
link.updateMatrixWorld( true );
rotated = true;
}
if ( ! rotated ) break;
}
}
// just in case
this.mesh.updateMatrixWorld( true );
}
};
THREE.CCDIKHelper = function ( mesh ) {
if ( mesh.geometry.iks === undefined || mesh.skeleton === undefined ) {
throw 'THREE.CCDIKHelper requires iks in mesh.geometry and skeleton in mesh.';
}
THREE.Object3D.call( this );
this.root = mesh;
this.matrix = mesh.matrixWorld;
this.matrixAutoUpdate = false;
this.sphereGeometry = new THREE.SphereBufferGeometry( 0.25, 16, 8 );
this.targetSphereMaterial = new THREE.MeshBasicMaterial( {
color: new THREE.Color( 0xff8888 ),
depthTest: false,
depthWrite: false,
transparent: true
} );
this.effectorSphereMaterial = new THREE.MeshBasicMaterial( {
color: new THREE.Color( 0x88ff88 ),
depthTest: false,
depthWrite: false,
transparent: true
} );
this.linkSphereMaterial = new THREE.MeshBasicMaterial( {
color: new THREE.Color( 0x8888ff ),
depthTest: false,
depthWrite: false,
transparent: true
} );
this.lineMaterial = new THREE.LineBasicMaterial( {
color: new THREE.Color( 0xff0000 ),
depthTest: false,
depthWrite: false,
transparent: true
} );
this._init();
this.update();
};
THREE.CCDIKHelper.prototype = Object.create( THREE.Object3D.prototype );
THREE.CCDIKHelper.prototype.constructor = THREE.CCDIKHelper;
THREE.CCDIKHelper.prototype._init = function () {
var self = this;
var mesh = this.root;
var iks = mesh.geometry.iks;
function createLineGeometry( ik ) {
var geometry = new THREE.BufferGeometry();
var vertices = new Float32Array( ( 2 + ik.links.length ) * 3 );
geometry.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
return geometry;
}
function createTargetMesh() {
return new THREE.Mesh( self.sphereGeometry, self.targetSphereMaterial );
}
function createEffectorMesh() {
return new THREE.Mesh( self.sphereGeometry, self.effectorSphereMaterial );
}
function createLinkMesh() {
return new THREE.Mesh( self.sphereGeometry, self.linkSphereMaterial );
}
function createLine( ik ) {
return new THREE.Line( createLineGeometry( ik ), self.lineMaterial );
}
for ( var i = 0, il = iks.length; i < il; i ++ ) {
var ik = iks[ i ];
this.add( createTargetMesh() );
this.add( createEffectorMesh() );
for ( var j = 0, jl = ik.links.length; j < jl; j ++ ) {
this.add( createLinkMesh() );
}
this.add( createLine( ik ) );
}
};
THREE.CCDIKHelper.prototype.update = function () {
var offset = 0;
var mesh = this.root;
var iks = mesh.geometry.iks;
var bones = mesh.skeleton.bones;
var matrixWorldInv = new THREE.Matrix4().getInverse( mesh.matrixWorld );
var vector = new THREE.Vector3();
function getPosition( bone ) {
vector.setFromMatrixPosition( bone.matrixWorld );
vector.applyMatrix4( matrixWorldInv );
return vector;
}
function setPositionOfBoneToAttributeArray( array, index, bone ) {
var v = getPosition( bone );
array[ index * 3 + 0 ] = v.x;
array[ index * 3 + 1 ] = v.y;
array[ index * 3 + 2 ] = v.z;
}
for ( var i = 0, il = iks.length; i < il; i ++ ) {
var ik = iks[ i ];
var targetBone = bones[ ik.target ];
var effectorBone = bones[ ik.effector ];
var targetMesh = this.children[ offset ++ ];
var effectorMesh = this.children[ offset ++ ];
targetMesh.position.copy( getPosition( targetBone ) );
effectorMesh.position.copy( getPosition( effectorBone ) );
for ( var j = 0, jl = ik.links.length; j < jl; j ++ ) {
var link = ik.links[ j ];
var linkBone = bones[ link.index ];
var linkMesh = this.children[ offset ++ ];
linkMesh.position.copy( getPosition( linkBone ) );
}
var line = this.children[ offset ++ ];
var array = line.geometry.attributes.position.array;
setPositionOfBoneToAttributeArray( array, 0, targetBone );
setPositionOfBoneToAttributeArray( array, 1, effectorBone );
for ( var j = 0, jl = ik.links.length; j < jl; j ++ ) {
var link = ik.links[ j ];
var linkBone = bones[ link.index ];
setPositionOfBoneToAttributeArray( array, j + 2, linkBone );
}
line.geometry.attributes.position.needsUpdate = true;
}
};

1200
node_modules/three/examples/js/animation/MMDPhysics.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,188 @@
/**
* @author mrdoob / http://mrdoob.com/
* @author greggman / http://games.greggman.com/
* @author zz85 / http://www.lab4games.net/zz85/blog
* @author kaypiKun
*/
THREE.CinematicCamera = function( fov, aspect, near, far ) {
THREE.PerspectiveCamera.call( this, fov, aspect, near, far );
this.type = "CinematicCamera";
this.postprocessing = { enabled : true };
this.shaderSettings = {
rings: 3,
samples: 4
};
this.material_depth = new THREE.MeshDepthMaterial();
// In case of cinematicCamera, having a default lens set is important
this.setLens();
this.initPostProcessing();
};
THREE.CinematicCamera.prototype = Object.create( THREE.PerspectiveCamera.prototype );
THREE.CinematicCamera.prototype.constructor = THREE.CinematicCamera;
// providing fnumber and coc(Circle of Confusion) as extra arguments
THREE.CinematicCamera.prototype.setLens = function ( focalLength, filmGauge, fNumber, coc ) {
// In case of cinematicCamera, having a default lens set is important
if ( focalLength === undefined ) focalLength = 35;
if ( filmGauge !== undefined ) this.filmGauge = filmGauge;
this.setFocalLength( focalLength );
// if fnumber and coc are not provided, cinematicCamera tries to act as a basic PerspectiveCamera
if ( fNumber === undefined ) fNumber = 8;
if ( coc === undefined ) coc = 0.019;
this.fNumber = fNumber;
this.coc = coc;
// fNumber is focalLength by aperture
this.aperture = focalLength / this.fNumber;
// hyperFocal is required to calculate depthOfField when a lens tries to focus at a distance with given fNumber and focalLength
this.hyperFocal = ( focalLength * focalLength ) / ( this.aperture * this.coc );
};
THREE.CinematicCamera.prototype.linearize = function ( depth ) {
var zfar = this.far;
var znear = this.near;
return - zfar * znear / ( depth * ( zfar - znear ) - zfar );
};
THREE.CinematicCamera.prototype.smoothstep = function ( near, far, depth ) {
var x = this.saturate( ( depth - near ) / ( far - near ) );
return x * x * ( 3 - 2 * x );
};
THREE.CinematicCamera.prototype.saturate = function ( x ) {
return Math.max( 0, Math.min( 1, x ) );
};
// function for focusing at a distance from the camera
THREE.CinematicCamera.prototype.focusAt = function ( focusDistance ) {
if ( focusDistance === undefined ) focusDistance = 20;
var focalLength = this.getFocalLength();
// distance from the camera (normal to frustrum) to focus on
this.focus = focusDistance;
// the nearest point from the camera which is in focus (unused)
this.nearPoint = ( this.hyperFocal * this.focus ) / ( this.hyperFocal + ( this.focus - focalLength ) );
// the farthest point from the camera which is in focus (unused)
this.farPoint = ( this.hyperFocal * this.focus ) / ( this.hyperFocal - ( this.focus - focalLength ) );
// the gap or width of the space in which is everything is in focus (unused)
this.depthOfField = this.farPoint - this.nearPoint;
// Considering minimum distance of focus for a standard lens (unused)
if ( this.depthOfField < 0 ) this.depthOfField = 0;
this.sdistance = this.smoothstep( this.near, this.far, this.focus );
this.ldistance = this.linearize( 1 - this.sdistance );
this.postprocessing.bokeh_uniforms[ 'focalDepth' ].value = this.ldistance;
};
THREE.CinematicCamera.prototype.initPostProcessing = function () {
if ( this.postprocessing.enabled ) {
this.postprocessing.scene = new THREE.Scene();
this.postprocessing.camera = new THREE.OrthographicCamera( window.innerWidth / - 2, window.innerWidth / 2, window.innerHeight / 2, window.innerHeight / - 2, - 10000, 10000 );
this.postprocessing.scene.add( this.postprocessing.camera );
var pars = { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBFormat };
this.postprocessing.rtTextureDepth = new THREE.WebGLRenderTarget( window.innerWidth, window.innerHeight, pars );
this.postprocessing.rtTextureColor = new THREE.WebGLRenderTarget( window.innerWidth, window.innerHeight, pars );
var bokeh_shader = THREE.BokehShader;
this.postprocessing.bokeh_uniforms = THREE.UniformsUtils.clone( bokeh_shader.uniforms );
this.postprocessing.bokeh_uniforms[ "tColor" ].value = this.postprocessing.rtTextureColor.texture;
this.postprocessing.bokeh_uniforms[ "tDepth" ].value = this.postprocessing.rtTextureDepth.texture;
this.postprocessing.bokeh_uniforms[ "manualdof" ].value = 0;
this.postprocessing.bokeh_uniforms[ "shaderFocus" ].value = 0;
this.postprocessing.bokeh_uniforms[ "fstop" ].value = 2.8;
this.postprocessing.bokeh_uniforms[ "showFocus" ].value = 1;
this.postprocessing.bokeh_uniforms[ "focalDepth" ].value = 0.1;
//console.log( this.postprocessing.bokeh_uniforms[ "focalDepth" ].value );
this.postprocessing.bokeh_uniforms[ "znear" ].value = this.near;
this.postprocessing.bokeh_uniforms[ "zfar" ].value = this.near;
this.postprocessing.bokeh_uniforms[ "textureWidth" ].value = window.innerWidth;
this.postprocessing.bokeh_uniforms[ "textureHeight" ].value = window.innerHeight;
this.postprocessing.materialBokeh = new THREE.ShaderMaterial( {
uniforms: this.postprocessing.bokeh_uniforms,
vertexShader: bokeh_shader.vertexShader,
fragmentShader: bokeh_shader.fragmentShader,
defines: {
RINGS: this.shaderSettings.rings,
SAMPLES: this.shaderSettings.samples
}
} );
this.postprocessing.quad = new THREE.Mesh( new THREE.PlaneBufferGeometry( window.innerWidth, window.innerHeight ), this.postprocessing.materialBokeh );
this.postprocessing.quad.position.z = - 500;
this.postprocessing.scene.add( this.postprocessing.quad );
}
};
THREE.CinematicCamera.prototype.renderCinematic = function ( scene, renderer ) {
if ( this.postprocessing.enabled ) {
renderer.clear();
// Render scene into texture
scene.overrideMaterial = null;
renderer.render( scene, camera, this.postprocessing.rtTextureColor, true );
// Render depth into texture
scene.overrideMaterial = this.material_depth;
renderer.render( scene, camera, this.postprocessing.rtTextureDepth, true );
// Render bokeh composite
renderer.render( this.postprocessing.scene, this.postprocessing.camera );
}
};

Some files were not shown because too many files have changed in this diff Show More